forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB35bdf35Tahinli2 months ago3757 commits

encode.rs23373 lines, 1.0 MiBHistoryRawDownload
1//! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out.
2//!
3//! This is the layer that turns the pieces below it — the intra predictors of
4//! [`crate::intra`], the forward transform and quantizer of
5//! [`crate::transform`], and the tile writer of [`crate::tile`] — into
6//! something that takes a picture. Every block is 32x32 (its chroma 16x16),
7//! which is the subset the tile writer codes, and each one picks its luma mode
8//! from the seven non-directional ones by rate-distortion; chroma searches
9//! its own `uv_mode` over the seven that read no further than the row above
10//! and the column to the left, its transform type derived from that mode the
11//! way the decoder derives it. Block sizes are what a loop above this would
12//! choose between.
13//!
14//! The encoder carries its own reconstruction, because prediction reads it: a
15//! block predicts from the reconstructed samples above and to its left, exactly
16//! as the decoder will. That makes the reconstruction a claim about what a
17//! decoder produces, and it is gated as one — sample for sample against ffmpeg.
18
19use crate::decode::WithRef;
20use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
21use ec_av1_syntax::{
22 CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams,
23 LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode,
24};
25use ec_core::{Error, Result};
26
27use crate::cdf;
28use crate::cdf_state::TxbSet;
29use crate::frame::frame_obu;
30use crate::intra::{
31 D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED,
32 SMOOTH_V_PRED, V_PRED,
33};
34use crate::mc;
35use crate::motion;
36use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16};
37use crate::obu::temporal_delimiter;
38use crate::quant::ac_q;
39use crate::sequence::sequence_header_obu;
40use crate::tile::{
41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
42};
43#[cfg(test)]
44use crate::transform::forward_and_quantize;
45use crate::transform::{
46 TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
47 forward_and_quantize_typed_scaled,
48};
49
50/// The side of the larger of the two luma blocks this encoder codes, in
51/// samples.
52const BLOCK: usize = 32;
53
54/// The side of the smaller one, which a 32x32 block may be split into four of.
55const SUB: usize = 16;
56
57/// The side of a superblock, which is what the partition tree starts from.
58pub(crate) const SUPERBLOCK: usize = 64;
59
60// lane-sb128 r1: the superblock size in samples the intra-reach rules
61// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the
62// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and
63// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128
64// superblock changes every answer inside it (the tables themselves are
65// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
66// stays the encoder's own fixed 64.
67
68/// Sets the superblock size [`Reach`] answers against (64 or 128).
69pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
70 fctx.reach_sb_px.with(|c| c.set(px));
71}
72
73fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
74 fctx.reach_sb_px.with(|c| c.get())
75}
76
77/// [`reach_sb_px`] in 4x4 mode-info units -- libaom's `sb_mi_size` in
78/// `has_top_right`/`has_bottom_left` (`mi_size_high[sb_size]`), which is what
79/// [`Reach::of_tu_chroma`] masks the block's mi position with.
80pub(crate) fn reach_sb_mi(fctx: &crate::decode::FrameCtx) -> usize {
81 reach_sb_px(fctx) / 4
82}
83
84/// `scale_chroma_bsize(bsize, ss_x, ss_y)` (libaom `reconintra.c:1649`,
85/// called from `av1_predict_intra_block` at `:1823`) in 4x4 mode-info units:
86/// the block shape a CHROMA plane's reach is answered against. Only the
87/// BLOCK_4X4 / BLOCK_4X8 / BLOCK_8X4 / BLOCK_4X16 / BLOCK_16X4 family is
88/// remapped -- every other block size passes through, so at `ss (0,0)` and
89/// for any block of 8 or more this is the block's own `(bw/4, bh/4)`.
90pub(crate) fn chroma_mi_shape(bw: usize, bh: usize, ss_x: usize, ss_y: usize) -> (usize, usize) {
91 match (bw, bh, ss_x, ss_y) {
92 // BLOCK_4X4 -> BLOCK_8X8 / BLOCK_8X4 / BLOCK_4X8 / itself.
93 (4, 4, 1, 1) => (2, 2),
94 (4, 4, 1, 0) => (2, 1),
95 (4, 4, 0, 1) => (1, 2),
96 // BLOCK_4X8 -> BLOCK_8X8 / BLOCK_8X8 / BLOCK_4X8 / itself.
97 (4, 8, 1, _) => (2, 2),
98 (4, 8, 0, 1) => (1, 2),
99 // BLOCK_8X4 -> BLOCK_8X8 / BLOCK_8X4 / BLOCK_8X8 / itself.
100 (8, 4, 1, 0) => (2, 1),
101 (8, 4, 1, 1) | (8, 4, 0, 1) => (2, 2),
102 // BLOCK_4X16 -> BLOCK_8X16 / BLOCK_8X16 / BLOCK_4X16 / itself.
103 (4, 16, 1, _) => (2, 4),
104 (4, 16, 0, 1) => (1, 4),
105 // BLOCK_16X4 -> BLOCK_16X8 / BLOCK_16X4 / BLOCK_16X8 / itself.
106 (16, 4, 1, 0) => (4, 1),
107 (16, 4, 1, 1) | (16, 4, 0, 1) => (4, 2),
108 _ => (bw / 4, bh / 4),
109 }
110}
111
112/// How heavily the mode search weighs rate against squared error, in units of
113/// the quantizer's reconstruction step squared per bit.
114///
115/// Swept three times over his clips and three synthetic pictures
116/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
117/// the three lane reports). The first sweep, before the mode symbol was
118/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
119/// third sweep, after the levels were costed through the writer's own CDFs
120/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
121/// on film and -0.20% against -0.14% on screen capture.
122///
123/// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than
124/// those ladders, and 0.1 was far off the point: the rate term was carrying
125/// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom /
126/// vs rav1e for 1080p film, 2160p film, screen capture:
127///
128/// | lambda | 1080p | 2160p | screen |
129/// |--------|-------|-------|--------|
130/// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 |
131/// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 |
132/// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 |
133/// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
134/// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 |
135/// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 |
136/// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 |
137/// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 |
138/// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 |
139///
140/// and on the native 1920x1024 crops, which is the table that decides:
141///
142/// | lambda | film 1080p | film 2160p | screen |
143/// |--------|------------|------------|--------|
144/// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 |
145/// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 |
146/// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 |
147/// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 |
148///
149/// 0.0375 was the best point on two clips of three there and cost the "2160p
150/// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept
151/// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the
152/// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of
153/// whose cells have no intra cost -- no real film supported the point.
154///
155/// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL
156/// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs
157/// libaom / vs rav1e, everything else at the shipped defaults:
158///
159/// | lambda | bars 1080p | bars 2160p | film A | film B | screen |
160/// |--------|------------|------------|--------|--------|--------|
161/// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 |
162/// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 |
163/// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 |
164/// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 |
165/// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 |
166/// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 |
167///
168/// Real film wants roughly HALF the rate weight the bars asked for: the bowl
169/// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep
170/// against the shipped 0.05, while the bars rows walk the other way (they are
171/// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so
172/// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture
173/// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx
174/// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall.
175const LAMBDA_SCALE: f64 = 0.0275;
176
177/// The rate weight a HIDDEN frame (a pyramid ARF, coded but not shown) codes
178/// under, as a multiple of [`LAMBDA_SCALE`] (lane-arfcen).
179///
180/// The ARF-vs-ARF census says our top ARF codes residual over HALF its area
181/// (rav1e's, at the same display position, over 26-30%) and comes out 1.4-2.5x
182/// its bytes at the same PSNR, while every leaf that predicts from it is
183/// still 0.4 dB behind rav1e's -- i.e. the ARF's extra fidelity is bought at
184/// a rate weight fitted on shown frames and does not propagate. This is the
185/// one knob that prices a hidden frame's rate differently from its q, which
186/// the pyramid's q offsets cannot do (they move lambda and step together).
187const HIDDEN_LAMBDA_FACTOR: f64 = 1.0;
188
189/// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build.
190fn hidden_lambda_factor() -> f64 {
191 match std::env::var("EC_AV1_LAMBDA_HIDDEN")
192 .ok()
193 .and_then(|v| v.parse().ok())
194 {
195 Some(f) => f,
196 None => HIDDEN_LAMBDA_FACTOR,
197 }
198}
199
200/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
201/// picks it is the thing running. A release build has no such knob.
202fn lambda_scale() -> f64 {
203 let swept = std::env::var("EC_AV1_LAMBDA")
204 .ok()
205 .and_then(|v| v.parse::<f64>().ok());
206 match swept {
207 Some(scale) if cfg!(test) => scale,
208 _ => LAMBDA_SCALE,
209 }
210}
211
212/// How a key frame's lambda differs from an inter frame's: libaom weighs the
213/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
214/// of 128), because every later frame predicts from the key frame, so an error
215/// left in it is paid for over the whole group. This encoder has no temporal
216/// propagation model at all, and this factor is the cheapest stand-in for one.
217/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
218///
219/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
220/// libaom / vs rav1e:
221///
222/// | k_key | 1080p | 2160p | screen |
223/// |---|---|---|---|
224/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
225/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
226/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
227/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
228///
229/// The two films want the key frame coded finer and the screen capture wants
230/// the opposite, by about the same amount, and at native the whole lever is
231/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
232/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
233/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
234/// per-frame-type weight; the real lever here is temporal propagation
235/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
236/// predict from, not each frame.
237const KEY_LAMBDA_FACTOR: f64 = 1.0;
238
239/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
240fn key_lambda_factor() -> f64 {
241 match std::env::var("EC_AV1_LAMBDA_KEY")
242 .ok()
243 .and_then(|v| v.parse::<f64>().ok())
244 {
245 Some(k) if cfg!(test) => k,
246 _ => KEY_LAMBDA_FACTOR,
247 }
248}
249
250// Every frame's predicted coefficient bits since the last
251// `take_predicted_bits`, in coding order -- the encoder half of
252// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
253#[cfg(test)]
254thread_local! {
255 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
256}
257
258/// Records one frame's predicted coefficient bits.
259#[cfg(test)]
260fn record_predicted_bits(bits: f64) {
261 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
262}
263
264/// Takes (and clears) what the frames encoded on this thread were predicted to
265/// spend on coefficients.
266#[cfg(test)]
267pub(crate) fn take_predicted_bits() -> Vec<f64> {
268 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
269}
270
271/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
272pub(crate) const SPLIT_INTER_8: bool = true;
273
274/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
275/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
276/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
277/// turns it off for an A/B on one build.
278/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
279/// residual as one transform over the whole block or as the four transforms
280/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
281/// intra block inside the inter frame. ON since lane-av1tx2, which found why
282/// the streams desynced -- the writer counted the [`crate::decode::
283/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
284/// reader drops the term -- and measured the split search: BD-rate vs libaom
285/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
286/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
287/// A/B on one build.
288fn tx_select_inter() -> bool {
289 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
290 crate::envflags::var("EC_AV1_TX_SELECT_INTER")
291 .ok()
292 .map(|v| !matches!(v.as_str(), "0" | "off"))
293 });
294 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
295}
296
297/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`, control
298/// vs arm): the capture row goes +27.8/-26.0 -> +20.8/-30.1 -- seven points
299/// against libaom -- while BOTH film rows LOSE (film A +21.7/-4.4 ->
300/// +22.1/-4.0, film B +26.9/-0.6 -> +28.1/+0.7) and 2160p bars lose 0.8/1.1.
301/// The keep rule wants both films down, so this takes the same content gate
302/// palette, intrabc and the angle-delta refinement already stand behind: a
303/// non-screen frame is byte-identical to the encoder before the lane.
304///
305/// The transform types an intra luma transform unit of `set` may be coded
306/// with -- exactly the alphabet the writer's `tx_type` symbol names for that
307/// set, so a searched type is always one the tile can express (lane-txset).
308/// `DCT_DCT` first: it is the incumbent every other candidate has to beat.
309///
310/// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16
311/// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types
312/// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all,
313/// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT`
314/// here.
315pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
316 const DCT: [TxType; 1] = [TxType::DctDct];
317 const INTRA1: [TxType; 7] = [
318 TxType::DctDct,
319 TxType::AdstAdst,
320 TxType::AdstDct,
321 TxType::DctAdst,
322 TxType::Idtx,
323 TxType::VDct,
324 TxType::HDct,
325 ];
326 const INTRA2: [TxType; 5] = [
327 TxType::DctDct,
328 TxType::AdstAdst,
329 TxType::AdstDct,
330 TxType::DctAdst,
331 TxType::Idtx,
332 ];
333 match set {
334 TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 if intra_tx_search_on(screen) => &INTRA2,
335 // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the
336 // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`;
337 // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two
338 // extra members are the 1-D DCTs, and the order is the reader's own
339 // map (`decode::tx_type_from_symbol`, 8-wide CDF).
340 TxbSet::Luma8Set1 | TxbSet::Luma4Set1 if intra_tx_search_on(screen) => &INTRA1,
341 _ => &DCT,
342 }
343}
344
345/// The transform types an INTER luma transform unit of `set` may be coded
346/// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every
347/// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3`
348/// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two
349/// types, a symbol the writer already codes and never varied. 64x64 codes no
350/// `tx_type` symbol at all, so it is not offered one.
351/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`): the
352/// capture row goes +20.8/-30.1 -> +20.1/-30.4 while the two synthetic bars
353/// rows lose TWENTY points (-1.0/-16.8 -> +23.1/+3.3 and +9.4/-12.7 ->
354/// +31.2/+3.7) and film B 0.3 -- the `local-rd-on-references` class at its
355/// loudest, and restricting the offer to 16x16 and below does not soften it
356/// (`le16`: +22.9/+3.1, +31.6/+4.0). So this takes the same content gate the
357/// intra search, palette and intrabc stand behind: a non-screen frame is
358/// byte-identical to the encoder before the lane.
359///
360/// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), `le16`
361/// (16x16 and below, the sizes libaom's own census picks a non-`DCT_DCT`
362/// inter type on -- it never takes `IDTX` at 32x32 on film B), anything else
363/// on for every frame at every size.
364pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
365 const DCT: [TxType; 1] = [TxType::DctDct];
366 const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx];
367 const INTER_WIDE: [TxType; 7] = [
368 TxType::DctDct,
369 TxType::AdstAdst,
370 TxType::AdstDct,
371 TxType::DctAdst,
372 TxType::Idtx,
373 TxType::VDct,
374 TxType::HDct,
375 ];
376 let mode = inter_tx_type_search();
377 let on = match mode {
378 InterTxSearch::Off => false,
379 InterTxSearch::Screen => screen,
380 InterTxSearch::All | InterTxSearch::Le16 => true,
381 };
382 match set {
383 TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3,
384 TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3,
385 // lane-txi: a `reduced_tx_set == 0` frame's inter 16x16 reads the
386 // TWELVE-type `TX_SET_INTER_2` and its 8x8/4x4 `ALL16` (inter 32x32
387 // stays the two-type `DCT_IDTX`). The seven offered here are the
388 // members those two alphabets SHARE with the intra set -- the four
389 // DTT combinations, `IDTX` and the two 1-D DCTs -- which is the
390 // candidate list rav1e's speed 6 prunes to; the FLIPADST family and
391 // the 1-D ADSTs are codable and left unoffered (deferred).
392 TxbSet::Luma16InterSet1 | TxbSet::Luma8InterSet1 | TxbSet::Luma4InterSet1 if on => {
393 &INTER_WIDE
394 }
395 _ => &DCT,
396 }
397}
398
399/// lane-txi: does THIS frame code `reduced_tx_set = 0` (spec 5.9.2), i.e.
400/// the wider `tx_type` alphabets at intra 8x8/4x4 and inter 16x16 and below?
401/// `EC_AV1_TXSET_WIDE`: `0`/`off`, `screen` (screen frames only), anything
402/// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated
403/// like both halves of the type search itself.
404pub(crate) fn wide_tx_set(screen: bool) -> bool {
405 match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
406 0 => return false,
407 1 => return true,
408 _ => {}
409 }
410 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
411 crate::envflags::var("EC_AV1_TXSET_WIDE")
412 .ok()
413 .map(|v| match v.as_str() {
414 "0" | "off" => InterTxSearch::Off,
415 "screen" => InterTxSearch::Screen,
416 _ => InterTxSearch::All,
417 })
418 });
419 match ENV.unwrap_or(if crate::speed::at(&crate::speed::WIDE_TX_SET) {
420 InterTxSearch::Screen
421 } else {
422 InterTxSearch::Off
423 }) {
424 InterTxSearch::Off => false,
425 InterTxSearch::Screen => screen,
426 _ => true,
427 }
428}
429
430/// A PROCESS-GLOBAL [`wide_tx_set`] override that wins over both the
431/// environment and the preset (`u8::MAX` = unset), the shape
432/// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the
433/// witness that has to see the wider alphabets turns it on through this while
434/// holding [`crate::speed::knob_write`].
435static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
436
437/// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it.
438#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
439pub(crate) fn set_wide_tx_set(on: Option<bool>) {
440 WIDE_TX_OVERRIDE.store(
441 on.map_or(u8::MAX, u8::from),
442 std::sync::atomic::Ordering::Relaxed,
443 );
444}
445
446/// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes
447/// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own
448/// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read
449/// the same alphabet or the two disagree on what a `tx_type` symbol costs.
450pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet {
451 if wide_tx_set(screen) { set.wide() } else { set }
452}
453
454#[derive(Clone, Copy, PartialEq)]
455pub(crate) enum InterTxSearch {
456 Off,
457 Screen,
458 /// 16x16 and below only.
459 Le16,
460 All,
461}
462
463/// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the
464/// environment and the preset (`u8::MAX` = unset), the shape
465/// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness
466/// that has to see a non-`DCT_DCT` inter unit turns it on through this while
467/// holding [`crate::speed::knob_write`].
468static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
469
470/// Sets [`INTER_TX_OVERRIDE`]; `None` clears it.
471#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
472pub(crate) fn set_inter_tx_search(on: Option<bool>) {
473 INTER_TX_OVERRIDE.store(
474 on.map_or(u8::MAX, u8::from),
475 std::sync::atomic::Ordering::Relaxed,
476 );
477}
478
479fn inter_tx_type_search() -> InterTxSearch {
480 match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
481 0 => return InterTxSearch::Off,
482 1 => return InterTxSearch::All,
483 _ => {}
484 }
485 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
486 crate::envflags::var("EC_AV1_TXSET_INTER")
487 .ok()
488 .map(|v| match v.as_str() {
489 "0" | "off" => InterTxSearch::Off,
490 "screen" => InterTxSearch::Screen,
491 "le16" => InterTxSearch::Le16,
492 _ => InterTxSearch::All,
493 })
494 });
495 ENV.unwrap_or_else(|| {
496 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) {
497 InterTxSearch::Screen
498 } else {
499 InterTxSearch::Off
500 }
501 })
502}
503
504/// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the
505/// 64-point one (it codes no `tx_type` symbol).
506/// lane-txw history, resolved by lane-intertx: the INTER half of the
507/// widening was blocked by `refusal-from-own-desync` twice over. Half of it
508/// was this writer coding a `V_DCT`/`H_DCT` unit as `TX_CLASS_2D`
509/// (`tile::write_coeffs`, fixed by lane-txw, which unblocked the intra
510/// half). The other half was the CHROMA inheritance: an inter block's
511/// chroma transform type is the luma type reduced to the chroma size's set
512/// (`decode::reduce_inherited_chroma_tx_type`), and (a) the encoder never
513/// set `FrameCtx::reduced_tx_set_inter`, so [`recode_inter_chroma`] reduced
514/// against a STALE allowance, and (b) `tile::write_block_planes` coded
515/// every chroma plane as `DCT_DCT`, so an inherited 1-D type desynced the
516/// chroma exactly as luma did. lane-intertx fixed both -- the frame sets
517/// its own bit on the context (`encode_inter_frame`), the writer derives
518/// the chroma type from this frame's own header bit
519/// (`reduce_inherited_chroma_tx_type_flagged`) -- and the widened SEARCH
520/// names these sets through [`luma_set_for`] at its call sites, so the
521/// wider candidates are reachable and honestly priced. The intra half
522/// never needed either (an intra block's chroma type comes off its own UV
523/// mode, never off luma).
524fn inter_luma_set(tx: usize) -> Option<TxbSet> {
525 Some(match tx {
526 4 => TxbSet::Luma4Inter,
527 8 => TxbSet::Luma8Inter,
528 16 => TxbSet::Luma16Inter,
529 32 => TxbSet::Luma32Inter,
530 _ => return None,
531 })
532}
533
534fn tx_type_search() -> bool {
535 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
536 crate::envflags::var("EC_AV1_TXSET")
537 .ok()
538 .map(|v| !matches!(v.as_str(), "0" | "off"))
539 });
540 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
541}
542
543/// Whether an intra luma unit of this frame searches its own type at all:
544/// the preset lever ([`tx_type_search`]) under the screen content gate, which
545/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global
546/// [`set_intra_tx_search`] override wins over (the witness needs the search
547/// on a frame the detector called non-screen).
548fn intra_tx_search_on(screen: bool) -> bool {
549 match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
550 0 => return false,
551 1 => return true,
552 _ => {}
553 }
554 (screen || intra_tx_all_frames()) && tx_type_search()
555}
556
557/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
558/// shape [`set_inter_tx_search`] has.
559static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
560
561/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
562#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
563pub(crate) fn set_intra_tx_search(on: Option<bool>) {
564 INTRA_TX_OVERRIDE.store(
565 on.map_or(u8::MAX, u8::from),
566 std::sync::atomic::Ordering::Relaxed,
567 );
568}
569
570/// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY
571/// frame -- the unconditional arm the gate measures -- instead of the screen
572/// content gate [`tx_type_candidates`] ships behind. Any other value keeps
573/// the gate (`0`/`off` still switches the search off entirely).
574fn intra_tx_all_frames() -> bool {
575 static ENV: std::sync::LazyLock<bool> =
576 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all"));
577 *ENV
578}
579
580fn tx_select() -> bool {
581 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
582 crate::envflags::var("EC_AV1_TX_SELECT")
583 .ok()
584 .map(|v| !matches!(v.as_str(), "0" | "off"))
585 });
586 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
587}
588
589fn split_inter_8() -> bool {
590 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
591 Some(v) if cfg!(test) => v != "0",
592 _ => crate::speed::at(&crate::speed::SPLIT_8),
593 }
594}
595
596/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
597/// NEARESTMV candidate it always had.
598pub(crate) const LEAF_NEW_MV: bool = true;
599
600/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
601/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
602/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
603/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
604pub(crate) const EXTRA_REF_NEW_MV: bool = true;
605
606/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
607/// own best vector before that reference's `NEWMV` search is skipped: a
608/// factor on the search cost scale, `1.0` meaning "as good or better".
609/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
610/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
611/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
612/// extra searches drop from +27% to +4% of the base count -- and on screen
613/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
614/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
615/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
616/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
617/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
618/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
619/// own noise. 0.35 stays; the lever that did move at the new rate weight is
620/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
621const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
622
623/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
624fn extra_new_skip_margin() -> f64 {
625 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
626 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
627 _ => EXTRA_NEW_SKIP_MARGIN,
628 }
629}
630
631/// The margin on a LEAF's SECOND-reference motion search, the same early-out
632/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
633/// `NEWMV`: the search is skipped when that reference's own
634/// `NEAREST_NEARESTMV` vector already prices this many times better than the
635/// leaf's `LAST` search found. `0.0` never skips.
636///
637/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
638/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
639/// 2160p (38195 with no second-reference search at all):
640/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
641/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
642/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
643/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
644/// of its extra searches; past it the calls double for another -0.3/-0.5.
645/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
646/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
647/// so the margin is pure wall on that content (+10% searches at 0.8).
648///
649/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
650/// the native gate with local warp on, BD vs libaom / vs rav1e:
651///
652/// | margin | film 1080p | film 2160p | screen |
653/// |---|---|---|---|
654/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
655/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
656/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
657/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
658/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
659///
660/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
661/// with screen flat -- and it beats never-skipping, i.e. the early-out is
662/// still worth having, just at a looser margin than the old rate weight
663/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
664/// 32.6s at 2160p), which is the price of the extra second-reference
665/// searches.
666const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
667
668/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
669/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
670fn leaf_second_new_margin() -> f64 {
671 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
672 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
673 None => LEAF_SECOND_NEW_MARGIN,
674 }
675}
676
677/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
678fn leaf_second_new_mv() -> bool {
679 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
680 Some(v) => v != "0",
681 None => crate::speed::at(&crate::speed::LEAF_SECOND),
682 }
683}
684
685/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
686/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
687/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
688/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
689/// was missing was the encoder ever forming one below 32x32.
690pub(crate) const LEAF_COMPOUND: bool = true;
691
692/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
693fn leaf_compound() -> bool {
694 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
695 Some(v) => v != "0",
696 None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
697 }
698}
699
700/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
701fn leaf_new_mv() -> bool {
702 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
703 Some(v) if cfg!(test) => v != "0",
704 _ => LEAF_NEW_MV,
705 }
706}
707
708/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
709/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
710/// the true frame edge cut through was ever split there; inside the frame
711/// every block was coded whole, which left the partition decision the key
712/// frame already makes unmade for eleven frames out of twelve.
713pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
714
715/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
716/// measurement that keeps it is running (test builds only, like
717/// [`lambda_scale`]).
718fn split_inter_blocks() -> bool {
719 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
720 Some(v) if cfg!(test) => v != "0",
721 _ => crate::speed::at(&crate::speed::SPLIT_INTER),
722 }
723}
724
725/// Whether the inter search offers the whole superblock as ONE 64x64 block
726/// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32
727/// quadrants it would otherwise always split into.
728///
729/// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6
730/// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of
731/// them skip at 328 bytes a frame -- while every block this encoder wrote was
732/// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669
733/// bits against rav1e's 61,988, about 46% of the film B gap.
734///
735/// lane-tx64: no longer skip-only. The root also prices a REAL residual --
736/// one TX_64X64 luma transform (`transform.rs`'s forward network has always
737/// reached 64 points; what was missing was the block coder and the writer
738/// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`],
739/// which carries that arm's own gate table. Still refused at the 64 root:
740/// compound references, a depth-1 4x32x32 var-tx tree, intra, and a
741/// superblock the true frame edge cuts through.
742///
743/// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the
744/// root and restores the skip-only shape lane-b64 shipped.
745pub(crate) const B64_ROOT: bool = true;
746
747/// How many superblocks took the 64x64 root since the last
748/// [`take_b64_root_hits`], so a gate reports how often it fires rather than
749/// assuming it does (class `gate-blind-to-feature`).
750static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
751
752/// The 64x64-root count since the last call, and zero it.
753pub fn take_b64_root_hits() -> usize {
754 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
755}
756
757/// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at
758/// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off,
759/// which is the attribution arm for a 128-superblock stream: it separates
760/// what the SIZE costs from what the 128x128 BLOCK buys.
761fn b128_root() -> bool {
762 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
763 crate::envflags::var("EC_AV1_B128")
764 .ok()
765 .is_none_or(|v| v != "0")
766 });
767 *ENV
768}
769
770/// lane-b128r: whether the 128 root prices a REAL residual as well as the
771/// skip arm -- four TX_64X64 luma units interleaved with a TX_32X32 chroma
772/// pair per 64x64 mu chunk, var-tx depth 0 (the shape
773/// [`crate::tile::write_inter_block_128`] codes and `decode_inter_block`
774/// reads). Written, witnessed and byte-exact through both decoders, and
775/// **off by default** (`EC_AV1_B128RES=1` turns it on) because it is INERT
776/// on content: the RD takes it 0.7-1.9 times per frame against thousands of
777/// whole 128 roots (lane-b128res census, native 12-frame gate, every clip),
778/// and the BD effect is inside the noise on both gates -- long-GOP films
779/// -0.1/+0.1 and all five 12-frame rows within 0.1 of the off default.
780///
781/// The historical reason for the parking is CLOSED: the bars 2160p q=90
782/// frame 11 disagreement with ffmpeg (8 luma samples at the rows above a
783/// 128-superblock horizontal edge) was the CDEF search pricing a preset per
784/// 64x64 unit under a root that codes ONE literal for all four -- lane-
785/// edge128's `crate::tile::cdef_unit_owner` collapses the four to the one
786/// the decoder derives, and on this HEAD the same row re-measures three-way
787/// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
788/// every plane, both gates). The knob stays as the arm's gate, not as a
789/// defect flag.
790fn b128_residual() -> bool {
791 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
792 crate::envflags::var("EC_AV1_B128RES")
793 .ok()
794 .map(|v| v != "0")
795 });
796 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
797 && b128_root()
798}
799/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
800/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
801/// plus one half) -- price a REAL residual in the RD as well as the skip arm
802/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
803/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
804/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
805/// no rect/AB piece can come out non-skip, so the writer's refusal is never
806/// reached. The residual shape is the whole 128 block's, halved or quartered
807/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
808/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
809/// for any inter partition shape).
810fn rectres() -> bool {
811 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
812 crate::envflags::var("EC_AV1_RECTRES")
813 .ok()
814 .map(|v| v != "0")
815 });
816 ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
817}
818
819/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
820/// witness clip codes the shape rather than waiting for content on which the
821/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
822/// root). Never read outside `#[cfg(test)]` builds.
823static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
824 std::sync::atomic::AtomicBool::new(false);
825
826/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
827#[cfg(test)]
828pub(crate) fn force_b128_rectres(on: bool) {
829 FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
830}
831
832/// How many rect/AB pieces the search left WITH a residual rather than
833/// skipped, since the last [`take_b128_rectres_hits`] (class
834/// `gate-blind-to-feature`).
835static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
836
837/// The rect/AB-piece-residual count since the last call, and zero it.
838pub fn take_b128_rectres_hits() -> usize {
839 B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
840}
841
842/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
843/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
844/// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's
845/// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this
846/// arm's attribution control; the writer has always had the path
847/// (`write_inter_block_128` calls `write_compound_block` for a block that
848/// names a second reference).
849fn b128_compound() -> bool {
850 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
851 crate::envflags::var("EC_AV1_B128COMP")
852 .ok()
853 .map(|v| v != "0")
854 });
855 ENV.unwrap_or(true) && b128_root()
856}
857
858/// How many 128 roots came out COMPOUND since the last
859/// [`take_b128_compound_hits`] (class `gate-blind-to-feature`).
860static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
861
862/// The compound-128 count since the last call, and zero it.
863pub fn take_b128_compound_hits() -> usize {
864 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
865}
866
867/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ`
868/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the
869/// same skip-only single-reference/compound machinery the NONE arm ships,
870/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
871/// `EC_AV1_B128HV=0` is this arm's attribution control.
872fn b128_rect() -> bool {
873 static ENV: std::sync::LazyLock<Option<bool>> =
874 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0"));
875 ENV.unwrap_or(true) && b128_root()
876}
877
878/// lane-rectdq: whether the delta_q symbol group is priced on the root
879/// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's
880/// attribution control (the pre-lane pricing, where a 128 rect root and the
881/// four-superblock arm were both priced as if the group were free).
882fn rectdq() -> bool {
883 static ENV: std::sync::LazyLock<Option<bool>> =
884 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0"));
885 ENV.unwrap_or(true)
886}
887
888/// lane-rectdq: what `crate::tile::write_delta_q` spends to move
889/// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of
890/// `res` -- the same three pieces that writer codes, in its order: the
891/// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the
892/// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from
893/// exactly this row), the escape literal pair when `abs >= 3`, and the sign
894/// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`).
895pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 {
896 if res <= 0 {
897 return 0.0;
898 }
899 /// spec `DELTA_Q_SMALL`, as in the writer.
900 const DELTA_Q_SMALL: usize = 3;
901 let reduced = (target - cur) / res;
902 let abs = reduced.unsigned_abs() as usize;
903 // A pricing coder, not a sum of table entries: the escape's literal bits
904 // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB`
905 // floor, so each really costs a little over one bit (class
906 // `price-the-narrowing-not-the-table`). Read off the same
907 // `SymbolEncoder::bits` account the writer's own coder keeps.
908 let mut enc = crate::msac::SymbolEncoder::pricer();
909 enc.reset_bits();
910 enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q);
911 if abs >= DELTA_Q_SMALL {
912 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
913 enc.literal(rem_bits - 1, 3);
914 enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits);
915 }
916 if abs != 0 {
917 enc.literal(u32::from(reduced < 0), 1);
918 }
919 enc.bits()
920}
921
922/// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64
923/// superblock units): the group every root shape but a SKIPPED
924/// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for
925/// `side == write_w == write_h == sb_px` and neither a rect half nor a 64
926/// superblock under a 128 grid is that.
927///
928/// The target is the root's own cell of the `sb_q` grid, exactly the entry
929/// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search --
930/// the writer's `plan.cur` only advances at the roots that really code a
931/// group, and which those are is decided by this very comparison -- so the
932/// PREVIOUS 128 root's target in raster order stands in for it (the frame's
933/// `base_q_idx` at the first root of the frame, which is also the writer's
934/// own per-tile reset). Wrong only where a neighbouring root came out a
935/// skipped NONE block, and then only by the difference of two adjacent tpl
936/// cells.
937fn delta_q_bits_at_root(
938 sb_q: Option<&Vec<u8>>,
939 sb_cols: usize,
940 base_q_idx: u8,
941 res: i32,
942 (root_r, root_c): (usize, usize),
943) -> f64 {
944 if !rectdq() || res <= 0 {
945 return 0.0;
946 }
947 let Some(q) = sb_q.filter(|q| !q.is_empty()) else {
948 return 0.0;
949 };
950 let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]);
951 let target = at(root_r, root_c);
952 let cur = if root_c >= 2 {
953 at(root_r, root_c - 2)
954 } else if root_r >= 2 {
955 // The last 128 root of the row above, i.e. the previous one in the
956 // writer's raster walk.
957 at(root_r - 2, (sb_cols.saturating_sub(1)) & !1)
958 } else {
959 i32::from(base_q_idx)
960 };
961 delta_q_bits(target, cur, res)
962}
963
964/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
965/// halves since the last take (class `gate-blind-to-feature`).
966static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
967/// The VERT twin of [`B128_HORZ_HITS`].
968static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
969
970/// The HORZ-128-root count since the last call, and zero it.
971pub fn take_b128_horz_hits() -> usize {
972 B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
973}
974
975/// The VERT-128-root count since the last call, and zero it.
976pub fn take_b128_vert_hits() -> usize {
977 B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
978}
979
980/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off,
981/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because
982/// synthetic content is where the shape is cheapest to decode-check and the
983/// RD there prefers one whole block; the gate census is the unforced count.
984static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
985
986/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
987#[cfg(test)]
988pub(crate) fn force_b128_rect(which: u8) {
989 FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
990}
991
992/// lane-ab128: whether the 128 superblock root offers its four AB shapes --
993/// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
994/// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128
995/// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is
996/// the same skip-only single-reference/compound block the NONE and HORZ/VERT
997/// arms ship, at its own footprint ([`search_root_128_ab`],
998/// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this
999/// arm's attribution control.
1000///
1001/// **Off by default** (`EC_AV1_B128AB=1` turns it on): measured on both gates
1002/// and it does not pay. The shapes fire 0-2 roots a frame against ~1000 coded
1003/// blocks (`EC_AV1_B128_CENSUS`), and every row is flat or 0.1 worse --
1004/// long-GOP film A +22.0/-8.5 against a +21.9/-8.6 control, film B +75.8/+0.8
1005/// against the same, 12-frame film A +18.1/-6.2 against +18.0/-6.3, film B
1006/// +23.1/-3.3 against +23.0/-3.5, screen byte-identical (lane-ab128). The
1007/// machinery is written, witnessed sample-exact through both decoders on all
1008/// four shapes, and kept for the arm that makes it pay: a non-skip piece (the
1009/// 64x64 pieces could carry the 64 root's residual, which is where libaom's
1010/// AB shapes earn their keep) or a cheaper partition price.
1011fn b128_ab() -> bool {
1012 static ENV: std::sync::LazyLock<Option<bool>> =
1013 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0"));
1014 ENV.unwrap_or(false) && b128_root()
1015}
1016
1017/// How many 128 roots the search left as each AB shape since the last take,
1018/// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class
1019/// `gate-blind-to-feature`).
1020static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
1021 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
1022
1023/// The four per-shape AB-root counts since the last call, and zero them.
1024pub fn take_b128_ab_hits() -> [usize; 4] {
1025 std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1026}
1027
1028/// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then
1029/// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic
1030/// content is where the shapes are cheapest to decode-check and the RD there
1031/// prefers one whole block).
1032static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1033
1034/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7).
1035#[cfg(test)]
1036pub(crate) fn force_b128_ab(which: u8) {
1037 FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed);
1038}
1039
1040/// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
1041/// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
1042/// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =
1043/// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR.
1044/// Each entry is the piece's own top-left in mode-info units and its
1045/// footprint in samples.
1046pub(crate) fn ab128_pieces(
1047 symbol: usize,
1048 (mi_row, mi_col): (usize, usize),
1049) -> [((usize, usize), (usize, usize)); 3] {
1050 const S: usize = SUPERBLOCK;
1051 let (r, c) = (mi_row, mi_col);
1052 let (r1, c1) = (mi_row + 16, mi_col + 16);
1053 match symbol {
1054 // PARTITION_HORZ_A
1055 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))],
1056 // PARTITION_HORZ_B
1057 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))],
1058 // PARTITION_VERT_A
1059 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))],
1060 // PARTITION_VERT_B
1061 _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))],
1062 }
1063}
1064
1065/// Test-only: take the 128 root's residual arm whatever it costs, so a
1066/// witness clip codes the shape rather than waiting for content on which the
1067/// RD picks it (the same role [`force_sb128`] plays for the superblock size).
1068/// Never read outside `#[cfg(test)]` builds.
1069static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
1070 std::sync::atomic::AtomicBool::new(false);
1071
1072/// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take
1073/// the 128 root whenever it produced a candidate at all, whatever its four
1074/// cells cost, so a witness codes the block it is about rather than waiting
1075/// for content on which the root also wins its own comparison.
1076static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1077
1078/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
1079/// forced residual block only reaches the writer if its root is taken.
1080#[cfg(test)]
1081pub(crate) fn force_b128_residual(on: bool) {
1082 FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
1083 force_b128_root(on);
1084}
1085
1086/// Arms [`FORCE_B128_ROOT`] for the rest of the process.
1087#[cfg(test)]
1088pub(crate) fn force_b128_root(on: bool) {
1089 FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed);
1090}
1091
1092/// How many 128 roots came out cheaper WITH a residual than skipped, since
1093/// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
1094static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1095
1096/// The 128-residual count since the last call, and zero it.
1097pub fn take_b128_residual_hits() -> usize {
1098 B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1099}
1100
1101/// How many 128x128 `PARTITION_NONE` roots the search took since the last
1102/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
1103/// is only attributable once the fire count is known.
1104static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1105
1106/// The 128x128-root count since the last call, and zero it.
1107pub fn take_b128_none_hits() -> usize {
1108 B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1109}
1110
1111/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
1112/// Preset-gated: it re-prices the block once per candidate level, so it buys
1113/// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
1114///
1115/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
1116/// which is what the byte pins are taken under when they name it.
1117fn rdoq_on() -> bool {
1118 static ENV: std::sync::LazyLock<Option<bool>> =
1119 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0"));
1120 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
1121}
1122
1123/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in
1124/// units of one squared AC quantiser step -- the search's own
1125/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency.
1126///
1127/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`],
1128/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock
1129/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here:
1130/// corner-cut, ceiling = a superblock the temporal map weighs away from the
1131/// frame average has its coefficients optimised at the frame's weight. The
1132/// upgrade is one `lambda` field on the trial call sites, which is the whole
1133/// mode-search argument list.
1134///
1135/// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom
1136/// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above
1137/// the mode search's own weight, and it is the same multiplier on all three
1138/// rows:
1139///
1140/// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen |
1141/// |---|---|---|---|
1142/// | 0.7 | +27.6 | +39.5 | +29.6 |
1143/// | 1.0 | +26.3 | +37.5 | +29.1 |
1144/// | 1.3 | +25.6 | +37.0 | +28.8 |
1145/// | 1.6 | +24.6 | +35.9 | +28.7 |
1146/// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 |
1147/// | 3.2 | +24.7 | +36.1 | +29.4 |
1148///
1149/// A coefficient's rate is worth twice here what the mode search prices it
1150/// at, and the likeliest reason is that the price is taken against tables
1151/// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded
1152/// late in a frame whose `txb_skip`/`base` tables have narrowed really costs
1153/// less than the pricer says, and this pass is the one decision taken per
1154/// COEFFICIENT, so it feels that error most. The honest fix is an adapted
1155/// price, not a fitted multiplier; this is the fitted multiplier, and its
1156/// bowl is measured rather than assumed.
1157const RDOQ_LAMBDA_MULT: f64 = 2.2;
1158
1159/// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term
1160/// calibration sweep).
1161fn rdoq_lambda() -> f64 {
1162 static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
1163 crate::envflags::var("EC_AV1_RDOQ_LAMBDA")
1164 .ok()
1165 .and_then(|v| v.parse().ok())
1166 .unwrap_or(RDOQ_LAMBDA_MULT)
1167 });
1168 lambda_scale() * *MULT
1169}
1170
1171/// [`B64_ROOT`], or what `EC_AV1_B64` names.
1172fn b64_root() -> bool {
1173 static ENV: std::sync::LazyLock<Option<bool>> =
1174 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0"));
1175 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
1176}
1177
1178/// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched
1179/// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64
1180/// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner)
1181/// and one TX_32X32 per chroma plane -- and compared against the four 32x32
1182/// quadrants at the same lambda, exactly the shape the inter root
1183/// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to
1184/// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`);
1185/// nothing produced one, so the key frame -- 21.6% of a real film stream --
1186/// coded every superblock split while libaom and rav1e leave 45-54% of theirs
1187/// whole.
1188///
1189/// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on
1190/// it), no filter intra (`filter_intra_size_class` has no 64 row) and no
1191/// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32
1192/// level grid, so only depth 0 is representable) -- the root is refused
1193/// outright on an `allow_intrabc` frame, whose quadrant searches carry DV
1194/// state a discarded trial would desync.
1195///
1196/// Switched off by `EC_AV1_I64=0` in any build.
1197pub(crate) const I64_ROOT: bool = true;
1198
1199/// How many key-frame superblocks were coded as one 64x64 intra block since
1200/// the last [`take_i64_root_hits`], so a gate reports the fire rate rather
1201/// than assuming it (class `gate-blind-to-feature`).
1202/// Index 1 is how many were OFFERED the trial at all, so a gate reads a
1203/// SHARE and not a bare count, and index 2 how many of the whole ones sat on
1204/// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the
1205/// `gate-blind-to-feature` guard for the edge path, which no
1206/// superblock-aligned clip fires at all.
1207static I64_HITS: [std::sync::atomic::AtomicUsize; 3] =
1208 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
1209
1210/// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the
1211/// last call, and zero them.
1212pub fn take_i64_root_hits() -> [usize; 3] {
1213 std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1214}
1215
1216/// [`I64_ROOT`], or what `EC_AV1_I64` names.
1217fn i64_root() -> bool {
1218 static ENV: std::sync::LazyLock<Option<bool>> =
1219 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0"));
1220 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
1221}
1222
1223/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
1224/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
1225/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
1226/// lane-b64 shipped, so the two can be measured against each other on the
1227/// same build.
1228///
1229/// MEASURED on the native gate (two arms of one build, baseline reproduced to
1230/// the tenth): both film rows improve on both columns -- film A
1231/// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and
1232/// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's
1233/// +-0.3 screen clause. So the caller gates this off on a screen frame
1234/// (`allow_screen_content_tools`), the same content gate the coding pyramid
1235/// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm
1236/// already codes them for nothing, and a residual there only spends bits the
1237/// intra/palette tools would have spent better.
1238///
1239/// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` +
1240/// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on:
1241///
1242/// | | skip-only | + residual |
1243/// |---|---|---|
1244/// | 64x64 share, all frames | 36.4% | 38.3% |
1245/// | 64x64 share, leaf frames | 53.3% | 56.0% |
1246/// | skip area, all frames | 80.4% | 78.8% |
1247/// | skip area, leaf frames | 90.2% | 88.5% |
1248/// | stream bytes | 34,366 | 34,295 |
1249/// | encoder wall | 13.4s | 9.6s |
1250///
1251/// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the
1252/// TX_64X64 coefficients are really being coded. The root wins MORE often
1253/// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is
1254/// 45.2%), which is also why the arm is 28% FASTER despite costing three more
1255/// transforms per superblock: a root that wins is four quadrant searches that
1256/// never run.
1257fn b64_residual() -> bool {
1258 static ENV: std::sync::LazyLock<Option<bool>> =
1259 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0"));
1260 ENV.unwrap_or(true) && b64_root()
1261}
1262
1263/// How many 64x64 roots came out cheaper with a residual than skipped, since
1264/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
1265/// rather than assuming one (class `gate-blind-to-feature`).
1266static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1267
1268/// The non-skip 64x64-root count since the last call, and zero it.
1269pub fn take_b64_residual_hits() -> usize {
1270 B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1271}
1272
1273/// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the
1274/// `LAST` + extra-reference pairs the 32x32 level already offers, at the
1275/// three modes a root can form without a second 64x64 motion search --
1276/// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half
1277/// is the vector `search_skip_64`'s own single-reference search already
1278/// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own
1279/// `NEWMV` vector, which only a second search per superblock produces -- the
1280/// wall this root exists to save -- so they are not offered here.
1281///
1282/// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
1283fn b64_compound() -> bool {
1284 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1285 crate::envflags::var("EC_AV1_B64COMP")
1286 .ok()
1287 .map(|v| v != "0")
1288 });
1289 ENV.unwrap_or(true) && b64_root()
1290}
1291
1292/// How many 64x64 roots took a COMPOUND candidate since the last
1293/// [`take_b64_compound_hits`] (class `gate-blind-to-feature`).
1294static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1295
1296/// The compound 64x64-root count since the last call, and zero it.
1297pub fn take_b64_compound_hits() -> usize {
1298 B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1299}
1300
1301/// Whether a 64x64 root that codes a residual may SPLIT its luma transform
1302/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by
1303/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by
1304/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because
1305/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose
1306/// residual has detail in the other three quadrants cannot code it at all.
1307///
1308/// Off by `EC_AV1_B64VARTX=0`.
1309fn b64_var_tx() -> bool {
1310 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1311 crate::envflags::var("EC_AV1_B64VARTX")
1312 .ok()
1313 .map(|v| v != "0")
1314 });
1315 ENV.unwrap_or(true) && b64_root()
1316}
1317
1318/// How many 64x64 roots split their luma transform since the last
1319/// [`take_b64_var_tx_hits`].
1320static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1321
1322/// The split-luma 64x64-root count since the last call, and zero it.
1323pub fn take_b64_var_tx_hits() -> usize {
1324 B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1325}
1326
1327/// Whether a superblock the true frame edge CUTS THROUGH may be left whole
1328/// (lane-b64b). AV1 asks only that the block's own half is inside
1329/// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already
1330/// codes that case; what was missing was a trial whose SSE is scored over the
1331/// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse)
1332/// instead of over the padding the encoder
1333/// invented past the edge. Both gate films are superblock-aligned, so this
1334/// only reaches the user's own arbitrary export sizes.
1335///
1336/// Off by `EC_AV1_B64EDGE=0`.
1337fn b64_edge() -> bool {
1338 edge_root_enabled() && b64_root()
1339}
1340
1341/// What `EC_AV1_B64EDGE` names on its own, without the inter root's own
1342/// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag
1343/// but is gated by [`i64_root`].
1344fn edge_root_enabled() -> bool {
1345 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1346 crate::envflags::var("EC_AV1_B64EDGE")
1347 .ok()
1348 .map(|v| v != "0")
1349 });
1350 ENV.unwrap_or(true)
1351}
1352
1353/// How many 64x64 roots the frame edge cut through since the last
1354/// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are
1355/// superblock-aligned, so nothing but a synthetic size fires this).
1356static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1357
1358/// The edge 64x64-root count since the last call, and zero it.
1359pub fn take_b64_edge_hits() -> usize {
1360 B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1361}
1362
1363/// Whether the encoder searches loop restoration at all (spec 7.17): one
1364/// Wiener filter per 64x64 luma restoration unit, picked from
1365/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
1366/// test build, like [`lambda_scale`].
1367pub(crate) const RESTORATION: bool = true;
1368
1369/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
1370fn restoration_enabled() -> bool {
1371 match std::env::var("EC_AV1_LR").ok() {
1372 Some(v) if cfg!(test) => v != "0",
1373 _ => crate::speed::at(&crate::speed::RESTORATION),
1374 }
1375}
1376
1377/// libaom's `partition_search_breakout` shape: how many non-zero luma
1378/// coefficients per 256 luma samples a block may code and still be judged
1379/// well enough predicted that the split below it is not worth trying. `0`
1380/// disables the breakout (only the existing all-skip prune applies), which
1381/// is the default until the sweep below justifies otherwise.
1382///
1383/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
1384/// is where this lane's wall would have gone: 1 cuts the three clips'
1385/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
1386/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
1387/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
1388/// encoder's inter quality lives, so `0` ships and the knob stays for a
1389/// future explicit speed preset.
1390pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
1391
1392/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
1393/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
1394/// out under `threshold * lambda` is not offered the split at all, and a
1395/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
1396/// always, as before this lever.
1397///
1398/// The census is what points here: the split trial runs on nearly every
1399/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
1400/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
1401/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
1402/// points, so the gate has to read the block's own RD cost, not its levels.
1403///
1404/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
1405/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
1406/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
1407/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
1408/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
1409/// the largest threshold whose BD stays inside the +0.3 keep rule on every
1410/// clip.
1411/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
1412/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
1413/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
1414/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
1415/// the screen wall). Neither clears the keep rule; 0.125 stays.
1416pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
1417
1418/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
1419fn split_rd_threshold() -> f64 {
1420 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
1421 crate::envflags::var("EC_AV1_SPLIT_RD")
1422 .ok()
1423 .and_then(|v| v.parse().ok())
1424 });
1425 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
1426}
1427
1428/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
1429/// [`split_rd_threshold`] withholds the split trial.
1430fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
1431 split_rd_breakout_at(split_rd_threshold(), cost, side, lambda)
1432}
1433
1434/// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own
1435/// early-out reads.
1436fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool {
1437 t > 0.0 && cost < t * lambda * (side * side) as f64
1438}
1439
1440/// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`]
1441/// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64).
1442///
1443/// The 32x32 level is allowed to loosen its breakout with the speed preset
1444/// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured
1445/// what that does one size up: at 0.5 a whole superblock is taken at 64x64
1446/// without its four quadrants ever being searched, and film B goes
1447/// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the
1448/// same per-pixel threshold withholds four times as much search -- the
1449/// preset's step is priced for the 32 level and does not carry up here.
1450fn b64_breakout_threshold() -> f64 {
1451 split_rd_threshold().min(SPLIT_RD_THRESHOLD)
1452}
1453
1454/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
1455/// build.
1456fn split_breakout_coeffs() -> usize {
1457 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
1458 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
1459 _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
1460 }
1461}
1462
1463/// How often each partition decision was taken since the last
1464/// [`take_partition_hits`], so a gate can report how often a new partition
1465/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
1466/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
1467/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
1468static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
1469 std::sync::atomic::AtomicUsize::new(0),
1470 std::sync::atomic::AtomicUsize::new(0),
1471 std::sync::atomic::AtomicUsize::new(0),
1472 std::sync::atomic::AtomicUsize::new(0),
1473];
1474
1475/// Records one such decision.
1476fn partition_hit(which: usize) {
1477 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1478}
1479
1480/// Takes (and clears) the counts.
1481#[cfg(test)]
1482pub(crate) fn take_partition_hits() -> [usize; 4] {
1483 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1484}
1485
1486/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
1487/// rate-distortion trials the block search actually runs, by kind, and where
1488/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
1489/// default, and a measurement build rather than a speed one -- the census
1490/// runs the SAD pre-pass the unpruned search otherwise skips.
1491pub fn census_on() -> bool {
1492 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1493 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
1494}
1495
1496/// What each [`CENSUS`] counter counts.
1497pub const CENSUS_KINDS: [&str; 11] = [
1498 "intra blocks searched (key frame + inter leaves)",
1499 "intra luma mode trials",
1500 "chroma searches",
1501 "chroma mode trials (each = 2 plane trials)",
1502 "tx-depth trials (transform units, depth >= 1)",
1503 "inter 32x32 blocks searched",
1504 "inter block intra-mode trials",
1505 "inter mv candidates (each = 3 mc trials)",
1506 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
1507 " of those, intra won",
1508 " of those, the NEARESTMV trial coded no residual",
1509];
1510
1511/// The census counters themselves, indexed by [`CENSUS_KINDS`].
1512static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
1513 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
1514
1515/// Where the RD winner sat in the SAD ranking, for the luma intra search and
1516/// the chroma mode search -- what says whether a top-N prune would have kept
1517/// the block the search actually chose.
1518static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
1519 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
1520static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
1521 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1522
1523fn census_add(kind: usize, n: usize) {
1524 if census_on() {
1525 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
1526 }
1527}
1528
1529/// Reads (and clears) the census, so a driver can attribute it to its own encode.
1530pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
1531 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
1532 (
1533 std::array::from_fn(|i| take(&CENSUS[i])),
1534 std::array::from_fn(|i| take(&LUMA_RANK[i])),
1535 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
1536 )
1537}
1538
1539/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
1540/// first -- the census's one shared rule, so the luma and chroma histograms
1541/// mean the same thing.
1542fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
1543 scored
1544 .iter()
1545 .filter(|&&(score, mode)| {
1546 mode != winner
1547 && score
1548 < scored
1549 .iter()
1550 .find(|&&(_, m)| m == winner)
1551 .map_or(f64::INFINITY, |&(s, _)| s)
1552 })
1553 .count()
1554}
1555
1556/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
1557/// four cost less. Set from the measurement in the lane report.
1558const SPLIT_BLOCKS: bool = true;
1559
1560/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
1561/// by calling [`encode_key_frame_inner`] both ways.
1562pub(crate) fn split_blocks() -> bool {
1563 SPLIT_BLOCKS
1564}
1565
1566/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
1567/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
1568/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
1569/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
1570/// stream's decode output actually carries 10-bit precision instead of
1571/// silently losing its low 2 bits). The encoder only ever produces values in
1572/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
1573/// decision); `Plane::source` narrows right back to `u8` at its two
1574/// construction sites, a lossless round trip for that range.
1575#[derive(Clone, Debug, PartialEq, Eq)]
1576pub struct Picture {
1577 /// The picture's width in luma samples.
1578 pub width: usize,
1579 /// Its height in luma samples.
1580 pub height: usize,
1581 /// The luma plane, `width * height` samples in raster order.
1582 pub y: Vec<u16>,
1583 /// The U plane: half the width, and the frame's own chroma height -- a
1584 /// quarter of the luma samples at 4:2:0, half at 4:2:2, all of them at
1585 /// 4:4:4. A consumer that only knows the luma size reads the chroma
1586 /// format off this sample count (see `decode::ref_chroma_shape`).
1587 pub u: Vec<u16>,
1588 /// The V plane, the same shape as U.
1589 pub v: Vec<u16>,
1590}
1591
1592impl Picture {
1593 /// A mid-grey picture of the given size.
1594 #[must_use]
1595 pub fn grey(width: usize, height: usize) -> Self {
1596 Self {
1597 width,
1598 height,
1599 y: vec![128; width * height],
1600 u: vec![128; width * height / 4],
1601 v: vec![128; width * height / 4],
1602 }
1603 }
1604
1605 pub(crate) fn check(&self) -> Result<()> {
1606 if self.width == 0
1607 || !self.width.is_multiple_of(BLOCK)
1608 || !self.height.is_multiple_of(BLOCK)
1609 || !self.height.is_multiple_of(BLOCK)
1610 {
1611 return Err(Error::unsupported(
1612 "AV1 encode",
1613 "the picture must be a whole number of 32x32 blocks in each direction",
1614 ));
1615 }
1616 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1617 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1618 return Err(Error::unsupported(
1619 "AV1 encode",
1620 "each plane must carry one sample per position at 4:2:0",
1621 ));
1622 }
1623 Ok(())
1624 }
1625
1626 /// What the public entry points require of the picture they are handed,
1627 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
1628 /// needs a whole chroma sample per two luma ones) and one sample per
1629 /// position on each plane.
1630 pub(crate) fn check_even(&self) -> Result<()> {
1631 if self.width == 0
1632 || self.height == 0
1633 || !self.width.is_multiple_of(2)
1634 || !self.height.is_multiple_of(2)
1635 {
1636 return Err(Error::unsupported(
1637 "AV1 encode",
1638 "the picture's width and height must each be even and nonzero",
1639 ));
1640 }
1641 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1642 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1643 return Err(Error::unsupported(
1644 "AV1 encode",
1645 "each plane must carry one sample per position at 4:2:0",
1646 ));
1647 }
1648 Ok(())
1649 }
1650
1651 /// This picture, padded by edge replication to the next whole number of
1652 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
1653 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
1654 /// sequence (what the inter tile writer's partition needs on top of
1655 /// that). Identity (a plain clone, not a copy through the replication
1656 /// loop) when the picture is already that size — the multiple-of-32 (or
1657 /// -64) fast path is unchanged.
1658 pub(crate) fn padded_to(&self, align: usize) -> Picture {
1659 let padded_width = self.width.next_multiple_of(align);
1660 let padded_height = self.height.next_multiple_of(align);
1661 if padded_width == self.width && padded_height == self.height {
1662 return self.clone();
1663 }
1664 Picture {
1665 width: padded_width,
1666 height: padded_height,
1667 y: pad_plane(
1668 &self.y,
1669 self.width,
1670 self.height,
1671 padded_width,
1672 padded_height,
1673 ),
1674 u: pad_plane(
1675 &self.u,
1676 self.width / 2,
1677 self.height / 2,
1678 padded_width / 2,
1679 padded_height / 2,
1680 ),
1681 v: pad_plane(
1682 &self.v,
1683 self.width / 2,
1684 self.height / 2,
1685 padded_width / 2,
1686 padded_height / 2,
1687 ),
1688 }
1689 }
1690}
1691
1692/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
1693/// (8-bit only, unchanged this round -- widening the encoder is out of this
1694/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
1695/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
1696/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
1697/// content (every value fits both ways), so this changes no encoder output.
1698#[allow(clippy::too_many_arguments)]
1699fn intra_predict_u8(
1700 mode: u8,
1701 angle_delta: i32,
1702 above: Option<&[u8]>,
1703 left: Option<&[u8]>,
1704 corner: Option<u8>,
1705 bw: usize,
1706 bh: usize,
1707 enable_edge_filter: bool,
1708 smooth_neighbor: bool,
1709 dst: &mut [u8],
1710 fctx: &crate::decode::FrameCtx,
1711) {
1712 // Three heap allocations per call became three stack buffers: this runs
1713 // once per mode per trial, and an edge is at most `bw + bh` samples while
1714 // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's
1715 // 64x64 intra root predicts through here too, and reads up to `2 * bw`
1716 // samples above).
1717 let mut above_buf = [0u16; 2 * SUPERBLOCK];
1718 let mut left_buf = [0u16; 2 * SUPERBLOCK];
1719 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
1720 // trial of every block, and a 4x4 block writes 32 bytes of it. The
1721 // predictor fills every sample it is handed, so the zeros are dead
1722 // either way -- size the scratch to the block instead of to the largest
1723 // block there is.
1724
1725 let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| {
1726 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1727 *d = u16::from(v);
1728 }
1729 };
1730 if let Some(s) = above {
1731 widen(s, &mut above_buf);
1732 }
1733 if let Some(s) = left {
1734 widen(s, &mut left_buf);
1735 }
1736 let above16 = above.map(|s| &above_buf[..s.len()]);
1737 let left16 = left.map(|s| &left_buf[..s.len()]);
1738 let mut run = |dst16: &mut [u16]| {
1739 crate::intra::predict(
1740 mode,
1741 angle_delta,
1742 above16,
1743 left16,
1744 corner.map(u16::from),
1745 bw,
1746 bh,
1747 enable_edge_filter,
1748 smooth_neighbor,
1749 dst16,
1750 fctx,
1751 );
1752 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
1753 *d = s as u8;
1754 }
1755 };
1756 let n = bw * bh;
1757 if n <= 64 {
1758 run(&mut [0u16; 64][..n]);
1759 } else if n <= 256 {
1760 run(&mut [0u16; 256][..n]);
1761 } else if n <= BLOCK * BLOCK {
1762 run(&mut [0u16; BLOCK * BLOCK][..n]);
1763 } else {
1764 run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]);
1765 }
1766}
1767
1768/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
1769/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
1770/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
1771fn filter_intra_predict_u8(
1772 mode: usize,
1773 above: Option<&[u8]>,
1774 left: Option<&[u8]>,
1775 corner: Option<u8>,
1776 side: usize,
1777 dst: &mut [u8],
1778 fctx: &crate::decode::FrameCtx,
1779) {
1780 let mut above_buf = [0u16; 2 * BLOCK];
1781 let mut left_buf = [0u16; 2 * BLOCK];
1782 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
1783 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1784 *d = u16::from(v);
1785 }
1786 };
1787 if let Some(a) = above {
1788 widen(a, &mut above_buf);
1789 }
1790 if let Some(l) = left {
1791 widen(l, &mut left_buf);
1792 }
1793 let mut dst16 = [0u16; BLOCK * BLOCK];
1794 let n = side * side;
1795 crate::intra::predict_filter_intra(
1796 mode,
1797 above.map(|a| &above_buf[..a.len()]),
1798 left.map(|l| &left_buf[..l.len()]),
1799 corner.map(u16::from),
1800 side,
1801 side,
1802 &mut dst16[..n],
1803 fctx,
1804 );
1805 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
1806 *d = v as u8;
1807 }
1808}
1809
1810/// Pads one plane to `(padded_width, padded_height)` by repeating its last
1811/// row and column, so the block coder always sees a whole number of blocks.
1812/// [`crop_plane`] undoes this on the way back out.
1813fn pad_plane<T: Copy + Default>(
1814 source: &[T],
1815 width: usize,
1816 height: usize,
1817 padded_width: usize,
1818 padded_height: usize,
1819) -> Vec<T> {
1820 let mut out = vec![T::default(); padded_width * padded_height];
1821 for row in 0..padded_height {
1822 let src = source[row.min(height - 1) * width..][..width].as_ref();
1823 let dst = &mut out[row * padded_width..][..padded_width];
1824 dst[..width].copy_from_slice(src);
1825 dst[width..].fill(src[width - 1]);
1826 }
1827 out
1828}
1829
1830/// The top-left `width` x `height` region of a plane that is `padded_width`
1831/// wide, which is the render-size crop [`Picture::padded`]'s replication
1832/// exists to let a decoder undo.
1833fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
1834 let mut out = Vec::with_capacity(width * height);
1835 for row in 0..height {
1836 out.extend_from_slice(&source[row * padded_width..][..width]);
1837 }
1838 out
1839}
1840
1841/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
1842/// region a decoder produces, which is the public contract for what a caller
1843/// sees back — the padded planes the encoder coded against never leave this
1844/// module. Identity when the reconstruction is already that size.
1845///
1846/// The chroma extent is `ROUND_POWER_OF_TWO(size, 1)` -- `(size + 1) / 2`,
1847/// libaom's `av1_common_plane_width` (`av1/common/av1_common_int.h`) -- so an
1848/// ODD declared luma size keeps the chroma column a decoder keeps (a 65-wide
1849/// 4:2:0 frame has 33, not 32). Every even size is unaffected: `(2k+1)/2 ==
1850/// k`, so this is a no-op for every caller `encode_key_frame`'s even-size
1851/// check lets through.
1852pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1853 let reconstruction = &encoded.reconstruction;
1854 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
1855 let cropped = if reconstruction.width == width && reconstruction.height == height {
1856 reconstruction.clone()
1857 } else {
1858 Picture {
1859 width,
1860 height,
1861 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1862 u: crop_plane(&reconstruction.u, reconstruction.width / 2, cw, ch),
1863 v: crop_plane(&reconstruction.v, reconstruction.width / 2, cw, ch),
1864 }
1865 };
1866 Encoded {
1867 stream: encoded.stream.clone(),
1868 modes: encoded.modes.clone(),
1869 inter_block_share: encoded.inter_block_share,
1870 reconstruction: cropped,
1871 tile: encoded.tile.clone(),
1872 mi_cols: encoded.mi_cols,
1873 mi_rows: encoded.mi_rows,
1874 base_q_idx: encoded.base_q_idx,
1875 tx_select: encoded.tx_select,
1876 switchable_motion_mode: encoded.switchable_motion_mode,
1877 screen: encoded.screen,
1878 reduced_tx_set: encoded.reduced_tx_set,
1879 start_cdfs: encoded.start_cdfs.clone(),
1880 next_cdfs: encoded.next_cdfs.clone(),
1881 loop_filter: encoded.loop_filter,
1882 loop_restoration: encoded.loop_restoration,
1883 allow_intrabc: encoded.allow_intrabc,
1884 delta: encoded.delta.clone(),
1885 cdef: encoded.cdef,
1886 }
1887}
1888
1889/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1890/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1891#[derive(Clone)]
1892pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1893
1894impl std::fmt::Debug for CdfSnapshot {
1895 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1896 f.write_str("CdfSnapshot")
1897 }
1898}
1899
1900/// What one call to [`encode_key_frame`] produced.
1901#[derive(Clone, Debug)]
1902pub struct Encoded {
1903 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1904 /// OBU carrying one tile.
1905 pub stream: Vec<u8>,
1906 /// What a decoder will produce from `stream` — the encoder's own
1907 /// reconstruction, which its prediction was built on.
1908 pub reconstruction: Picture,
1909 /// The luma intra mode each block was coded under, in the order the blocks
1910 /// are coded — raster order among the quadrants of each superblock, and
1911 /// among the four 16x16 blocks of a quadrant that was split.
1912 pub modes: Vec<u8>,
1913 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1914 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1915 /// for a key frame, which has no such choice — so a caller can tell a
1916 /// frame with no motion worth coding from one that never got the chance.
1917 pub inter_block_share: f64,
1918 /// The tile payload alone, undecorated by any OBU framing, and the frame
1919 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1920 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1921 /// off the wire by parsing `stream`'s OBUs instead.
1922 pub(crate) tile: Vec<u8>,
1923 pub(crate) mi_cols: u32,
1924 pub(crate) mi_rows: u32,
1925 pub(crate) base_q_idx: u8,
1926 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1927 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1928 /// and reading it off `stream`'s header is what `decode_stream` does. A
1929 /// test that decodes `tile` directly must pass this one along, or it reads
1930 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1931 /// block.
1932 pub(crate) tx_select: bool,
1933 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1934 /// bit that makes every eligible single-reference inter block carry a
1935 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1936 /// decoding `tile` directly must pass it along or it desyncs at the
1937 /// first eligible block.
1938 pub(crate) switchable_motion_mode: bool,
1939 /// The CDF state this frame's tile writer started from -- the defaults
1940 /// for a key frame and for the first inter frame, and the previous
1941 /// frame's stored tables after that. A test that decodes `tile` directly
1942 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1943 /// the frame's `primary_ref_frame` slot holds (same class as
1944 /// `tx_select`: a header bit a raw tile decode cannot guess).
1945 ///
1946 /// BOXED (lane-av1stacksweep), and this is the whole point: the payload is
1947 /// a 15232-byte `Cdfs`, and `Encoded` is returned BY VALUE from a
1948 /// four-deep `Result<Encoded>` constructor chain, so an inline copy of two
1949 /// of them made `Encoded` 30728 bytes -- 99.2% of this struct was these
1950 /// two fields, and it was the largest by-value return in the crate.
1951 /// `DpbSlot::cdfs` was boxed for the same reason in lane-av1enchang; this
1952 /// is the other copy of the same table. The VALUES are untouched, so the
1953 /// bitstream is byte-identical; `crate::stack_budget` gates the result.
1954 pub(crate) start_cdfs: Box<CdfSnapshot>,
1955 /// What this frame stores into the slots it refreshes (spec 7.20,
1956 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1957 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1958 /// started from when it is on.
1959 pub(crate) next_cdfs: Box<CdfSnapshot>,
1960 /// This frame header's chosen deblocking parameters
1961 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1962 /// picture the decoder produces UNDER them, so a test that decodes
1963 /// `tile` directly must pass these along, exactly as it must `tx_select`
1964 /// (class: test asserts against a stale header).
1965 pub(crate) loop_filter: LoopFilterParams,
1966 /// This frame header's chosen CDEF parameters, threaded for the same
1967 /// reason as `loop_filter`.
1968 pub(crate) cdef: CdefParams,
1969 /// This frame header's `allow_screen_content_tools`
1970 /// ([`screen_content`]) -- every intra block of the tile carries the two
1971 /// palette-mode symbols under it, so a raw tile decode that guessed
1972 /// `false` would desync at the first block (same class as `tx_select`).
1973 pub(crate) screen: bool,
1974 /// This frame header's own `reduced_tx_set` (spec 5.9.2) -- the bit that
1975 /// picks the inter `tx_type` alphabets AND, on an inter block, the
1976 /// allowance the chroma transform's inherited type reduces against
1977 /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). A raw tile
1978 /// decode that guesses `true` here mis-derives every inherited chroma
1979 /// type on a `reduced_tx_set = 0` frame (lane-intertx; same class as
1980 /// `tx_select`/`screen` above).
1981 pub(crate) reduced_tx_set: bool,
1982 /// This frame header's chosen loop restoration parameters, threaded for
1983 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1984 /// filters themselves are coded in `tile`, so a decode of it under a
1985 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1986 pub(crate) loop_restoration: LoopRestorationParams,
1987 /// This frame header's `allow_intrabc` -- every intra block of the tile
1988 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1989 /// guessed `false` would desync at the first block (same class as
1990 /// `screen`/`tx_select`).
1991 pub(crate) allow_intrabc: bool,
1992 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1993 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1994 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1995 /// decode that guessed the defaults desyncs at the first superblock
1996 /// (same class as `screen`/`tx_select`).
1997 pub(crate) delta: ec_av1_syntax::DeltaParams,
1998}
1999
2000thread_local! {
2001 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
2002 /// for on the last key frame encoded on this thread -- read by the gates,
2003 /// which print it beside the block counts (class `gate-blind-to-feature`).
2004 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
2005}
2006
2007/// [`IBC_SHARE`] for the last key frame encoded on this thread.
2008#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2009pub(crate) fn intrabc_source_share() -> f64 {
2010 IBC_SHARE.with(std::cell::Cell::get)
2011}
2012
2013thread_local! {
2014 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
2015 /// header offers the per-frame `allow_screen_content_tools` bit at all.
2016 /// Armed once by the key frame ([`encode_key_frame_inner`], from
2017 /// [`screen_content`]) and read by every header builder after it, so that
2018 /// the inter frames of a screen sequence lay their headers out the same
2019 /// way the sequence header the key frame wrote says they do -- a per-call
2020 /// parameter would have to thread through `inter_frame_headers`' four
2021 /// public entry points and every hand-built-stream test that calls them.
2022 /// A sequence with no screen content leaves this false and writes exactly
2023 /// the bits it wrote before this lane.
2024 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2025}
2026
2027thread_local! {
2028 /// Overrides [`screen_content`] for the calling thread, which is what the
2029 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
2030 /// codes every block losslessly, so both arms of a mode ablation reach
2031 /// infinite PSNR and the ablation measures nothing at all (the
2032 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
2033 /// variable cannot do this -- the tests run in one process, in parallel.
2034 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2035}
2036
2037thread_local! {
2038 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
2039 /// under, AFTER the content gate: the pyramid, or `None` for a stream
2040 /// that stayed flat. Read by the BD gates, which print the requested and
2041 /// the effective pyramid side by side -- a screen clip requests one and
2042 /// codes flat, and that difference is the gate (class
2043 /// `gate-blind-to-feature`).
2044 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
2045 const { std::cell::Cell::new(None) };
2046}
2047
2048/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
2049#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2050pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
2051 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
2052}
2053
2054#[cfg(test)]
2055pub(crate) fn force_screen(value: Option<bool>) {
2056 SCREEN_FORCE.with(|c| c.set(value));
2057}
2058
2059// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
2060// ablation can measure the mode search alone. Setting it also clears the
2061// sequence header's own `enable_filter_intra` bit, so the stream the arm
2062// writes is exactly the one this encoder wrote before the lane.
2063#[cfg(test)]
2064thread_local! {
2065 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2066}
2067
2068#[cfg(test)]
2069pub(crate) fn force_filter_intra(value: Option<bool>) {
2070 FILTER_INTRA_FORCE.with(|c| c.set(value));
2071}
2072
2073pub(crate) fn arm_seq_screen(on: bool) {
2074 SEQ_SCREEN.with(|c| c.set(on));
2075}
2076
2077fn seq_screen() -> bool {
2078 SEQ_SCREEN.with(std::cell::Cell::get)
2079}
2080
2081/// How many distinct colours a 16x16 luma block may hold and still count as
2082/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
2083/// `av1_set_screen_content_options` bound is 4, which separates nothing on
2084/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
2085/// the variance floor below on the five gate clips at BOTH the native crop
2086/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
2087/// the frame is the widest-margin split of those ten rows -- every
2088/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
2089/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
2090/// native and 17.9% scaled.
2091fn screen_colors() -> usize {
2092 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2093 *N.get_or_init(|| {
2094 std::env::var("EC_AV1_SCREEN_COLORS")
2095 .ok()
2096 .and_then(|v| v.parse().ok())
2097 .unwrap_or(16)
2098 })
2099}
2100
2101/// The reciprocal of the frame area those blocks must cover, in tenths --
2102/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
2103/// 8 (an eighth) is the midpoint of the two populations
2104/// `probe_screen_detect` measures at the colour bound and variance floor
2105/// around it. `EC_AV1_SCREEN_PCT`.
2106fn screen_pct() -> usize {
2107 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2108 *N.get_or_init(|| {
2109 std::env::var("EC_AV1_SCREEN_PCT")
2110 .ok()
2111 .and_then(|v| v.parse().ok())
2112 .unwrap_or(10)
2113 })
2114}
2115
2116/// The per-pixel variance a few-colour block must clear before it counts as
2117/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
2118/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
2119/// a smooth dark film frame is all few-colour blocks and reads as a desktop
2120/// capture -- which is exactly what this detector did until 2026-09-07, when
2121/// it called BOTH real films screen content on 48/48 frames, priced every
2122/// coefficient against the default CDFs and ran the palette search over
2123/// film. `probe_screen_detect`: at 16 colours the floor takes both films
2124/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
2125/// 23.6%.
2126fn screen_var() -> u64 {
2127 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
2128 *N.get_or_init(|| {
2129 std::env::var("EC_AV1_SCREEN_VAR")
2130 .ok()
2131 .and_then(|v| v.parse().ok())
2132 .unwrap_or(16)
2133 })
2134}
2135
2136/// How many frames [`screen_content`] said yes/no to, so a gate can print
2137/// whether the detector fired at all (class `gate-blind-to-feature`).
2138pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
2139 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2140
2141/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
2142/// the distinct colours of every 16x16 block and turn the screen-content
2143/// tools on when the blocks holding between 2 and [`screen_colors`] of them
2144/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
2145/// frame. `width` is the plane's
2146/// stride, `true_*` the frame's real (decodable) extent.
2147fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
2148 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
2149 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2150 return forced;
2151 }
2152 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
2153 let on = v != "0";
2154 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2155 return on;
2156 }
2157 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
2158 let mut counted = 0usize;
2159 for by in (0..true_height).step_by(blk) {
2160 for bx in (0..true_width).step_by(blk) {
2161 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
2162 let mut seen = [false; 256];
2163 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
2164 for row in 0..h {
2165 for col in 0..w {
2166 let v = y[(by + row) * width + bx + col];
2167 sum += u64::from(v);
2168 sq += u64::from(v) * u64::from(v);
2169 if !seen[usize::from(v)] {
2170 seen[usize::from(v)] = true;
2171 colors += 1;
2172 }
2173 }
2174 }
2175 // Per-pixel variance over the block's real (edge-clipped) extent.
2176 let n = (h * w) as u64;
2177 let var = (sq - sum * sum / n) / n;
2178 if colors > 1 && colors <= limit && var > floor {
2179 counted += 1;
2180 }
2181 }
2182 }
2183 let on = counted * blk * blk * screen_pct() > true_width * true_height;
2184 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2185 on
2186}
2187
2188/// Whether this SOURCE picture reads as screen content, for a caller that has
2189/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
2190/// gates its coding pyramid on this (a desktop capture keeps the flat
2191/// one-in-one-out structure the BD gate measured it on, camera material takes
2192/// the mini-GOP). The key frame runs the same detector again when it builds
2193/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
2194/// count, so this probe undoes its own tick and leaves the gate prints
2195/// reading one detection per coded frame.
2196pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
2197 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
2198 let on = screen_content(&y, picture.width, picture.width, picture.height);
2199 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2200 on
2201}
2202
2203/// The sequence and frame headers a picture of this size is coded under: one
2204/// tile, one transform size per block, no in-loop filter parameters yet
2205/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
2206/// CDEF strengths in once the tile is coded), no CDF adaptation
2207/// and no tool the tile writer does not code.
2208///
2209/// # Errors
2210/// Returns an error when the picture is larger than the 16-bit frame size the
2211/// sequence header carries.
2212pub fn key_frame_headers(
2213 width: usize,
2214 height: usize,
2215 base_q_idx: u8,
2216) -> Result<(SequenceHeader, FrameHeader)> {
2217 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
2218}
2219
2220/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
2221/// studio (limited) range: what this crate's sequence header carried before
2222/// [`crate::encoder`]'s facade could configure it, and what
2223/// [`key_frame_headers`] still asks for.
2224fn unspecified_color_config() -> ColorConfig {
2225 ColorConfig {
2226 bit_depth: 8,
2227 mono_chrome: false,
2228 num_planes: 3,
2229 color_primaries: 2,
2230 transfer_characteristics: 2,
2231 matrix_coefficients: 2,
2232 color_range: false,
2233 subsampling_x: 1,
2234 subsampling_y: 1,
2235 chroma_sample_position: ChromaSamplePosition::Unknown,
2236 separate_uv_delta_q: false,
2237 }
2238}
2239
2240/// [`key_frame_headers`] with the sequence header's colour config named
2241/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
2242/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
2243/// which is all a player picks a colour transform from and which
2244/// [`crate::encoder::Colour`] is the facade's own name for.
2245///
2246/// `color_config` also carries the chroma shape, and that is what a coverage
2247/// witness needs: nothing in this crate's ENCODER codes a shape other than
2248/// 4:2:0, but a sequence header can still be written at any
2249/// `subsampling_x`/`subsampling_y` the spec allows, which is how the 4:4:0
2250/// header witness is built. It builds HEADERS only -- pair the pair it
2251/// returns with a tile from [`encode_key_frame`] (4:2:0) or
2252/// [`encode_key_frame_at_size`].
2253///
2254/// # Errors
2255/// The same as [`key_frame_headers`].
2256pub fn key_frame_headers_colour(
2257 width: usize,
2258 height: usize,
2259 base_q_idx: u8,
2260 color_config: ColorConfig,
2261) -> Result<(SequenceHeader, FrameHeader)> {
2262 let bits = |n: usize| -> Result<u32> {
2263 let n = u32::try_from(n).map_err(|_| too_large())?;
2264 if n == 0 || n > 1 << 16 {
2265 return Err(too_large());
2266 }
2267 Ok((32 - (n - 1).leading_zeros()).max(1))
2268 };
2269 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
2270 let (w, h) = (width as u32, height as u32);
2271 let seq = SequenceHeader {
2272 seq_profile: 0,
2273 operating_points: vec![OperatingPoint {
2274 seq_level_idx: 8,
2275 ..OperatingPoint::default()
2276 }],
2277 frame_width_bits,
2278 frame_height_bits,
2279 max_frame_width: w,
2280 max_frame_height: h,
2281 use_128x128_superblock: sb128_on(),
2282 // lane-fintra: the encoder's intra search offers the five recursive
2283 // filter-intra modes on eligible blocks, so the sequence bit is set
2284 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
2285 // off and restores the streams this encoder wrote before the lane).
2286 enable_filter_intra: filter_intra_on(),
2287 enable_intra_edge_filter: false,
2288 enable_order_hint: true,
2289 order_hint_bits: 7,
2290 enable_superres: false,
2291 // spec 5.9.19: with the sequence bit set every frame header carries
2292 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
2293 // pair for the whole frame, chosen by `crate::filter_search` -- so no
2294 // `cdef_idx` literal is coded in the tile and a frame that wants no
2295 // CDEF simply carries zero strengths.
2296 enable_cdef: true,
2297 enable_restoration: true,
2298 // SELECT (2) when this sequence's key frame detected screen content
2299 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
2300 // is then coded in every frame header, and only the frames that want
2301 // the palette syntax set it. 0 -- the forced-off form, no bit at all
2302 // -- otherwise, which is what every non-screen stream this encoder
2303 // writes still carries.
2304 seq_force_screen_content_tools: if seq_screen() {
2305 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
2306 } else {
2307 0
2308 },
2309 seq_force_integer_mv: 0,
2310 color_config,
2311 still_picture: false,
2312 reduced_still_picture_header: false,
2313 timing_info: None,
2314 decoder_model_info: None,
2315 initial_display_delay_present_flag: false,
2316 operating_point: 0,
2317 operating_point_idc: 0,
2318 frame_id_numbers_present_flag: false,
2319 delta_frame_id_length: 0,
2320 additional_frame_id_length: 0,
2321 enable_interintra_compound: false,
2322 enable_masked_compound: false,
2323 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
2324 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
2325 // header is byte-identical to the streams before this lane.
2326 enable_warped_motion: warp_on(),
2327 enable_dual_filter: false,
2328 enable_jnt_comp: false,
2329 enable_ref_frame_mvs: false,
2330 film_grain_params_present: false,
2331 };
2332 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
2333 // own (true, unpadded) width and height, not from any block-grid
2334 // alignment — a decoder derives these straight from `frame_width`/
2335 // `frame_height` below, so this must match it exactly.
2336 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
2337 let header = FrameHeader {
2338 frame_type: FrameType::Key,
2339 frame_is_intra: true,
2340 show_frame: true,
2341 error_resilient_mode: true,
2342 // The tile writer keeps the same CDF state the decoder does and
2343 // updates it in the same order, so the frame lets the decoder adapt.
2344 disable_cdf_update: false,
2345 // Nothing reads the state this frame leaves behind: a key frame always
2346 // starts from the defaults, and this encoder emits one frame.
2347 disable_frame_end_update_cdf: true,
2348 force_integer_mv: true,
2349 refresh_frame_flags: 0xFF,
2350 primary_ref_frame: PRIMARY_REF_NONE,
2351 frame_width: w,
2352 frame_height: h,
2353 upscaled_width: w,
2354 render_width: w,
2355 render_height: h,
2356 mi_cols,
2357 mi_rows,
2358 tile_info: TileInfo {
2359 uniform_spacing: true,
2360 cols: 1,
2361 rows: 1,
2362 mi_col_starts: vec![0, mi_cols],
2363 mi_row_starts: vec![0, mi_rows],
2364 tile_size_bytes: 1,
2365 ..TileInfo::default()
2366 },
2367 quantization: QuantizationParams {
2368 base_q_idx,
2369 ..QuantizationParams::default()
2370 },
2371 tx_mode: TxMode::Largest,
2372 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
2373 // intra transform below 32x32, not only 16x16 -- the set this crate
2374 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
2375 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
2376 // so a decoder honouring the header picks the same CDF the writer
2377 // used only if this is set here too, not only on the inter variant
2378 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
2379 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
2380 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
2381 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
2382 // the arithmetic coder's `rng` register from the very first 8x8-leaf
2383 // luma transform onward with no symbol value ever differing.
2384 reduced_tx_set: true,
2385 ..FrameHeader::default()
2386 };
2387 Ok((seq, header))
2388}
2389
2390/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
2391/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
2392/// 1 still holds the key frame however long the GOP runs.
2393pub const GOLDEN_SLOT: u8 = 1;
2394
2395/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
2396/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
2397/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
2398/// one filter for the whole frame, which is what libaom does on this content
2399/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
2400/// stream, so a per-BLOCK filter search has no bits to win). The kernel
2401/// reaches the search, the trials and the recon through
2402/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
2403/// prediction the search priced are the same one.
2404/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the
2405/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
2406/// the witness that has to see a non-REGULAR kernel coded and decoded turns
2407/// it on through this while holding [`crate::speed::knob_write`].
2408static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
2409
2410/// Sets [`INTERP_OVERRIDE`]; `None` clears it.
2411#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
2412pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) {
2413 INTERP_OVERRIDE.store(
2414 filter.map_or(u8::MAX, |f| f as u8),
2415 std::sync::atomic::Ordering::Relaxed,
2416 );
2417}
2418
2419fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
2420 use ec_av1_syntax::InterpolationFilter as F;
2421 match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2422 0 => return F::Eighttap,
2423 1 => return F::EighttapSmooth,
2424 2 => return F::EighttapSharp,
2425 _ => {}
2426 }
2427 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2428 crate::envflags::var("EC_AV1_INTERP")
2429 .ok()
2430 .map(|v| match v.as_str() {
2431 "smooth" => F::EighttapSmooth,
2432 "sharp" => F::EighttapSharp,
2433 _ => F::Eighttap,
2434 })
2435 });
2436 ENV.unwrap_or(F::Eighttap)
2437}
2438
2439/// The frame header for a shown inter frame that predicts from the single
2440/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
2441/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
2442/// reused verbatim: an inter frame never changes the sequence.
2443///
2444/// # Errors
2445/// Returns an error under the same conditions as [`key_frame_headers`].
2446pub fn inter_frame_headers(
2447 width: usize,
2448 height: usize,
2449 base_q_idx: u8,
2450 order_hint: u32,
2451 last_slot: u8,
2452) -> Result<(SequenceHeader, FrameHeader)> {
2453 inter_frame_headers_slots(
2454 width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot,
2455 )
2456}
2457
2458/// [`inter_frame_headers`] with the three slots named apart: the one read as
2459/// `LAST_FRAME`, the one this frame refreshes, and the one read as
2460/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
2461/// so that the frame two back is still intact in the slot this one is about
2462/// to overwrite -- read before write, spec 7.20's decode order.
2463///
2464/// # Errors
2465/// As [`inter_frame_headers`].
2466pub fn inter_frame_headers_slots(
2467 width: usize,
2468 height: usize,
2469 base_q_idx: u8,
2470 order_hint: u32,
2471 last_slot: u8,
2472 self_slot: u8,
2473 altref_slot: u8,
2474) -> Result<(SequenceHeader, FrameHeader)> {
2475 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
2476 let header = FrameHeader {
2477 frame_type: FrameType::Inter,
2478 frame_is_intra: false,
2479 show_frame: true,
2480 error_resilient_mode: false,
2481 disable_cdf_update: false,
2482 // The tile writer hands its end-of-tile tables to the next frame
2483 // (`encode_sequence_with_ctx`), so the frame stores them the way the
2484 // decoder will load them (spec 7.20).
2485 disable_frame_end_update_cdf: false,
2486 force_integer_mv: false,
2487 order_hint,
2488 primary_ref_frame: 0,
2489 refresh_frame_flags: 1 << self_slot,
2490 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
2491 // names the slot this frame both predicts from and refreshes;
2492 // GOLDEN names slot 1, which the key frame wrote when it refreshed
2493 // all eight and which no inter frame ever overwrites, so it holds
2494 // the key frame's own picture for the whole GOP.
2495 ref_frame_idx: {
2496 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
2497 idx[3] = GOLDEN_SLOT;
2498 idx[6] = altref_slot;
2499 idx
2500 },
2501 // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`:
2502 // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's
2503 // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in
2504 // every frame this constructor builds, so no further guard is needed.
2505 allow_high_precision_mv: high_precision_mv_at(base_q_idx),
2506 // A FIXED frame-level filter, so no block codes an `interp_filter`
2507 // symbol. lane-obmc3 instrumented whether that costs anything: a
2508 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
2509 // (45941 B, the same point `lanes/libcen.report.md` matched) read
2510 // back through `EC_AV1_BITCENSUS=1 syntax_census` codes
2511 // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed
2512 // frame filter here too, so there are ZERO per-block filter bits at
2513 // stake on this content and the per-block switchable search was not
2514 // built (the charter's premise that libaom codes switchable interp
2515 // per block on film B is refuted by its own stream).
2516 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
2517 // lane-av1obmc: with this bit set every single-reference inter block
2518 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
2519 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
2520 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
2521 // to the OBMC knob rather than always on: with every block choosing
2522 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
2523 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
2524 // and stays byte-identical to the streams before this lane.
2525 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
2526 // `allow_warped_motion` besides -- which is what makes an eligible
2527 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
2528 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2529 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on(),
2530 allow_warped_motion: warp_on(),
2531 use_ref_frame_mvs: false,
2532 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
2533 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
2534 // set this crate carries a table for at 16x16 (see
2535 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
2536 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
2537 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
2538 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
2539 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
2540 // path) -- with this flag set, `get_tx_set`'s intra branch returns
2541 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
2542 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
2543 reduced_tx_set: true,
2544 ..key
2545 };
2546 Ok((seq, header))
2547}
2548
2549fn too_large() -> Error {
2550 Error::unsupported(
2551 "AV1 encode",
2552 "the picture is larger than a frame size can carry",
2553 )
2554}
2555
2556/// One plane of the picture being coded, and the reconstruction being built
2557/// beside it.
2558/// What one committed 4x4 cell left behind for the coefficient contexts of
2559/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
2560/// is the same state decode.rs records.
2561#[derive(Clone, Copy, Default, PartialEq, Eq)]
2562struct CoefCtx {
2563 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
2564 level: u8,
2565 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
2566 /// the DC itself was zero (tile.rs `dc_vote`).
2567 dc: i8,
2568}
2569
2570/// One plane's coefficient contexts, committed in CODING ORDER: the search
2571/// prices partition TREES, so the neighbour state a candidate reads has to be
2572/// whatever the blocks coded before it left -- the parent's committed
2573/// neighbours for a tree's first child, the just-committed sibling for the
2574/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
2575/// writer's two running bands is what makes that fall out: a trial commits
2576/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
2577/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
2578/// to its left is exactly what the tile writer's `Neighbours` bands will hold
2579/// when it gets there.
2580///
2581/// Before this map the pricer took both contexts as zero, which is exact for
2582/// a luma transform covering its whole block and the largest remaining row of
2583/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
2584#[derive(Default)]
2585struct CoefCtxMap {
2586 cells: Vec<CoefCtx>,
2587 stride: usize,
2588 /// Whether the transforms being priced right now are SMALLER than the
2589 /// block they sit in -- a `TxMode::Select` depth split
2590 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
2591 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
2592 /// trial cannot tell, and it is what decides whether luma reads context 0
2593 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
2594 tu_split: bool,
2595}
2596
2597/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
2598/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
2599/// padding-inclusive score the search used before lane-sse, which is how the
2600/// before/after arms of the straddling gate rows are read off ONE binary.
2601fn edge_sse() -> bool {
2602 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
2603 crate::envflags::var("EC_AV1_EDGESSE")
2604 .ok()
2605 .map(|v| v != "0")
2606 });
2607 ENV.unwrap_or(true)
2608}
2609
2610/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
2611/// through and the share of their raw squared error that sat in the padding
2612/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
2613/// it, but the numbers are an instrument, not a decision (class
2614/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
2615/// without this census no gate row can say the clip fires at all).
2616fn edge_census() -> bool {
2617 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
2618 crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1")
2619 });
2620 *ENV
2621}
2622
2623/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
2624/// 128x128): how many scores clipped, the inside squared error they kept and
2625/// the padding squared error they dropped.
2626static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
2627 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
2628
2629/// One clipped score, for [`take_edge_census`].
2630fn record_edge_score(side: usize, inside: u64, padding: u64) {
2631 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
2632 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2633 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
2634 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
2635}
2636
2637/// The straddling-block census since the last call, and zero it: one
2638/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
2639#[must_use]
2640pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
2641 EDGE_SCORES
2642 .iter()
2643 .enumerate()
2644 .filter_map(|(log2, row)| {
2645 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
2646 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
2647 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
2648 (n != 0).then_some((1usize << log2, n, inside, padding))
2649 })
2650 .collect()
2651}
2652
2653struct Plane<'a> {
2654 source: &'a [u8],
2655 reconstruction: Vec<u8>,
2656 width: usize,
2657 height: usize,
2658 /// The frame's true, decodable extent in this plane's own units --
2659 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
2660 /// not `width`/`height` above, which is the padded coding-surface size.
2661 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
2662 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
2663 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
2664 /// this bound, even though the padded reconstruction buffer holds real
2665 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
2666 /// those instead of stopping here is what desyncs prediction at the true
2667 /// edge.
2668 true_width: usize,
2669 true_height: usize,
2670 /// This plane's own tile's pixel bounds, in this plane's units -- the
2671 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
2672 /// prediction never reaches across a tile edge even though the
2673 /// neighbouring tile's real samples sit right there in the shared
2674 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
2675 /// leaves every edge exactly as it was before tiles existed.
2676 tile_x0: usize,
2677 tile_y0: usize,
2678 tile_x1: usize,
2679 tile_y1: usize,
2680 /// [`CoefCtxMap`]: what the blocks already committed left for the
2681 /// coefficient contexts of the ones still being priced. Sized on the
2682 /// first commit, so a plane literal does not have to know its own extent
2683 /// twice.
2684 ctx: CoefCtxMap,
2685}
2686
2687impl Plane<'_> {
2688 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
2689 /// called at every superblock of the frame-raster search with the rect
2690 /// of the tile that superblock belongs to.
2691 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
2692 self.tile_x0 = x0;
2693 self.tile_y0 = y0;
2694 self.tile_x1 = x1.min(self.width);
2695 self.tile_y1 = y1.min(self.height);
2696 }
2697 /// The reconstructed samples a block at `(x, y)` predicts from: the row
2698 /// above it, the column to its left and the sample between them, each
2699 /// missing where the block sits against an edge of the frame.
2700 ///
2701 /// `reach` says whether the samples above the block's right and below its
2702 /// left are decoded, which is what a directional mode reads into; where
2703 /// they are not, or where the frame ends first, the edge is shorter and
2704 /// the predictor repeats its last sample, exactly as the decoder's clamp
2705 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
2706 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
2707 /// a free per mode per block, on the search's hottest path -- while an
2708 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
2709 /// samples, on the caller's stack.
2710 fn edges_into<'a>(
2711 &self,
2712 x: usize,
2713 y: usize,
2714 side: usize,
2715 reach: Reach,
2716 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
2717 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
2718 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
2719 // Even a block's *own* edge is clamped to the true frame bound, not
2720 // just a `reach` extension: libaom's `av1_predict_intra_block`
2721 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
2722 // this block's own right/bottom to the frame edge -- from
2723 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
2724 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
2725 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
2726 // samples the row/column above/left holds before the decoder starts
2727 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
2728 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
2729 // extent straddles that edge legally (`has_half`) -- the transform
2730 // still covers the whole block, but prediction does not get to read
2731 // real reconstructed pixels past the true edge for its own row/column,
2732 // only for the padded tail it invents.
2733 let own_across = x + side.min(self.true_width.saturating_sub(x));
2734 let across = if reach.above_right {
2735 own_across + side.min(self.true_width.saturating_sub(own_across))
2736 } else {
2737 own_across
2738 }
2739 .min(self.width);
2740 let own_down = y + side.min(self.true_height.saturating_sub(y));
2741 let down = if reach.below_left {
2742 own_down + side.min(self.true_height.saturating_sub(own_down))
2743 } else {
2744 own_down
2745 }
2746 .min(self.height);
2747 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
2748 // whose own origin already sits past the true edge -- only reachable
2749 // through a partition trial priced for comparison on a split this
2750 // frame's straddling quadrant will go on to refuse (see
2751 // `a_picture_off_the_block_grid_is_refused`), never through a block
2752 // this encoder actually commits. Such a block has no true-edge
2753 // samples above or left of it at all, same as `y == 0`/`x == 0`.
2754 let across = across.min(self.tile_x1);
2755 let down = down.min(self.tile_y1);
2756 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
2757 if let Some(n) = above_n {
2758 above_buf[..n].copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
2759 }
2760 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
2761 if let Some(n) = left_n {
2762 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
2763 *d = self.reconstruction[row * self.width + x - 1];
2764 }
2765 }
2766 let corner = (x > self.tile_x0 && y > self.tile_y0)
2767 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
2768 (
2769 above_n.map(|n| &above_buf[..n]),
2770 left_n.map(|n| &left_buf[..n]),
2771 corner,
2772 )
2773 }
2774
2775 /// Codes one block under one mode without committing it: hands back the
2776 /// levels, the block the decoder would reconstruct, the squared error
2777 /// against the source and an estimate of what the levels cost in bits.
2778 fn trial(
2779 &self,
2780 at: At,
2781 mode: u8,
2782 angle_delta: i32,
2783 base_q_idx: u8,
2784 deadzone: f64,
2785 fctx: &crate::decode::FrameCtx,
2786 ) -> Trial {
2787 self.trial_typed(
2788 at,
2789 mode,
2790 angle_delta,
2791 base_q_idx,
2792 deadzone,
2793 TxType::DctDct,
2794 fctx,
2795 )
2796 }
2797
2798 /// [`Self::trial`] under a named transform type -- what an intra chroma
2799 /// block gets, since chroma codes no `tx_type` symbol and the decoder
2800 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
2801 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
2802 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
2803 #[allow(clippy::too_many_arguments)]
2804 /// Sum of absolute differences between the source block at `(x, y)` and a
2805 /// `side x side` prediction, as the whole number it is.
2806 ///
2807 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
2808 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
2809 /// exactly, so no add here rounds and the order of the adds cannot change
2810 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
2811 /// integer division per sample -- is what lets the row walk vectorize.
2812 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
2813 let mut sad = 0u32;
2814 for row in 0..side {
2815 let source = &self.source[(y + row) * self.width + x..][..side];
2816 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
2817 sad += u32::from(s.abs_diff(p));
2818 }
2819 }
2820 f64::from(sad)
2821 }
2822
2823 /// Squared error between the source block at `(x, y)` and a reconstruction
2824 /// of it, over the part of the block that is INSIDE the true frame.
2825 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
2826 /// `255^2 * 64 * 64`, under 2^28.
2827 ///
2828 /// A block the frame edge cuts through is still coded whole -- the
2829 /// decoder reconstructs its outside samples too and the display crop
2830 /// throws them away -- so scoring the padding would rank a mode, a
2831 /// transform or a partition tree by how well it codes samples the source
2832 /// does not have (libaom clips the same way: `av1_dist_block` measures
2833 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
2834 /// edge pixels, so predicting it is nearly free, but coding coefficients
2835 /// for it spends real bits. Both gate films are superblock-aligned; this
2836 /// only reaches arbitrary export sizes (lane-sse, generalising
2837 /// lane-b64b's 64-root-only rescore of the 64 root).
2838 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
2839 let inside_rows = side.min(self.true_height.saturating_sub(y));
2840 let inside_cols = side.min(self.true_width.saturating_sub(x));
2841 let straddles = inside_rows < side || inside_cols < side;
2842 // The knob is read only for a block the edge cuts, so the interior
2843 // path -- the hot one -- carries no extra load at all.
2844 let (rows, cols) = match straddles && !edge_sse() {
2845 true => (side, side),
2846 false => (inside_rows, inside_cols),
2847 };
2848 let mut sse = 0u64;
2849 for row in 0..rows {
2850 let source = &self.source[(y + row) * self.width + x..][..cols];
2851 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
2852 let d = u32::from(s.abs_diff(r));
2853 sse += u64::from(d * d);
2854 }
2855 }
2856 if straddles && edge_census() {
2857 let (mut inside, mut whole) = (0u64, 0u64);
2858 for row in 0..side {
2859 let source = &self.source[(y + row) * self.width + x..][..side];
2860 for (col, (&s, &r)) in source
2861 .iter()
2862 .zip(&reconstruction[row * side..][..side])
2863 .enumerate()
2864 {
2865 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
2866 whole += d;
2867 if row < inside_rows && col < inside_cols {
2868 inside += d;
2869 }
2870 }
2871 }
2872 record_edge_score(side, inside, whole - inside);
2873 }
2874 sse as f64
2875 }
2876
2877 fn trial_typed(
2878 &self,
2879 at: At,
2880 mode: u8,
2881 // This block's `angle_delta_y`/`angle_delta_uv` (spec
2882 // `read_intra_angle_info`, -3..=3), zero for every non-directional
2883 // mode -- the predictor's own `angle_delta` argument.
2884 angle_delta: i32,
2885 base_q_idx: u8,
2886 deadzone: f64,
2887 tx_type: TxType,
2888 fctx: &crate::decode::FrameCtx,
2889 ) -> Trial {
2890 let At {
2891 x, y, side, reach, ..
2892 } = at;
2893 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2894 let (above, left, corner) =
2895 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2896 // Per-candidate scratch on the search's hottest path, so both buffers
2897 // live on the stack -- `side` is at most `BLOCK` -- rather than
2898 // costing a malloc/free pair per trial (`mc_trial` already does this).
2899 let mut prediction = [0u8; BLOCK * BLOCK];
2900 let prediction = &mut prediction[..side * side];
2901 intra_predict_u8(
2902 mode,
2903 angle_delta,
2904 above,
2905 left,
2906 corner,
2907 side,
2908 side,
2909 false,
2910 false,
2911 prediction,
2912 fctx,
2913 );
2914
2915 let mut residual = [0i32; BLOCK * BLOCK];
2916 let residual = &mut residual[..side * side];
2917 for row in 0..side {
2918 for col in 0..side {
2919 residual[row * side + col] =
2920 i32::from(self.source[(y + row) * self.width + x + col])
2921 - i32::from(prediction[row * side + col]);
2922 }
2923 }
2924 #[cfg(test)]
2925 let t = stage_start();
2926 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
2927 // reconstruction below and the price further down are both of the
2928 // grid this trial would really code.
2929 let (levels, rdoq_bits) = if rdoq_on() {
2930 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2931 residual,
2932 side,
2933 8,
2934 i32::from(base_q_idx),
2935 deadzone,
2936 tx_type,
2937 );
2938 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2939 let bits = crate::tile::rdoq(
2940 &mut levels,
2941 &scaled,
2942 side,
2943 base_q_idx,
2944 at.set,
2945 skip_ctx,
2946 sign_ctx,
2947 rdoq_lambda(),
2948 tx_type,
2949 );
2950 (levels, Some(bits))
2951 } else {
2952 (
2953 forward_and_quantize_typed(
2954 residual,
2955 side,
2956 8,
2957 i32::from(base_q_idx),
2958 deadzone,
2959 tx_type,
2960 ),
2961 None,
2962 )
2963 };
2964 // lane-av1speed2: 60% of the transform units of an inter stream carry
2965 // no coefficient at all, and the square entry point re-inflates that
2966 // case into `side * side` zeros (one allocate-and-memset per trial)
2967 // only for the sum below to add them to the prediction. The `_wh`
2968 // entry hands back the empty all-zero marker instead, and a zero
2969 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
2970 // `p` for a `u8`, so the bytes are the same.
2971 let coded = dequant_and_inverse_typed_wh(
2972 &levels,
2973 side,
2974 side,
2975 8,
2976 i32::from(base_q_idx),
2977 0,
2978 0,
2979 tx_type,
2980 None,
2981 );
2982 #[cfg(test)]
2983 stage_since(2, t);
2984
2985 let reconstruction: Vec<u8> = if coded.is_empty() {
2986 prediction.to_vec()
2987 } else {
2988 prediction
2989 .iter()
2990 .zip(&coded)
2991 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2992 .collect()
2993 };
2994 let sse = self.block_sse(x, y, side, &reconstruction);
2995 // What the levels cost is priced through the same CDFs the tile writer
2996 // will code them with, so the search ranks modes -- and the partition
2997 // trial ranks trees -- by the bits they actually spend.
2998 #[cfg(test)]
2999 let t = stage_start();
3000 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
3001 // What the search used before it could price a block exactly: a
3002 // level costs its magnitude's width plus a sign and a run. Kept
3003 // reachable from the sweep so the two rate terms can be compared
3004 // on one build.
3005 levels
3006 .iter()
3007 .filter(|&&level| level != 0)
3008 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
3009 .sum()
3010 } else if let Some(bits) = rdoq_bits {
3011 // Already priced, against the grid the pass settled on.
3012 bits
3013 } else {
3014 {
3015 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
3016 crate::tile::coeff_bits_typed(
3017 &levels,
3018 at.set,
3019 crate::decode::q_ctx_of(base_q_idx),
3020 skip_ctx,
3021 sign_ctx,
3022 tx_type,
3023 )
3024 }
3025 };
3026 #[cfg(test)]
3027 stage_since(3, t);
3028 Trial {
3029 levels,
3030 reconstruction,
3031 sse,
3032 bits,
3033 }
3034 }
3035
3036 /// [`Self::trial`] with the prediction already built, so that an inter
3037 /// block's motion-compensated prediction can go through the same
3038 /// residual/quantize/reconstruct path an intra block's does. `skip`
3039 /// takes the prediction as the reconstruction outright, coding no
3040 /// residual at all — what a `NEARESTMV` block that names no coefficients
3041 /// codes.
3042 #[allow(clippy::too_many_arguments)]
3043 fn code_from_prediction(
3044 &self,
3045 x: usize,
3046 y: usize,
3047 side: usize,
3048 prediction: &[u8],
3049 skip: bool,
3050 base_q_idx: u8,
3051 deadzone: f64,
3052 set: TxbSet,
3053 ) -> Trial {
3054 self.code_from_prediction_typed(
3055 x,
3056 y,
3057 side,
3058 prediction,
3059 skip,
3060 base_q_idx,
3061 deadzone,
3062 set,
3063 TxType::DctDct,
3064 )
3065 }
3066
3067 /// [`Self::code_from_prediction`] coding the residual with a NAMED
3068 /// transform type (lane-txset2): the inter luma sets carry a two-type
3069 /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
3070 /// a symbol for, and [`commit_inter_luma`] prices both through this.
3071 #[allow(clippy::too_many_arguments)]
3072 fn code_from_prediction_typed(
3073 &self,
3074 x: usize,
3075 y: usize,
3076 side: usize,
3077 prediction: &[u8],
3078 skip: bool,
3079 base_q_idx: u8,
3080 deadzone: f64,
3081 set: TxbSet,
3082 tx_type: TxType,
3083 ) -> Trial {
3084 if skip {
3085 let sse = self.block_sse(x, y, side, prediction);
3086 return Trial {
3087 levels: vec![0i32; side * side],
3088 reconstruction: prediction.to_vec(),
3089 sse,
3090 bits: 0.0,
3091 };
3092 }
3093 // A 64x64 root's residual is four times the scratch every other
3094 // block coder here sizes for [`BLOCK`]; only that one case pays for
3095 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
3096 let mut small = [0i32; BLOCK * BLOCK];
3097 let mut big = if side > BLOCK {
3098 vec![0i32; side * side]
3099 } else {
3100 Vec::new()
3101 };
3102 let residual: &mut [i32] = if side > BLOCK {
3103 &mut big
3104 } else {
3105 &mut small[..side * side]
3106 };
3107 for row in 0..side {
3108 for col in 0..side {
3109 residual[row * side + col] =
3110 i32::from(self.source[(y + row) * self.width + x + col])
3111 - i32::from(prediction[row * side + col]);
3112 }
3113 }
3114 #[cfg(test)]
3115 let t = stage_start();
3116 // lane-rdoq, as in [`Self::trial_typed`].
3117 let (levels, rdoq_bits) = if rdoq_on() {
3118 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
3119 residual,
3120 side,
3121 8,
3122 i32::from(base_q_idx),
3123 deadzone,
3124 tx_type,
3125 );
3126 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3127 let bits = crate::tile::rdoq(
3128 &mut levels,
3129 &scaled,
3130 side,
3131 base_q_idx,
3132 set,
3133 skip_ctx,
3134 sign_ctx,
3135 rdoq_lambda(),
3136 tx_type,
3137 );
3138 (levels, Some(bits))
3139 } else {
3140 (
3141 forward_and_quantize_typed(
3142 residual,
3143 side,
3144 8,
3145 i32::from(base_q_idx),
3146 deadzone,
3147 tx_type,
3148 ),
3149 None,
3150 )
3151 };
3152 // The same all-zero shortcut [`Self::trial_typed`] takes.
3153 let coded = dequant_and_inverse_typed_wh(
3154 &levels,
3155 side,
3156 side,
3157 8,
3158 i32::from(base_q_idx),
3159 0,
3160 0,
3161 tx_type,
3162 None,
3163 );
3164 #[cfg(test)]
3165 stage_since(2, t);
3166 let reconstruction: Vec<u8> = if coded.is_empty() {
3167 prediction.to_vec()
3168 } else {
3169 prediction
3170 .iter()
3171 .zip(&coded)
3172 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
3173 .collect()
3174 };
3175 let sse = self.block_sse(x, y, side, &reconstruction);
3176 // A 64-point transform codes only its top-left 32x32 corner (spec
3177 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
3178 // key frame writer takes a 32x32 level grid for one). The inverse
3179 // above reads the whole 64x64 array, but the price below and the
3180 // levels the writer takes are that corner.
3181 let levels = if side > BLOCK {
3182 coded_corner(&levels, side, BLOCK)
3183 } else {
3184 levels
3185 };
3186 #[cfg(test)]
3187 let t = stage_start();
3188 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
3189 levels
3190 .iter()
3191 .filter(|&&level| level != 0)
3192 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
3193 .sum()
3194 } else if let Some(bits) = rdoq_bits {
3195 bits
3196 } else {
3197 {
3198 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3199 crate::tile::coeff_bits_typed(
3200 &levels,
3201 set,
3202 crate::decode::q_ctx_of(base_q_idx),
3203 skip_ctx,
3204 sign_ctx,
3205 tx_type,
3206 )
3207 }
3208 };
3209 #[cfg(test)]
3210 stage_since(3, t);
3211 Trial {
3212 levels,
3213 reconstruction,
3214 sse,
3215 bits,
3216 }
3217 }
3218
3219 /// Codes this block's luma at transform depth `depth`: the
3220 /// `(side >> depth)^2` transform units in raster order, each predicted
3221 /// from the reconstruction the units before it left behind -- exactly
3222 /// what the decoder's multi-transform-unit branch does (decode.rs
3223 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
3224 /// reconstructed on its own. Commits the result and hands back the
3225 /// block-coordinate levels, the block's squared error and what its
3226 /// coefficients cost.
3227 #[allow(clippy::too_many_arguments)]
3228 fn code_tx_depth(
3229 &mut self,
3230 at: At,
3231 mode: u8,
3232 angle_delta: i32,
3233 depth: usize,
3234 // This block's `filter_intra_mode` when it is coded with one, in
3235 // which case every transform unit predicts recursively off the
3236 // reconstruction the units before it left -- what the decoder does
3237 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
3238 // `filter_intra`), not once over the whole block.
3239 filter_intra: Option<u8>,
3240 search: &Search,
3241 fctx: &crate::decode::FrameCtx,
3242 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
3243 let At {
3244 x, y, side, reach, ..
3245 } = at;
3246 let tx = side >> depth;
3247 let n = 1usize << depth;
3248 let set = luma_set_for(
3249 match tx {
3250 32 => TxbSet::Luma32,
3251 16 => TxbSet::Luma16,
3252 8 => TxbSet::Luma8,
3253 _ => TxbSet::Luma4,
3254 },
3255 search.screen,
3256 );
3257 let mut levels = vec![0i32; side * side];
3258 census_add(4, n * n);
3259 // A unit smaller than its block reads the neighbour magnitude table
3260 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
3261 self.ctx.tu_split = n > 1;
3262 let (mut sse, mut bits) = (0.0, 0.0);
3263 // One entry per unit at its own `tu_row * n + tu_col`, which is how
3264 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
3265 // frame edge cuts away is never coded there, so a compacted list
3266 // would slide every later unit's type onto the wrong transform.
3267 let mut tx_types = vec![TxType::DctDct; n * n];
3268 for tu_row in 0..n {
3269 for tu_col in 0..n {
3270 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3271 let tu = At {
3272 x: x + col_off,
3273 y: y + row_off,
3274 side: tx,
3275 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
3276 set,
3277 };
3278 let trial = match filter_intra {
3279 Some(fi) => {
3280 let (mut above_buf, mut left_buf) =
3281 ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3282 let (above, left, corner) = self.edges_into(
3283 tu.x,
3284 tu.y,
3285 tx,
3286 tu.reach,
3287 &mut above_buf,
3288 &mut left_buf,
3289 );
3290 let mut prediction = vec![0u8; tx * tx];
3291 filter_intra_predict_u8(
3292 usize::from(fi),
3293 above,
3294 left,
3295 corner,
3296 tx,
3297 &mut prediction,
3298 fctx,
3299 );
3300 self.code_from_prediction(
3301 tu.x,
3302 tu.y,
3303 tx,
3304 &prediction,
3305 false,
3306 search.base_q_idx,
3307 search.deadzone,
3308 set,
3309 )
3310 }
3311 None => {
3312 // lane-txset: the unit picks its own transform type
3313 // out of the set the writer can name it in, priced
3314 // through the same RDOQ'd trial path (its `bits`
3315 // already carry the `tx_type` symbol itself).
3316 let mut best: Option<(f64, TxType, Trial)> = None;
3317 for &tx_type in tx_type_candidates(set, search.screen) {
3318 let candidate = self.trial_typed(
3319 tu,
3320 mode,
3321 angle_delta,
3322 search.base_q_idx,
3323 search.deadzone,
3324 tx_type,
3325 fctx,
3326 );
3327 // lane-txi: a non-`DCT_DCT` type is charged its
3328 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
3329 // search's weight (default 1 = unchanged). The
3330 // film rows buy 0.04 dB for 1.2% more bytes at
3331 // weight 1 on every frame and every PLANE, key
3332 // frame included -- a rate term this decision
3333 // under-charges (class
3334 // `rd-rate-term-calibration`), not the
3335 // propagation loss the leaves would have shown.
3336 let cost = candidate.sse
3337 + search.lambda * candidate.bits
3338 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
3339 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
3340 best = Some((cost, tx_type, candidate));
3341 }
3342 }
3343 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
3344 tx_types[tu_row * n + tu_col] = tx_type;
3345 TX_TYPE_HITS[tx_type as usize]
3346 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3347 trial
3348 }
3349 };
3350 sse += trial.sse;
3351 bits += trial.bits;
3352 self.commit(tu.x, tu.y, tx, &trial);
3353 for row in 0..tx {
3354 levels[(row_off + row) * side + col_off..][..tx]
3355 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3356 }
3357 }
3358 }
3359 self.ctx.tu_split = false;
3360 (levels, sse, bits, tx_types)
3361 }
3362
3363 /// Writes a trial's reconstruction back into the plane, and the
3364 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
3365 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
3366 for row in 0..side {
3367 self.reconstruction[(y + row) * self.width + x..][..side]
3368 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
3369 }
3370 self.commit_ctx(x, y, side, &trial.levels);
3371 }
3372
3373 /// Publishes one committed transform's own context over every 4x4 cell it
3374 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
3375 /// which is what the writer will read when it reaches the next block.
3376 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
3377 if self.ctx.cells.is_empty() {
3378 self.ctx.stride = self.width.div_ceil(4);
3379 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
3380 }
3381 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
3382 let state = CoefCtx {
3383 level: cul,
3384 dc: match levels[0].signum() {
3385 0 => 0,
3386 -1 => -1,
3387 _ => 1,
3388 },
3389 };
3390 let n = (side / 4).max(1);
3391 // Only up to the frame's TRUE extent: the writer's own
3392 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
3393 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
3394 // and leaves the cells past it uncoded even mid-block, so a
3395 // straddling block publishes context for its inside part only.
3396 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
3397 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
3398 for row in 0..rows {
3399 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3400 let end = (start + cols).min(self.ctx.cells.len());
3401 if start < end {
3402 self.ctx.cells[start..end].fill(state);
3403 }
3404 }
3405 }
3406
3407 /// A block committed without any residual at all ([`ibc_commit`]): the
3408 /// cells it covers coded nothing, and leaving an earlier trial's state
3409 /// there would price its neighbours off a block that was never coded.
3410 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
3411 self.commit_ctx(x, y, side, &[0i32]);
3412 }
3413
3414 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
3415 /// plane reads, off what the blocks before it in coding order committed
3416 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
3417 /// the above/left neighbours coded anything (tile.rs
3418 /// `write_block_planes`), luma reads context 0 when its transform covers
3419 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
3420 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
3421 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
3422 /// the same neighbours (tile.rs `dc_sign_ctx`).
3423 ///
3424 /// A neighbour outside this plane's own TILE does not exist, exactly as
3425 /// the writer's per-tile `Neighbours` bands start blank.
3426 ///
3427 /// CLOSED (lane-av1straddle): the decisions this price changes used to
3428 /// make `decode_stream_round_trips_an_odd_size_gop` and
3429 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
3430 /// fail at 216x96. Never this map: the writer coded the phantom
3431 /// transform units of a right-edge-straddling 32x32 (tile.rs
3432 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
3433 /// like decode.rs and libaom), which libdav1d and libaom both refused
3434 /// outright while a decision change was what first walked into it.
3435 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
3436 if self.ctx.cells.is_empty() {
3437 return (0, 0);
3438 }
3439 let n = (side / 4).max(1);
3440 let (cx, cy) = (x / 4, y / 4);
3441 let (mut top, mut left) = (0u8, 0u8);
3442 let mut vote = 0i32;
3443 if y > self.tile_y0 && cy > 0 {
3444 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
3445 top |= cell.level;
3446 vote += i32::from(cell.dc);
3447 }
3448 }
3449 if x > self.tile_x0 && cx > 0 {
3450 for row in 0..n {
3451 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
3452 left |= cell.level;
3453 vote += i32::from(cell.dc);
3454 }
3455 }
3456 let skip_ctx = if set.is_chroma() {
3457 usize::from(top != 0) + usize::from(left != 0)
3458 } else if self.ctx.tu_split {
3459 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3460 } else {
3461 0
3462 };
3463 let sign_ctx = match vote.signum() {
3464 0 => 0,
3465 -1 => 1,
3466 _ => 2,
3467 };
3468 (skip_ctx, sign_ctx)
3469 }
3470
3471 /// The source samples of one square, contiguous — what a motion search
3472 /// compares its candidates' predictions against ([`motion::search`]'s
3473 /// `source`), since [`Self::source`] itself is the whole plane, strided
3474 /// by [`Self::width`].
3475 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
3476 rows_of(self.source, self.width, x, y, side)
3477 }
3478
3479 /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
3480 /// root's own HORZ/VERT motion search.
3481 fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
3482 let mut out = vec![0u8; w * h];
3483 for row in 0..h {
3484 out[row * w..][..w].copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3485 }
3486 out
3487 }
3488
3489 /// The reconstructed samples of one square, so that a partition trial can
3490 /// be undone.
3491 /// The reconstructed samples of one square AND the coefficient contexts
3492 /// its cells hold, so that a partition trial can be undone whole: a
3493 /// losing trial that left its own nz/DC state behind would price the
3494 /// blocks after it off a block the tile writer never codes.
3495 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
3496 (
3497 rows_of(&self.reconstruction, self.width, x, y, side),
3498 self.ctx_rows(x, y, side),
3499 )
3500 }
3501
3502 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
3503 if self.ctx.cells.is_empty() {
3504 return Vec::new();
3505 }
3506 let n = (side / 4).max(1);
3507 (0..n)
3508 .flat_map(|row| {
3509 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3510 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
3511 })
3512 .collect()
3513 }
3514
3515 /// Puts a snapshot back.
3516 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
3517 for row in 0..side {
3518 self.reconstruction[(y + row) * self.width + x..][..side]
3519 .copy_from_slice(&saved.0[row * side..][..side]);
3520 }
3521 if saved.1.is_empty() {
3522 return;
3523 }
3524 let n = (side / 4).max(1);
3525 for row in 0..n {
3526 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3527 let end = (start + n).min(self.ctx.cells.len());
3528 if start < end {
3529 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
3530 }
3531 }
3532 }
3533
3534 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
3535 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
3536 /// prescreen by the identical rule rather than a second one that could
3537 /// drift from it.
3538 fn intra_scores(
3539 &self,
3540 at: At,
3541 modes: &[u8],
3542 mode_bits: &[f64; 13],
3543 lambda: f64,
3544 fctx: &crate::decode::FrameCtx,
3545 ) -> Vec<(f64, u8)> {
3546 let At {
3547 x, y, side, reach, ..
3548 } = at;
3549 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3550 let (above, left, corner) =
3551 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3552 modes
3553 .iter()
3554 .map(|&mode| {
3555 let mut prediction = vec![0u8; side * side];
3556 intra_predict_u8(
3557 mode,
3558 0,
3559 above,
3560 left,
3561 corner,
3562 side,
3563 side,
3564 false,
3565 false,
3566 &mut prediction,
3567 fctx,
3568 );
3569 let sad = self.block_sad(x, y, side, &prediction);
3570 (sad + lambda * mode_bits[usize::from(mode)], mode)
3571 })
3572 .collect()
3573 }
3574
3575 /// Codes one block under every mode the search offers (or, when
3576 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
3577 /// pre-pass plus DC) and commits the one whose squared error and
3578 /// estimated rate come out cheapest.
3579 ///
3580 /// The prediction is built once per mode regardless -- the full RD trial
3581 /// needs it too -- so ranking modes by SAD on that same prediction before
3582 /// running the expensive part (forward transform, quantize, reconstruct,
3583 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
3584 /// only to sum.
3585 fn search_block(
3586 &mut self,
3587 at: At,
3588 search: &Search,
3589 mode_bits: &[f64; 13],
3590 fctx: &crate::decode::FrameCtx,
3591 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
3592 let At {
3593 x, y, side, reach, ..
3594 } = at;
3595 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3596 let (above, left, corner) =
3597 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3598 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
3599 // the census reports it), so summing it under the default unpruned
3600 // search is `side * side` absolute differences per mode spent on a
3601 // number no one reads.
3602 let want_sad = search.top_k.is_some() || census_on();
3603 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
3604 .modes
3605 .iter()
3606 .map(|&mode| {
3607 let mut prediction = vec![0u8; side * side];
3608 intra_predict_u8(
3609 mode,
3610 0,
3611 above,
3612 left,
3613 corner,
3614 side,
3615 side,
3616 false,
3617 false,
3618 &mut prediction,
3619 fctx,
3620 );
3621 let sad = if want_sad {
3622 self.block_sad(x, y, side, &prediction)
3623 } else {
3624 0.0
3625 };
3626 (
3627 sad + search.lambda * mode_bits[usize::from(mode)],
3628 mode,
3629 prediction,
3630 )
3631 })
3632 .collect();
3633 if let Some(k) = search.top_k {
3634 if k < scored.len() {
3635 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
3636 let dc_entry = dc_pos.map(|i| scored.remove(i));
3637 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3638 scored.truncate(if dc_entry.is_some() {
3639 k.saturating_sub(1)
3640 } else {
3641 k
3642 });
3643 if let Some(dc_entry) = dc_entry {
3644 scored.push(dc_entry);
3645 }
3646 }
3647 }
3648 let ranking: Vec<(f64, u8)> = if census_on() {
3649 scored
3650 .iter()
3651 .map(|&(score, mode, _)| (score, mode))
3652 .collect()
3653 } else {
3654 Vec::new()
3655 };
3656 census_add(0, 1);
3657 census_add(1, scored.len());
3658 let mut best: Option<(f64, u8, Trial)> = None;
3659 for (_, mode, prediction) in scored {
3660 let trial = self.code_from_prediction(
3661 x,
3662 y,
3663 side,
3664 &prediction,
3665 false,
3666 search.base_q_idx,
3667 search.deadzone,
3668 at.set,
3669 );
3670 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
3671 if best
3672 .as_ref()
3673 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
3674 {
3675 best = Some((cost, mode, trial));
3676 }
3677 }
3678 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
3679 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
3680 // directional modes each carry a -3..=3 delta, three degrees a step,
3681 // which the writer has always coded as ZERO because nothing searched
3682 // it. Refined on the winning mode only -- libaom's own ordering, and
3683 // six extra trials on the directional blocks instead of on every
3684 // block times every mode. The edges are the ones the base angle
3685 // already read (`enable_intra_edge_filter` is off in this encoder's
3686 // sequence header, so no delta changes which samples exist), and the
3687 // predictor is the decoder's, `angle_delta` argument and all.
3688 let mut angle_delta = 0i32;
3689 // Not on a screen frame: measured on the 5-row native gate, the
3690 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
3691 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
3692 // synthetic edges land on the base angles, so every delta there buys
3693 // a symbol and no prediction. Same `search.screen` gate palette and
3694 // intrabc already stand behind.
3695 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
3696 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
3697 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
3698 let mut prediction = vec![0u8; side * side];
3699 for delta in [-3i32, -2, -1, 1, 2, 3] {
3700 intra_predict_u8(
3701 mode,
3702 delta,
3703 above,
3704 left,
3705 corner,
3706 side,
3707 side,
3708 false,
3709 false,
3710 &mut prediction,
3711 fctx,
3712 );
3713 let candidate = self.code_from_prediction(
3714 x,
3715 y,
3716 side,
3717 &prediction,
3718 false,
3719 search.base_q_idx,
3720 search.deadzone,
3721 at.set,
3722 );
3723 let bits =
3724 symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3725 - zero_bits;
3726 let cost_d = candidate.sse
3727 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
3728 if cost_d < cost {
3729 cost = cost_d;
3730 angle_delta = delta;
3731 trial = candidate;
3732 }
3733 }
3734 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
3735 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3736 }
3737 // lane-txset: the block's own transform type, searched on the mode
3738 // and angle the trials above settled -- the same ordering the angle
3739 // refinement uses, and the same RD terms.
3740 let mut tx_type = TxType::DctDct;
3741 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
3742 let candidate = self.trial_typed(
3743 at,
3744 mode,
3745 angle_delta,
3746 search.base_q_idx,
3747 search.deadzone,
3748 candidate_type,
3749 fctx,
3750 );
3751 let cost_t =
3752 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3753 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3754 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3755 // block's true one for the caller's own decision.
3756 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3757 cost = cost_t;
3758 tx_type = candidate_type;
3759 trial = candidate;
3760 }
3761 }
3762 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3763 if census_on() {
3764 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
3765 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3766 }
3767 self.commit(x, y, side, &trial);
3768 // A 64-point transform codes only its top-left 32x32 corner, which is
3769 // the grid `code_from_prediction` hands back (lane-i64).
3770 (
3771 coeffs(&trial.levels, side.min(BLOCK)),
3772 mode,
3773 angle_delta,
3774 cost,
3775 tx_type,
3776 )
3777 }
3778}
3779
3780/// Where one block sits in its plane, and how far past its own edges its
3781/// prediction may read.
3782#[derive(Clone, Copy)]
3783struct At {
3784 x: usize,
3785 y: usize,
3786 side: usize,
3787 reach: Reach,
3788 /// Which of the tile writer's coefficient tables this block's levels are
3789 /// coded with, and so which the search prices them through.
3790 set: TxbSet,
3791}
3792
3793/// Which of the samples past a block's own edges the decoder has decoded by
3794/// the time it predicts the block, and so which a directional mode may read.
3795///
3796/// The decoder derives these from its `BlockDecoded` flags, which are cleared
3797/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
3798/// that map, this reads the answer the same way libaom and rav1e do: for a
3799/// block whose transform covers it whole, whether the samples above its right
3800/// (or below its left) are decoded depends only on where the block sits inside
3801/// its 64x64 superblock, which is a pinned table per block size.
3802#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3803pub(crate) struct Reach {
3804 pub(crate) above_right: bool,
3805 pub(crate) below_left: bool,
3806}
3807
3808/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
3809/// libaom): for a block that is neither in the superblock's top row nor its
3810/// rightmost column, whether the block above and to its right is coded before
3811/// it. Indexed by the block's position in the superblock, in blocks of its own
3812/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
3813/// 128, not this crate's 64 superblock -- bit by bit from the low end.
3814const HAS_TOP_RIGHT: [&[u8]; 4] = [
3815 &[255, 85, 119, 85, 127, 85, 119, 85],
3816 &[95, 87],
3817 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
3818 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
3819 &[
3820 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
3821 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
3822 ],
3823 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
3824 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
3825 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
3826 // with side 4 outside a TX4 split; without their own row they clamped
3827 // into the 8x8 table and read above-right samples the decoder has not
3828 // written yet (all-zero pixels in the bottom-right triangle of a
3829 // directional 4x4 leaf).
3830 &[
3831 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
3832 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
3833 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
3834 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
3835 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
3836 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
3837 119, 119, 119, 119, 85, 85, 85, 85,
3838 ],
3839];
3840
3841/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
3842/// left.
3843const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
3844 &[84, 16, 84, 0, 84, 16, 84, 0],
3845 &[4, 4],
3846 // has_bl_8x8 (libaom av1/common/reconintra.c)
3847 &[
3848 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
3849 84, 85, 16, 17, 84, 85, 0, 0,
3850 ],
3851 // has_bl_4x4 (same source, same order).
3852 &[
3853 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
3854 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,
3855 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
3856 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,
3857 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
3858 85, 85, 0, 0, 0, 0,
3859 ],
3860];
3861
3862/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
3863/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
3864/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
3865/// rather than in raster order, so the bottom-left square's top-right
3866/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
3867/// libaom switches tables on the partition type (`get_has_tr_table`); the
3868/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
3869/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
3870/// lane-part32 r5 caught reading undecoded samples.
3871const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
3872 // has_tr_vert_16x16
3873 &[255, 0, 119, 0, 127, 0, 119, 0],
3874 // has_tr_vert_32x32
3875 &[15, 7],
3876 // has_tr_vert_8x8
3877 &[
3878 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
3879 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
3880 ],
3881];
3882
3883/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
3884const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
3885 // has_bl_vert_16x16
3886 &[254, 16, 254, 0, 254, 16, 254, 0],
3887 // has_bl_vert_32x32
3888 &[14, 14],
3889 // has_bl_vert_8x8
3890 &[
3891 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
3892 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
3893 ],
3894];
3895
3896thread_local! {
3897 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
3898 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
3899 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
3900 /// threading one bool through this crate's already twenty-argument
3901 /// `decode_block` would touch every call site instead of the two arms
3902 /// that need it.
3903 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3904}
3905
3906/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
3907pub(crate) struct VertAbGuard(bool);
3908
3909impl Drop for VertAbGuard {
3910 fn drop(&mut self) {
3911 VERT_AB_PARTITION.with(|c| c.set(self.0));
3912 }
3913}
3914
3915/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
3916/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
3917/// so no byte is retyped). Each is indexed by
3918/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
3919/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
3920/// superblock grid; on this crate's 64-pixel superblock the highest index a
3921/// shape can reach stays inside its own table, so no wrap is involved.
3922///
3923/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
3924/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
3925/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
3926/// 10 of the 21 reachable superblock positions for above-right and 7 for
3927/// below-left.
3928/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3929const HAS_TR_4X8: [u8; 64] = [
3930 255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255,
3931 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119,
3932 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127,
3933 127, 127, 127, 119, 119, 119, 119,
3934];
3935/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3936const HAS_BL_4X8: [u8; 64] = [
3937 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,
3938 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,
3939 1, 1, 16, 17, 17, 17, 0, 0, 0, 0,
3940];
3941/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3942const HAS_TR_8X4: [u8; 64] = [
3943 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,
3944 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,
3945 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0,
3946];
3947/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3948const HAS_BL_8X4: [u8; 64] = [
3949 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254,
3950 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255,
3951 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0,
3952];
3953/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3954const HAS_TR_8X16: [u8; 16] = [
3955 255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119,
3956];
3957/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3958const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
3959/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3960const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
3961/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3962const HAS_BL_16X8: [u8; 16] = [
3963 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0,
3964];
3965/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3966const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
3967/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3968const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
3969/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3970const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
3971/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3972const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
3973/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3974const HAS_TR_32X64: [u8; 1] = [127];
3975/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3976const HAS_BL_32X64: [u8; 1] = [0];
3977/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3978const HAS_TR_64X32: [u8; 1] = [19];
3979/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3980const HAS_BL_64X32: [u8; 1] = [34];
3981/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3982const HAS_TR_4X16: [u8; 32] = [
3983 255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255,
3984 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127,
3985];
3986/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3987const HAS_BL_4X16: [u8; 32] = [
3988 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,
3989];
3990/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3991const HAS_TR_16X4: [u8; 32] = [
3992 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,
3993 85, 0, 0, 0,
3994];
3995/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3996const HAS_BL_16X4: [u8; 32] = [
3997 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84,
3998 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0,
3999];
4000/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
4001const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
4002/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
4003const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
4004/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
4005const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
4006/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
4007const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
4008/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
4009const HAS_TR_16X64: [u8; 2] = [255, 127];
4010/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
4011const HAS_BL_16X64: [u8; 2] = [0, 0];
4012/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
4013const HAS_TR_64X16: [u8; 2] = [3, 1];
4014/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
4015const HAS_BL_64X16: [u8; 2] = [42, 42];
4016
4017/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
4018fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
4019 match (bw, bh) {
4020 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
4021 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
4022 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
4023 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
4024 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
4025 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
4026 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
4027 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
4028 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
4029 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
4030 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
4031 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
4032 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
4033 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
4034 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
4035 }
4036}
4037
4038impl Reach {
4039 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
4040 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
4041 /// own answer is `block` -- a different rule from the standalone-block
4042 /// tables, because a unit's neighbours are mostly its own block's
4043 /// already-reconstructed units:
4044 /// * top-right: available while the unit to the right is still inside
4045 /// the block (`col_off + tx < bw`); otherwise only the block's top row
4046 /// of units reaches past it, through the block-level answer
4047 /// (libaom's `row_off > 0` branch returns exactly
4048 /// `col_off + txw < plane_bw`).
4049 /// * bottom-left: a unit outside the block's left column has none
4050 /// (libaom returns 0 for `col_off > 0`); inside the block
4051 /// (`row_off + tx < bh`) they are the left unit's, already
4052 /// reconstructed; the bottom row falls back to the block-level answer.
4053 pub(crate) fn of_tu(
4054 bw: usize,
4055 bh: usize,
4056 col_off: usize,
4057 row_off: usize,
4058 // The unit's own width and height in pixels; equal for a square
4059 // transform, different for the rect unit a 1:4 strip's first split
4060 // produces (lane-rectsplitx r1).
4061 tx_w: usize,
4062 tx_h: usize,
4063 block: Self,
4064 ) -> Self {
4065 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
4066 // order, so both libaom predicates special-case it (lane-sb128c r10);
4067 // without this the last unit column of every chunk of a 128x64 block
4068 // predicts from a chunk libaom has not decoded yet.
4069 let wide = bw > 64;
4070 Self {
4071 above_right: if row_off > 0 {
4072 // `has_top_right`'s `row_off > 0` branch: the offset is taken
4073 // modulo the 64-wide chunk, except for the one unit whose
4074 // top-right corner is the centre of a 128x128 block.
4075 if wide {
4076 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
4077 } else {
4078 col_off + tx_w < bw
4079 }
4080 } else if col_off + tx_w < bw {
4081 true
4082 } else {
4083 block.above_right
4084 },
4085 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
4086 // `has_bottom_left`: at the left edge of a right-hand chunk
4087 // the bottom-left pixels are in the already-coded left chunk,
4088 // provided they stay inside it.
4089 (row_off % 64) + tx_h < bh.min(64)
4090 } else if col_off > 0 {
4091 false
4092 } else if row_off + tx_h < bh {
4093 true
4094 } else {
4095 block.below_left
4096 },
4097 }
4098 }
4099
4100 /// libaom's own `has_top_right`/`has_bottom_left` for one transform unit
4101 /// of a CHROMA plane, at the plane granularity libaom uses there
4102 /// (`reconintra.c:203` / `reconintra.c:381`).
4103 ///
4104 /// Two things make a chroma unit's answer differ from the same unit's
4105 /// LUMA answer, and [`Self::of_tu`] has neither:
4106 ///
4107 /// 1. libaom runs a chroma plane through `scale_chroma_bsize(bsize,
4108 /// ss_x, ss_y)` (`reconintra.c:1823`, definition `:1649`) before
4109 /// either call, and that remap is not the identity. At 4:2:2
4110 /// (`ss (1,0)`) a BLOCK_4X4 luma leaf becomes BLOCK_8X4 -- TWO mi
4111 /// wide and one mi tall.
4112 /// 2. `has_bottom_left`'s "leftmost column of superblock" arm
4113 /// (`reconintra.c:429-435`) is then reached at `blk_col_in_sb == 0`,
4114 /// which the one-mi-wide luma BLOCK_4X4 reads as column 1 and the
4115 /// per-block table denies. [`Self::of_tu`] has no such arm at all: it
4116 /// ends at `block.below_left`, the BLOCK-level answer, which stands in
4117 /// for the table plus both superblock arms and so agrees with libaom
4118 /// only where neither superblock arm is the deciding step.
4119 ///
4120 /// `mi_bw`/`mi_bh` are the PLANE-scaled block's mi extent ([`Self`]'s
4121 /// caller supplies it from [`chroma_mi_shape`], never the luma block's),
4122 /// and `col_off`/`row_off`/`tx_w`/`tx_h` are LUMA pixels as at every other
4123 /// `Reach` call site -- libaom's plane units are one `tx_size_*_unit`
4124 /// (`1 << (2 + ss)` luma pixels) wide, and each comparison below is
4125 /// restated in luma pixels rather than rescaled twice. The
4126 /// 128-wide arm libaom guards on `block_size_wide[bsize] > 64` is not
4127 /// transcribed: every caller keeps such blocks on [`Self::of_tu`].
4128 ///
4129 /// `above_avail` is libaom's `top_available && right_available` and
4130 /// `below_avail` its `bottom_available && left_available` -- the early
4131 /// returns at `reconintra.c:204` / `:383`. The caller states them because
4132 /// libaom's two edge tests are TILE bounds over the TRANSFORM's plane
4133 /// extent (`mi_col + ((col_off + txw) << ss_x) < mi_col_end`,
4134 /// `mi_row + ((row_off + txh) << ss_y) < mi_row_end`,
4135 /// `reconintra.c:1815-1817`) while `top_available`/`left_available` are
4136 /// `y0 > 0` / `x0 > 0`.
4137 #[allow(clippy::too_many_arguments)]
4138 pub(crate) fn of_tu_chroma(
4139 mi_bw: usize,
4140 mi_bh: usize,
4141 mi_row: usize,
4142 mi_col: usize,
4143 sb_mi: usize,
4144 col_off: usize,
4145 row_off: usize,
4146 tx_w: usize,
4147 tx_h: usize,
4148 ss_x: usize,
4149 ss_y: usize,
4150 above_avail: bool,
4151 below_avail: bool,
4152 ) -> Self {
4153 if !above_avail && !below_avail {
4154 return Self::none();
4155 }
4156 let bw_log2 = mi_bw.trailing_zeros() as usize;
4157 let bh_log2 = mi_bh.trailing_zeros() as usize;
4158 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
4159 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
4160 // `plane_bw_unit`/`plane_bh_unit` (`reconintra.c:208` / `:414`) in
4161 // libaom's plane units, restated in the luma pixels of the offsets.
4162 let plane_bw = (mi_bw >> ss_x).max(1) << (2 + ss_x);
4163 let plane_bh = (mi_bh >> ss_y).max(1) << (2 + ss_y);
4164 let (tr, bl) = Self::plane_reach_tables(mi_bw, mi_bh);
4165 Self {
4166 above_right: above_avail
4167 && (if row_off > 0 {
4168 col_off + tx_w < plane_bw
4169 } else if col_off + tx_w < plane_bw {
4170 true
4171 } else if blk_row == 0 {
4172 // Top row of superblock: the top-right pixels are in the
4173 // superblock above.
4174 true
4175 } else if ((blk_col + 1) << bw_log2) >= sb_mi {
4176 // Rightmost column: they fall in the superblock to the
4177 // right, which is not decoded yet.
4178 false
4179 } else {
4180 Self::bit(tr, (blk_row << (5 - bw_log2)) + blk_col)
4181 }),
4182 below_left: below_avail
4183 && (if col_off > 0 {
4184 // Bottom-left pixels are in the bottom-left block.
4185 false
4186 } else if row_off + tx_h < plane_bh {
4187 true
4188 } else if blk_col == 0 {
4189 // `reconintra.c:429-435`: `blk_start_row_off + row_off +
4190 // count < sb_height_unit`, compared in plane units. Both
4191 // `>> ss_y` floors are lifted out of the comparison
4192 // instead of being evaluated, so the luma-pixel
4193 // restatement is exact.
4194 let from_block = (blk_row << bh_log2) >> ss_y;
4195 let sb_height = (sb_mi >> ss_y).saturating_sub(from_block);
4196 row_off + tx_h < sb_height << (2 + ss_y)
4197 } else if ((blk_row + 1) << bh_log2) >= sb_mi {
4198 // Bottom row (and not the leftmost column): the
4199 // superblock below is not decoded yet.
4200 false
4201 } else {
4202 Self::bit(bl, (blk_row << (5 - bw_log2)) + blk_col)
4203 }),
4204 }
4205 }
4206
4207 /// The `has_tr_*`/`has_bl_*` pair for a block of `mi_bw` x `mi_bh` mi --
4208 /// libaom's `get_has_tr_table`/`get_has_bl_table` indexed by the
4209 /// PLANE-scaled `BLOCK_SIZE`, so one shape can be a rectangle where
4210 /// [`Self::table`] would read a square's row (a 4:2:2 chroma BLOCK_8X4,
4211 /// which is [`Self::of_tu_chroma`]'s whole reason for existing).
4212 fn plane_reach_tables(mi_bw: usize, mi_bh: usize) -> (&'static [u8], &'static [u8]) {
4213 if mi_bw != mi_bh {
4214 return rect_reach_tables(mi_bw * 4, mi_bh * 4);
4215 }
4216 let row = Self::table(mi_bw * 4);
4217 if VERT_AB_PARTITION.with(std::cell::Cell::get) && row < HAS_TOP_RIGHT_VERT.len() {
4218 (&HAS_TOP_RIGHT_VERT[row], &HAS_BOTTOM_LEFT_VERT[row])
4219 } else {
4220 (&HAS_TOP_RIGHT[row], &HAS_BOTTOM_LEFT[row])
4221 }
4222 }
4223
4224 /// What a block of `side` samples at `(x, y)` may read past its own edges,
4225 /// in a frame of `width` by `height`.
4226 pub(crate) fn of(
4227 side: usize,
4228 x: usize,
4229 y: usize,
4230 width: usize,
4231 height: usize,
4232 fctx: &crate::decode::FrameCtx,
4233 ) -> Self {
4234 Self {
4235 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
4236 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
4237 }
4238 }
4239
4240 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
4241 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
4242 /// block's own width for the row stride and by its own height for the
4243 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
4244 /// unlike the square [`Self::of`] which uses one `side` for everything.
4245 pub(crate) fn of_rect(
4246 bw: usize,
4247 bh: usize,
4248 x: usize,
4249 y: usize,
4250 width: usize,
4251 height: usize,
4252 fctx: &crate::decode::FrameCtx,
4253 ) -> Self {
4254 Self {
4255 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
4256 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
4257 }
4258 }
4259
4260 /// [`Self::of`] for one transform unit of a square block whose transform
4261 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
4262 /// non-zero `row_off`/`col_off`): interior units answer from the block's
4263 /// own geometry, and only a unit on the block's top row (resp. left
4264 /// column) reaches the table -- which is the BLOCK's table read at the
4265 /// BLOCK's position, never a table row for the transform's size. Letting
4266 /// the unit stand in for a block of its own size agrees with libaom for
4267 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
4268 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
4269 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
4270 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
4271 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
4272 /// the transform covering the whole block, luma): everything before the
4273 /// table lookup is that function's own early-exit ladder.
4274 fn top_right_rect(
4275 bw: usize,
4276 bh: usize,
4277 x: usize,
4278 y: usize,
4279 fctx: &crate::decode::FrameCtx,
4280 ) -> bool {
4281 let sb_mi: usize = reach_sb_px(fctx) / 4;
4282 let (mi_row, mi_col) = (y / 4, x / 4);
4283 let bw_log2 = (bw / 4).trailing_zeros() as usize;
4284 let bh_log2 = (bh / 4).trailing_zeros() as usize;
4285 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
4286 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
4287 // Top row of the superblock: the top-right pixels are in the (already
4288 // decoded) superblock above.
4289 if blk_row == 0 {
4290 return true;
4291 }
4292 // Rightmost column: they fall in the superblock to the right.
4293 if ((blk_col + 1) << bw_log2) >= sb_mi {
4294 return false;
4295 }
4296 let table = rect_reach_tables(bw, bh).0;
4297 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4298 }
4299
4300 /// libaom `has_top_right`'s own index arithmetic:
4301 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
4302 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
4303 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
4304 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
4305 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
4306 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
4307 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
4308 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
4309 (blk_row << (5 - bw_log2)) + blk_col
4310 }
4311
4312 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
4313 fn bottom_left_rect(
4314 bw: usize,
4315 bh: usize,
4316 x: usize,
4317 y: usize,
4318 fctx: &crate::decode::FrameCtx,
4319 ) -> bool {
4320 let sb_mi: usize = reach_sb_px(fctx) / 4;
4321 let (mi_row, mi_col) = (y / 4, x / 4);
4322 let bw_log2 = (bw / 4).trailing_zeros() as usize;
4323 let bh_log2 = (bh / 4).trailing_zeros() as usize;
4324 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
4325 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
4326 // Leftmost column of the superblock: the bottom-left pixels are in
4327 // the left superblock iff they stay inside its height.
4328 if blk_col == 0 {
4329 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
4330 }
4331 // Bottom row (and not the leftmost column): they fall in the
4332 // superblock below, which is not decoded yet.
4333 if ((blk_row + 1) << bh_log2) >= sb_mi {
4334 return false;
4335 }
4336 let table = rect_reach_tables(bw, bh).1;
4337 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4338 }
4339
4340 /// Marks every [`Reach::of`] made until the returned guard drops as being
4341 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
4342 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
4343 /// unaffected: libaom's own comment says vertical rectangles keep their
4344 /// non-vert table, which is what [`Reach::of_rect`] already reads.
4345 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
4346 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
4347 /// can count the sub-block work that partition creates (lane-ab16).
4348 pub(crate) fn in_vert_ab() -> bool {
4349 VERT_AB_PARTITION.with(std::cell::Cell::get)
4350 }
4351
4352 pub(crate) fn vert_ab_partition() -> VertAbGuard {
4353 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
4354 }
4355
4356 /// Neither, which is all a mode that reads no further than its own edges
4357 /// needs.
4358 pub(crate) fn none() -> Self {
4359 Self {
4360 above_right: false,
4361 below_left: false,
4362 }
4363 }
4364
4365 /// `has_top_right` for a block whose transform covers it whole: the top
4366 /// row of a superblock reads into the superblock above, which is decoded;
4367 /// the rightmost column would read into the superblock to the right, which
4368 /// is not; and everything between is the table's to answer.
4369 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4370 let (row, col, per_side) = Self::position(side, x, y, fctx);
4371 if row == 0 {
4372 return true;
4373 }
4374 if col + 1 == per_side {
4375 return false;
4376 }
4377 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4378 // (the clamp corner-cut that used to live here is gone); sides
4379 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4380 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4381 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4382 // -- a reach over-estimate (extra above-right reference pixels),
4383 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4384 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4385 // NB: named `table_row`, not `row` -- `row` above is the block's
4386 // position inside the superblock and is what the bit index below
4387 // steps by (a merge that shadowed it desynced every block size).
4388 let table_row = Self::table(side);
4389 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
4390 && table_row < HAS_TOP_RIGHT_VERT.len()
4391 {
4392 HAS_TOP_RIGHT_VERT[table_row]
4393 } else {
4394 HAS_TOP_RIGHT[table_row]
4395 };
4396 Self::bit(
4397 table,
4398 (row * Self::table_stride(side) + col) % (table.len() * 8),
4399 )
4400 }
4401
4402 /// `has_bottom_left` for such a block: the leftmost column of a superblock
4403 /// reads into the superblock to its left, which is decoded only as far
4404 /// down as its own bottom; the bottom row would read into the superblock
4405 /// below, which is not decoded at all; and the table answers the rest.
4406 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4407 let (row, col, per_side) = Self::position(side, x, y, fctx);
4408 if col == 0 {
4409 return row * side + side < reach_sb_px(fctx);
4410 }
4411 if row + 1 == per_side {
4412 return false;
4413 }
4414 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4415 // (the clamp corner-cut that used to live here is gone); sides
4416 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4417 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4418 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4419 // -- a reach over-estimate (extra above-right reference pixels),
4420 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4421 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4422 // NB: named `table_row`, not `row` -- `row` above is the block's
4423 // position inside the superblock and is what the bit index below
4424 // steps by (a merge that shadowed it desynced every block size).
4425 let table_row = Self::table(side);
4426 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
4427 && table_row < HAS_BOTTOM_LEFT_VERT.len()
4428 {
4429 HAS_BOTTOM_LEFT_VERT[table_row]
4430 } else {
4431 HAS_BOTTOM_LEFT[table_row]
4432 };
4433 Self::bit(
4434 table,
4435 (row * Self::table_stride(side) + col) % (table.len() * 8),
4436 )
4437 }
4438
4439 /// Where a block sits inside its superblock, in blocks of its own size,
4440 /// and how many of them a superblock is across.
4441 fn position(
4442 side: usize,
4443 x: usize,
4444 y: usize,
4445 fctx: &crate::decode::FrameCtx,
4446 ) -> (usize, usize, usize) {
4447 let sb = reach_sb_px(fctx);
4448 ((y % sb) / side, (x % sb) / side, sb / side)
4449 }
4450
4451 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
4452 /// these tables to its compile-time maximum superblock (128, spec
4453 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
4454 /// size an encode actually uses, so a block's row in the bit index steps
4455 /// by 128 / `side` even though this crate only ever codes a 64
4456 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
4457 /// here instead indexes the wrong bit for every block size but the one
4458 /// where 64 and 128 give the same stride.
4459 fn table_stride(side: usize) -> usize {
4460 128 / side
4461 }
4462
4463 /// Which of the three block sizes the encoder codes a table row is for.
4464 fn table(side: usize) -> usize {
4465 if side == BLOCK {
4466 1
4467 } else if side == 8 {
4468 2
4469 } else if side == 4 {
4470 3
4471 } else {
4472 0
4473 }
4474 }
4475
4476 /// One bit of a table, counting from the low end of its first byte.
4477 fn bit(table: &[u8], index: usize) -> bool {
4478 (table[index / 8] >> (index % 8)) & 1 != 0
4479 }
4480}
4481
4482/// What one symbol costs against a CDF, in bits.
4483/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
4484/// search, the frame header's `allow_warped_motion` and the sequence's
4485/// `enable_warped_motion`, all three together. ON by default since
4486/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
4487/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
4488/// bits -- back off for an A/B on one build.
4489pub(crate) fn warp_on() -> bool {
4490 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4491 crate::envflags::var("EC_AV1_WARP")
4492 .ok()
4493 .map(|v| !matches!(v.as_str(), "0" | "off"))
4494 });
4495 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
4496}
4497
4498/// The smallest LEAF an OBMC candidate is offered for, so the census can
4499/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
4500/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
4501/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
4502///
4503/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
4504/// (12 frames, four quantizers, the standing keep table):
4505///
4506/// | min side | film 1080p | film 2160p | screen |
4507/// |---|---|---|---|
4508/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
4509/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
4510/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
4511/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
4512///
4513/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
4514/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
4515/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
4516/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
4517/// that wins the local RD on five blocks in six and loses ladder bytes is
4518/// the `local-RD-on-references` class again, not a missing footprint.
4519///
4520/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
4521/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
4522/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
4523/// loss on the 1080p film became a 0.3-point win and the other two rows went
4524/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
4525/// of the "local win, ladder loss" it was charged with was the rate weight.
4526/// It still does not meet the keep rule (two down, one flat, both columns).
4527/// The tool stays OFF by default; the upgrade path is the price, not the size
4528/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
4529/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
4530/// 1080p film up, i.e. the same disagreement between the two gates).
4531///
4532/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
4533/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
4534/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
4535/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
4536/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
4537/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
4538/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
4539/// the margin's gain are the same bytes. It stays OFF.
4540///
4541/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
4542/// judgement above was taken when the gate's "film" rows were the `testsrc2`
4543/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
4544/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
4545/// the standing native keep table (`bd_rate_screen_native`):
4546///
4547/// | arm | film A | film B | screen | OBMC fire A/B |
4548/// |---|---|---|---|---|
4549/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
4550/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
4551/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
4552///
4553/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
4554/// only), where the anchors' non-skip area is the known gap:
4555///
4556/// | arm | film B long GOP | wall ours |
4557/// |---|---|---|
4558/// | off (control) | +89.8 / +9.1 | 477.5s |
4559/// | min side 8 | +89.6 / +9.0 | 514.1s |
4560///
4561/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
4562/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
4563/// only at min side 16, which is exactly where film B loses 0.7 on both
4564/// columns. Nothing here meets the keep rule (both films down on both
4565/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
4566/// costs +7.7% wall. OBMC stays OFF at every preset.
4567fn obmc_min_side() -> usize {
4568 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4569 *N.get_or_init(|| {
4570 std::env::var("EC_AV1_OBMC_MIN")
4571 .ok()
4572 .and_then(|v| v.parse().ok())
4573 .unwrap_or(8)
4574 })
4575}
4576
4577/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
4578/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
4579/// same frame-CDF price the coefficients of a non-screen frame are estimated
4580/// with, not the static default table.
4581/// The same price for whichever alphabet the writer will really use for this
4582/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
4583/// (`allow_warped_motion` and at least one warp sample), otherwise the
4584/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
4585/// search pay it, so the alphabet cancels out of a comparison and only its
4586/// per-value spread decides.
4587fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
4588 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
4589 return 0.0;
4590 };
4591 match warp_alphabet {
4592 true => crate::tile::motion_mode_symbol_bits(row, motion),
4593 false => crate::tile::obmc_symbol_bits(row, motion == 1),
4594 }
4595}
4596
4597/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
4598/// candidate, the header's `allow_warped_motion` and the sequence's
4599/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
4600/// native keep table, against the same build with the knob off:
4601///
4602/// | clip | warp on | off |
4603/// |---|---|---|
4604/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
4605/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
4606/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
4607///
4608/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
4609/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
4610/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
4611/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
4612/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
4613/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
4614/// this is a measured loss, not an inert knob. Same shape as the OBMC
4615/// candidate above it (`obmc_min_side`): a local RD win that does not convert
4616/// into ladder bytes.
4617///
4618/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
4619/// because a tool whose gain is local and whose cost is the rate it adds is
4620/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
4621///
4622/// | clip | warp on | off (both at lambda 0.05) |
4623/// |---|---|---|
4624/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
4625/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
4626/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
4627///
4628/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
4629/// column inside 0.1 everywhere -- which reads as a keep rather than the
4630/// 0.7/0.9 loss it was.
4631///
4632/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
4633/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
4634/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
4635/// ran the conformance shape the lambda lane deferred: every warp stream
4636/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
4637/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
4638/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
4639/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
4640/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
4641/// `allow_warped_motion` and `enable_warped_motion` back off together.
4642///
4643/// The WARPED_CAUSAL prediction of one square single-reference block: the
4644/// decoder's own warp-sample walk (`decode::find_samples` +
4645/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
4646/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
4647/// grid -- never a second implementation of any of the three. `None` when the
4648/// block would code no motion_mode symbol at all, when it has no warp sample
4649/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
4650/// or when the projection is not filter-representable (the decoder would then
4651/// predict translationally, so the mode is pure cost).
4652#[allow(clippy::too_many_arguments)]
4653fn warp_prediction(
4654 grid: &MiGrid,
4655 (mi_row, mi_col): (usize, usize),
4656 (mi_rows, mi_cols): (usize, usize),
4657 (x, y): (usize, usize),
4658 side: usize,
4659 mv: (i32, i32),
4660 ref_frame: i8,
4661 ref_planes: [(&[u16], usize, usize, usize); 3],
4662 fctx: &crate::decode::FrameCtx,
4663) -> Option<[Vec<u8>; 3]> {
4664 let n4 = side / 4;
4665 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
4666 return None;
4667 }
4668 let mut samples = crate::decode::find_samples(
4669 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
4670 );
4671 if samples.is_empty() {
4672 return None;
4673 }
4674 if samples.len() > 1 {
4675 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
4676 }
4677 let params = crate::warp::find_projection(
4678 &samples,
4679 side as i32,
4680 side as i32,
4681 mv.1,
4682 mv.0,
4683 mi_row as i32,
4684 mi_col as i32,
4685 )?;
4686 let mut pred = [
4687 vec![0u16; side * side],
4688 vec![0u16; side * side / 4],
4689 vec![0u16; side * side / 4],
4690 ];
4691 // The translational prediction first, exactly as the decoder builds it,
4692 // then the affine one over the planes whose OWN block is at least 8x8
4693 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
4694 // 4x4 chroma stays translational).
4695 for (i, r) in ref_planes.into_iter().enumerate() {
4696 let luma_plane = i == 0;
4697 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
4698 let s = if luma_plane { side } else { side / 2 };
4699 mc::predict(
4700 r.0,
4701 r.1,
4702 r.2,
4703 r.3,
4704 mv_to_q4(px, mv.1, luma_plane),
4705 mv_to_q4(py, mv.0, luma_plane),
4706 s,
4707 s,
4708 &mut pred[i],
4709 fctx,
4710 );
4711 if crate::decode::warp_plane_allowed(s, s) {
4712 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
4713 crate::warp::warp_affine(
4714 &params,
4715 r.0,
4716 r.2 as i32,
4717 r.3 as i32,
4718 r.1 as i32,
4719 &mut pred[i],
4720 px as i32,
4721 py as i32,
4722 cside,
4723 cside,
4724 cside,
4725 sub,
4726 sub,
4727 fctx,
4728 );
4729 }
4730 }
4731 let [py_buf, pu_buf, pv_buf] = pred;
4732 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4733 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4734}
4735
4736/// What tile.rs' `write_compound_ref_frames` pays for the pair
4737/// `(ref0, ref1)`, symbol for symbol, each at the context its own
4738/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
4739/// derives from the block's above/left neighbours -- plus the `comp_mode`
4740/// symbol itself at `reference_mode_ctx`.
4741///
4742/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
4743/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
4744/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
4745/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4746pub(crate) fn compound_ref_bits((ref0, ref1): (i8, i8), stack: &crate::mvstack::MvStack) -> f64 {
4747 use crate::mvstack::{
4748 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4749 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
4750 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
4751 uni_comp_ref_p1_ctx,
4752 };
4753 let (a, a1) = stack.above_refs;
4754 let (l, l1) = stack.left_refs;
4755 let unidir = is_uni_comp_ref(ref0, ref1);
4756 let comp_mode = symbol_bits(
4757 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4758 1,
4759 );
4760 let ref_type = symbol_bits(
4761 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
4762 usize::from(!unidir),
4763 );
4764 if unidir {
4765 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
4766 let p0 = symbol_bits(
4767 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4768 usize::from(both_backward),
4769 );
4770 if both_backward {
4771 return comp_mode + ref_type + p0;
4772 }
4773 let past_last2 = ref1 != LAST2_FRAME;
4774 let p1 = symbol_bits(
4775 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
4776 usize::from(past_last2),
4777 );
4778 let p2 = if past_last2 {
4779 symbol_bits(
4780 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4781 usize::from(ref1 == GOLDEN_FRAME),
4782 )
4783 } else {
4784 0.0
4785 };
4786 return comp_mode + ref_type + p0 + p1 + p2;
4787 }
4788 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
4789 let fwd = symbol_bits(
4790 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
4791 usize::from(far),
4792 ) + if far {
4793 symbol_bits(
4794 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4795 usize::from(ref0 == GOLDEN_FRAME),
4796 )
4797 } else {
4798 symbol_bits(
4799 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
4800 usize::from(ref0 == LAST2_FRAME),
4801 )
4802 };
4803 let is_altref = ref1 == ALTREF_FRAME;
4804 let bwd = symbol_bits(
4805 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
4806 usize::from(is_altref),
4807 ) + if is_altref {
4808 0.0
4809 } else {
4810 symbol_bits(
4811 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
4812 usize::from(ref1 == ALTREF2_FRAME),
4813 )
4814 };
4815 comp_mode + ref_type + fwd + bwd
4816}
4817
4818/// What the `skip` symbol costs at the context tile.rs really codes it with
4819/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
4820/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
4821/// exactly the difference between this symbol's two values, so the row it is
4822/// read from moves that decision (class pricer-context-zero, lane-ctx).
4823pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
4824 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
4825 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
4826}
4827
4828/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
4829/// neighbours' intra/inter state, with an out-of-tile side contributing
4830/// nothing, off the same two cells (lane-ctx).
4831pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
4832 let ctx = crate::tile::intra_inter_ctx(
4833 stack.above_nbr.is_some(),
4834 stack.left_nbr.is_some(),
4835 stack.above_nbr.is_some_and(|n| n.is_inter),
4836 stack.left_nbr.is_some_and(|n| n.is_inter),
4837 );
4838 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
4839}
4840
4841/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
4842/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
4843/// context -- zero on a frame that carries no `reference_select` bit, where
4844/// the writer codes no symbol at all.
4845fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
4846 if !reference_select() {
4847 return 0.0;
4848 }
4849 symbol_bits(
4850 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4851 0,
4852 )
4853}
4854
4855/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
4856/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
4857/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
4858/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
4859/// LAST is p1=0,p3=0,p4=0,
4860/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
4861/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
4862/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
4863/// symbols off the wrong CDFs -- which is what made the search believe an
4864/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
4865/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
4866/// paid nothing at all, so compound was overcharged by the whole symbol.
4867pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
4868 use crate::mvstack::{
4869 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4870 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4871 single_ref_p5_ctx, single_ref_p6_ctx,
4872 };
4873 let (a, a1) = stack.above_refs;
4874 let (l, l1) = stack.left_refs;
4875 let comp_mode = comp_mode_single_bits(stack);
4876 let backward = ref_frame >= BWDREF_FRAME;
4877 let p1 = symbol_bits(
4878 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4879 usize::from(backward),
4880 );
4881 if backward {
4882 let is_altref = ref_frame == ALTREF_FRAME;
4883 let p2 = symbol_bits(
4884 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
4885 usize::from(is_altref),
4886 );
4887 return comp_mode
4888 + p1
4889 + p2
4890 + if is_altref {
4891 0.0
4892 } else {
4893 symbol_bits(
4894 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
4895 usize::from(ref_frame == ALTREF2_FRAME),
4896 )
4897 };
4898 }
4899 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4900 comp_mode
4901 + p1
4902 + symbol_bits(
4903 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4904 usize::from(far),
4905 )
4906 + if far {
4907 symbol_bits(
4908 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4909 usize::from(ref_frame == GOLDEN_FRAME),
4910 )
4911 } else {
4912 symbol_bits(
4913 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4914 usize::from(ref_frame == LAST2_FRAME),
4915 )
4916 }
4917}
4918
4919pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
4920 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
4921 let width = cdf[symbol] - low;
4922 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
4923 // 32769 prices a symbol can carry; the `log2` behind each is computed
4924 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
4925 // profile -- this function is called for every symbol of every candidate
4926 // the RD search prices). Each entry is exactly the expression this used
4927 // to evaluate, so every price is bit-identical.
4928 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
4929 PRICES.get_or_init(|| {
4930 (0..=32768u32)
4931 .map(|w| -(f64::from(w) / 32768.0).log2())
4932 .collect()
4933 })[usize::from(width)]
4934}
4935
4936/// What the tile writer spends to say a block is coded in each of the thirteen
4937/// modes, given the modes of the blocks above it and to its left: the luma mode
4938/// symbol against the CDF those two neighbours pick, the angle delta a
4939/// directional mode carries, and the chroma mode symbol, whose CDF the luma
4940/// mode itself indexes.
4941///
4942/// Without this the search is blind to what a mode costs to name, which is not
4943/// a rounding error: a directional mode on a picture that does not run that way
4944/// is a rate loss the squared error never sees.
4945/// Codes one square of the picture as a single block: searches the luma mode,
4946/// codes both chroma planes DC, and hands back the block and what it cost --
4947/// squared error plus lambda times the bits its symbols spend.
4948/// How many halvings of a `side`-square block's transform the `tx_depth`
4949/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
4950/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
4951fn max_tx_depth(side: usize) -> usize {
4952 match side {
4953 8 => 1,
4954 16 | 32 => 2,
4955 _ => 0,
4956 }
4957}
4958
4959/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
4960/// Priced at context row 0 -- the writer picks the real row from its
4961/// neighbours' transform sizes, which the search has no view of; the term is
4962/// the same for every depth of one block either way, so it only shifts the
4963/// depth-0-versus-split margin, never the ordering between two splits.
4964fn tx_depth_bits(side: usize, depth: usize) -> f64 {
4965 match side {
4966 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
4967 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
4968 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
4969 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
4970 }
4971}
4972
4973/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4974/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4975/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4976/// (the mode search's own weight); below 1 the split trial is charged less
4977/// for its bits and fires more often.
4978///
4979/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4980/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4981/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4982/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4983/// so what is mis-calibrated is the weight the split's rate is judged under,
4984/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4985pub(crate) fn split_lambda_mult() -> f64 {
4986 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4987 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4988 .ok()
4989 .and_then(|v| v.parse().ok())
4990 .unwrap_or(SPLIT_LAMBDA)
4991 });
4992 *M
4993}
4994
4995/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4996/// the sweep that chose it.
4997const SPLIT_LAMBDA: f64 = 1.0;
4998
4999/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
5000/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
5001/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
5002/// trials offered, trials the split won, then the (rate, distortion) of the
5003/// split and flat arms summed apart for the split-won and flat-won trials --
5004/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
5005static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
5006 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
5007
5008/// Whether [`SPLIT_CENSUS`] is armed, read once.
5009pub(crate) fn split_census_on() -> bool {
5010 static ON: std::sync::LazyLock<bool> =
5011 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
5012 *ON
5013}
5014
5015/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
5016/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
5017fn split_census_base(site: usize, key: bool, side: usize) -> usize {
5018 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
5019 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
5020}
5021
5022/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
5023/// `(rate in bits, distortion as squared error)`.
5024fn split_census(
5025 site: usize,
5026 key: bool,
5027 side: usize,
5028 split_won: bool,
5029 split: (f64, f64),
5030 flat: (f64, f64),
5031) {
5032 use std::sync::atomic::Ordering::Relaxed;
5033 let base = split_census_base(site, key, side);
5034 let add = |i: usize, v: u64| {
5035 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
5036 };
5037 add(0, 1);
5038 let off = if split_won {
5039 add(1, 1);
5040 2
5041 } else {
5042 6
5043 };
5044 let (win, lose) = if split_won {
5045 (split, flat)
5046 } else {
5047 (flat, split)
5048 };
5049 add(off, (win.0 * 64.0).max(0.0) as u64);
5050 add(off + 1, win.1.max(0.0) as u64);
5051 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
5052 add(off + 3, lose.1.max(0.0) as u64);
5053}
5054
5055/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
5056/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
5057/// last table a run prints is the whole encode's total (there is no flush
5058/// hook the encoder API guarantees to reach).
5059pub(crate) fn dump_split_census() {
5060 use std::sync::atomic::Ordering::Relaxed;
5061 eprintln!(
5062 "SPLITCENSUS site frame side offered split share% \
5063 win_rate win_dist lose_rate lose_dist"
5064 );
5065 for site in 0..2 {
5066 for key in [true, false] {
5067 for side_idx in 0..4 {
5068 let base = split_census_base(site, key, 8 << side_idx);
5069 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
5070 if v[0] == 0 {
5071 continue;
5072 }
5073 let (n, s) = (v[0] as f64, v[1] as f64);
5074 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
5075 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
5076 // all `n` trials, not a mean of two means.
5077 eprintln!(
5078 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
5079 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
5080 if site == 0 { "intra" } else { "inter" },
5081 if key { "key " } else { "inter" },
5082 8 << side_idx,
5083 v[0],
5084 v[1],
5085 100.0 * s / n,
5086 (v[2] + v[6]) as f64 / n / 64.0,
5087 (v[3] + v[7]) as f64 / n,
5088 (v[4] + v[8]) as f64 / n / 64.0,
5089 (v[5] + v[9]) as f64 / n,
5090 );
5091 }
5092 }
5093 }
5094}
5095
5096/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
5097/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
5098/// its mode/reference syntax and not the search's own cost function
5099/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
5100/// control; below 1 a coded vector is charged less and `NEWMV` wins more
5101/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
5102pub(crate) fn mv_lambda_mult() -> f64 {
5103 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
5104 crate::envflags::var("EC_AV1_MV_LAMBDA")
5105 .ok()
5106 .and_then(|v| v.parse().ok())
5107 .unwrap_or(MV_LAMBDA)
5108 });
5109 *M
5110}
5111
5112/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
5113const MV_LAMBDA: f64 = 1.0;
5114
5115/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
5116/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
5117/// which the RD cost multiplies by lambda). Zero at the default weight.
5118fn mv_rate_surcharge(mv_bits: f64) -> f64 {
5119 (mv_lambda_mult() - 1.0) * mv_bits
5120}
5121
5122/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
5123/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
5124/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
5125/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
5126/// cost it won by, 4 the summed cost it lost by, 5 the summed
5127/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
5128/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
5129/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
5130/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
5131/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
5132static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
5133 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
5134
5135/// Whether [`NEWMV_CENSUS`] is armed, read once.
5136pub(crate) fn newmv_census_on() -> bool {
5137 static ON: std::sync::LazyLock<bool> =
5138 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
5139 *ON
5140}
5141
5142/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
5143fn newmv_census_global(i: usize) {
5144 if newmv_census_on() {
5145 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5146 }
5147}
5148
5149/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
5150/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
5151/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
5152/// candidate's own; both `f64::INFINITY` is a block that offered neither.
5153fn newmv_census_block(
5154 side: usize,
5155 offered: bool,
5156 new_cost: f64,
5157 other_cost: f64,
5158 mv: (i32, i32),
5159 nearest: (i32, i32),
5160 mv_bits: f64,
5161) {
5162 if !newmv_census_on() {
5163 return;
5164 }
5165 use std::sync::atomic::Ordering::Relaxed;
5166 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
5167 let add = |i: usize, v: u64| {
5168 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
5169 };
5170 add(0, 1);
5171 if !offered {
5172 return;
5173 }
5174 add(1, 1);
5175 if new_cost < other_cost {
5176 add(2, 1);
5177 add(3, (other_cost - new_cost).max(0.0) as u64);
5178 } else {
5179 add(4, (new_cost - other_cost).max(0.0) as u64);
5180 }
5181 add(
5182 5,
5183 ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64,
5184 );
5185 if mv == nearest {
5186 add(6, 1);
5187 }
5188 add(7, (mv_bits * 64.0).max(0.0) as u64);
5189}
5190
5191/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
5192/// same guard [`dump_split_census`] rides (cumulative, so the last table a
5193/// run prints is the whole encode's).
5194pub(crate) fn dump_newmv_census() {
5195 use std::sync::atomic::Ordering::Relaxed;
5196 eprintln!(
5197 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
5198 mv_dist_q3 mv==nearest% mv_bits"
5199 );
5200 for side_idx in 0..4 {
5201 let base = side_idx * 8;
5202 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
5203 if v[0] == 0 {
5204 continue;
5205 }
5206 let off = v[1].max(1) as f64;
5207 eprintln!(
5208 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
5209 8 << side_idx,
5210 v[0],
5211 v[1],
5212 v[2],
5213 100.0 * v[2] as f64 / off,
5214 v[3] as f64 / v[2].max(1) as f64,
5215 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
5216 v[5] as f64 / off,
5217 100.0 * v[6] as f64 / off,
5218 v[7] as f64 / off / 64.0,
5219 );
5220 }
5221 // lane-hpmv: how many mv components this encode coded an eighth-pel bit
5222 // for, and how many of those named a vector no non-hp frame can code.
5223 let (hp_all, hp_eighth) = crate::tile::hp_symbols();
5224 eprintln!(
5225 "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)",
5226 100.0 * hp_eighth as f64 / hp_all.max(1) as f64,
5227 );
5228 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
5229 eprintln!(
5230 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
5231 leaf second reference {}/{} ({:.1}%)",
5232 g[1],
5233 g[0],
5234 100.0 * g[1] as f64 / g[0].max(1) as f64,
5235 g[3],
5236 g[2],
5237 100.0 * g[3] as f64 / g[2].max(1) as f64,
5238 );
5239 let [
5240 calls,
5241 evals,
5242 _subpel,
5243 rounds,
5244 near_pred,
5245 unmoved,
5246 widest,
5247 widest_moves,
5248 ] = crate::motion::take_census();
5249 let per = |n: u64| n as f64 / calls.max(1) as f64;
5250 eprintln!(
5251 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
5252 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
5253 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
5254 per(evals),
5255 per(rounds),
5256 100.0 * near_pred as f64 / calls.max(1) as f64,
5257 100.0 * unmoved as f64 / calls.max(1) as f64,
5258 100.0 * widest as f64 / calls.max(1) as f64,
5259 per(widest_moves),
5260 );
5261}
5262
5263/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
5264/// the intra witness's fire count stays its own.
5265pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
5266 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
5267
5268/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
5269/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
5270/// `0` compares types on reconstruction error alone, which is what separates
5271/// a rate-term calibration (class `rd-rate-term-calibration`) from a
5272/// distortion the trial mis-measures.
5273pub(crate) fn tx_type_lambda_mult() -> f64 {
5274 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
5275 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
5276 .ok()
5277 .and_then(|v| v.parse().ok())
5278 .unwrap_or(1.0)
5279 });
5280 *M
5281}
5282
5283/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
5284/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
5285/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
5286/// question needs: at weight 1 the five-type intra search spends 1.2% more
5287/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
5288/// of the type it picks.
5289pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
5290 if tx_type == TxType::DctDct {
5291 0.0
5292 } else {
5293 lambda * (tx_type_lambda_mult() - 1.0) * bits
5294 }
5295}
5296
5297/// lane-txrd instrument: over the FLAT inter luma decision, the summed
5298/// reconstruction error and priced bits of the type the search chose against
5299/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
5300/// integer counter. `EC_AV1_TXRD_CENSUS`.
5301pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
5302 std::sync::atomic::AtomicU64::new(0),
5303 std::sync::atomic::AtomicU64::new(0),
5304 std::sync::atomic::AtomicU64::new(0),
5305 std::sync::atomic::AtomicU64::new(0),
5306 std::sync::atomic::AtomicU64::new(0),
5307 std::sync::atomic::AtomicU64::new(0),
5308 std::sync::atomic::AtomicU64::new(0),
5309];
5310
5311/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
5312/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
5313#[cfg(test)]
5314pub(crate) fn take_txrd_stats() -> [u64; 7] {
5315 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5316}
5317
5318/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
5319#[cfg(test)]
5320pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
5321 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
5322}
5323
5324/// How many luma transform units resolved to each [`TxType`], indexed by the
5325/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
5326/// and the instrument that says which types the search actually reaches.
5327pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
5328 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
5329
5330/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
5331/// counts to its own encode.
5332#[cfg(test)]
5333pub(crate) fn take_tx_type_hits() -> [usize; 16] {
5334 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
5335}
5336
5337/// How many blocks resolved to each `tx_depth`, the fire count that says
5338/// whether the depth search below reaches its candidates at all.
5339static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
5340 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
5341
5342/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
5343/// to its own encode.
5344#[cfg(test)]
5345pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
5346 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5347}
5348
5349/// How many inter blocks resolved to each var-tx depth (0 = one transform
5350/// over the whole block, 1 = its four halves), the fire count a gate prints
5351/// to see the split search reach its candidates at all. Indexed
5352/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
5353/// says which of the four block classes the split reaches -- the 32x32 root
5354/// and the compound blocks are this lane's two new ones.
5355static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
5356 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5357
5358/// Whether a 32x32 inter winner searches its own var-tx depth (the four
5359/// 16x16 units against the flat transform) instead of coding depth 0 blind.
5360/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
5361///
5362/// Rejected three times on the bars rows of the native gate (flat to +0.3).
5363/// lane-av1resweep re-judged it on the two REAL film crops at
5364/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
5365/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
5366///
5367/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
5368/// |---|---|---|---|
5369/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
5370/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
5371/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
5372/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
5373/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
5374///
5375/// The bars rows are ~90% zero-intra-cost cells, so the split never had
5376/// residual to reach there -- the tool was being judged on content that
5377/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
5378fn tx32_depth_search() -> bool {
5379 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5380 crate::envflags::var("EC_AV1_TX32_DEPTH")
5381 .ok()
5382 .map(|v| !matches!(v.as_str(), "0" | "off"))
5383 });
5384 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
5385}
5386
5387/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
5388/// trial units have to be predicted from BOTH references
5389/// ([`mc_trial_compound`]) or the split would re-predict them by single-
5390/// reference translation, which is not what the decoder reconstructs.
5391/// ON by default (the table on [`tx32_depth_search`]: on real film it is
5392/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
5393/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
5394/// `EC_AV1_COMP_VARTX`.
5395fn compound_var_tx() -> bool {
5396 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5397 crate::envflags::var("EC_AV1_COMP_VARTX")
5398 .ok()
5399 .map(|v| !matches!(v.as_str(), "0" | "off"))
5400 });
5401 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
5402}
5403
5404/// How many 32x32-and-below inter blocks each reference frame won, indexed by
5405/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
5406/// fire count a gate prints to see an extra reference reach a block at all
5407/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
5408/// chosen is a pyramid that costs bytes and buys nothing).
5409static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
5410 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5411
5412/// Reads [`REF_FRAME_HITS`] and zeroes it.
5413#[cfg(test)]
5414pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
5415 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
5416}
5417
5418/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
5419#[cfg(test)]
5420pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
5421 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5422}
5423
5424/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
5425/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
5426/// is one flag, depth 1 is a split root plus one unsplit flag per child
5427/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
5428/// or a 4x4 sub-size).
5429fn txfm_split_bits(side: usize, depth: usize) -> f64 {
5430 let max_tx = side.min(64);
5431 let ctx = |tx: usize| {
5432 crate::decode::txfm_partition_ctx_rect(
5433 crate::decode::TXFM_CTX_INIT,
5434 crate::decode::TXFM_CTX_INIT,
5435 side,
5436 tx,
5437 tx,
5438 )
5439 };
5440 if depth == 0 {
5441 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
5442 }
5443 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
5444 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
5445}
5446
5447/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
5448/// type is never coded -- the decoder takes the LUMA type of the block's
5449/// chroma-reference position and reduces it to the set the chroma size allows
5450/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
5451/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
5452/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
5453/// basis they were never produced for: on the bars gate row the luma of the
5454/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
5455/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
5456/// collapse two lanes attributed to the type PRICE (class
5457/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
5458/// field the encoder never mirrored).
5459///
5460/// Re-codes the two chroma planes of a committed inter block at the type the
5461/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
5462/// the trials the caller already holds are right.
5463#[allow(clippy::too_many_arguments)]
5464fn recode_inter_chroma(
5465 chroma: &[Plane; 2],
5466 (x, y): (usize, usize),
5467 side: usize,
5468 mv: (i32, i32),
5469 refs: [(&[u16], usize, usize, usize); 2],
5470 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
5471 search: &Search,
5472 set: TxbSet,
5473 luma_tx_type: TxType,
5474 fctx: &crate::decode::FrameCtx,
5475) -> Option<[Trial; 2]> {
5476 let c = side / 2;
5477 let tx =
5478 crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
5479 if tx == TxType::DctDct {
5480 return None;
5481 }
5482 Some([0usize, 1].map(|p| match second {
5483 Some((mv1, r1)) => mc_trial_compound_typed(
5484 &chroma[p],
5485 x / 2,
5486 y / 2,
5487 c,
5488 (mv, mv1),
5489 false,
5490 refs[p],
5491 r1[p],
5492 search.base_q_idx,
5493 search.deadzone,
5494 set,
5495 tx,
5496 fctx,
5497 ),
5498 None => mc_trial_typed(
5499 &chroma[p],
5500 x / 2,
5501 y / 2,
5502 c,
5503 mv,
5504 false,
5505 refs[p].0,
5506 refs[p].1,
5507 refs[p].2,
5508 refs[p].3,
5509 false,
5510 search.base_q_idx,
5511 search.deadzone,
5512 set,
5513 tx,
5514 fctx,
5515 ),
5516 }))
5517}
5518
5519/// The inter block's own var-tx decision, once its motion vector is settled:
5520/// its residual as ONE transform over the whole block, or as the four
5521/// transforms of half the side the tree's first halving names. The prediction
5522/// is the same motion compensation either way, so the split trial
5523/// re-transforms the identical residual in four pieces -- it wins where four
5524/// small transforms carry a locally varying residual cheaper than one big
5525/// one. Commits the winner into `luma` and hands back its block-coordinate
5526/// levels, the depth the writer codes and the cost the winner adds to (or
5527/// takes off) the caller's already-computed flat cost.
5528///
5529/// Only for a block wholly inside the frame: past the true edge the reader's
5530/// var-tx recursion skips the units that fall outside
5531/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
5532/// leave the residual units this writes unpaired.
5533#[allow(clippy::too_many_arguments)]
5534fn commit_inter_luma(
5535 luma: &mut Plane,
5536 (x, y): (usize, usize),
5537 side: usize,
5538 mv: (i32, i32),
5539 reference: (&[u16], usize, usize, usize),
5540 search: &Search,
5541 flat: &Trial,
5542 skip: bool,
5543 // A COMPOUND winner's second half: the vector and reference planes the
5544 // trial units are blended from ([`mc_trial_compound`], the decoder's own
5545 // `comp_group_idx == 0` average). `None` is the single-reference block.
5546 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
5547 fctx: &crate::decode::FrameCtx,
5548) -> (Vec<i32>, u8, f64, Vec<TxType>) {
5549 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
5550 // type out of the two-type inter set the writer already codes a symbol
5551 // for, priced the same way the intra search is (sse + lambda * bits, the
5552 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
5553 // block codes no residual and the 64-point transform names no type.
5554 let mut flat_typed: Option<Trial> = None;
5555 let mut flat_type = TxType::DctDct;
5556 if !skip {
5557 // lane-intertx: on a `reduced_tx_set = 0` frame the search names the
5558 // Set1 alphabet the writer codes into ([`luma_set_for`], the shape
5559 // the intra search already takes), which is what makes the wider
5560 // seven-type candidate list below reachable -- and prices every
5561 // candidate, `IDTX` included, in the alphabet its symbol is really
5562 // coded into.
5563 if let Some(fset) = inter_luma_set(side).map(|set| luma_set_for(set, search.screen)) {
5564 let lambda = search.lambda * tx_type_lambda_mult();
5565 let cost = |t: &Trial| t.sse + lambda * t.bits;
5566 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
5567 if tx_type == TxType::DctDct {
5568 continue;
5569 }
5570 let candidate = match second {
5571 Some((mv1, ref1)) => mc_trial_compound_typed(
5572 luma,
5573 x,
5574 y,
5575 side,
5576 (mv, mv1),
5577 true,
5578 reference,
5579 ref1,
5580 search.base_q_idx,
5581 search.deadzone,
5582 fset,
5583 tx_type,
5584 fctx,
5585 ),
5586 None => mc_trial_typed(
5587 luma,
5588 x,
5589 y,
5590 side,
5591 mv,
5592 true,
5593 reference.0,
5594 reference.1,
5595 reference.2,
5596 reference.3,
5597 false,
5598 search.base_q_idx,
5599 search.deadzone,
5600 fset,
5601 tx_type,
5602 fctx,
5603 ),
5604 };
5605 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
5606 flat_type = tx_type;
5607 flat_typed = Some(candidate);
5608 }
5609 }
5610 }
5611 }
5612 // Counted at the return points, so the census names the types the block
5613 // really CODES -- a split unit's winner that the flat cost then beats was
5614 // never written (class `counter from refused stream`).
5615 let count = |types: &[TxType]| {
5616 for &t in types {
5617 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5618 }
5619 };
5620 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
5621 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
5622 use std::sync::atomic::Ordering::Relaxed;
5623 TXRD_STATS[0].fetch_add(1, Relaxed);
5624 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
5625 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
5626 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
5627 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
5628 // Is the `DCT_DCT` baseline the search compares against the trial
5629 // THIS function would build for the same block? A stale or
5630 // differently-predicted baseline is what would let a candidate win on
5631 // both terms at once (class `local-rd-on-references` vs a real
5632 // pricing defect); re-predicting it here is the only way to tell.
5633 if let Some(fset) = inter_luma_set(side) {
5634 let here = match second {
5635 Some((mv1, ref1)) => mc_trial_compound_typed(
5636 luma,
5637 x,
5638 y,
5639 side,
5640 (mv, mv1),
5641 true,
5642 reference,
5643 ref1,
5644 search.base_q_idx,
5645 search.deadzone,
5646 fset,
5647 TxType::DctDct,
5648 fctx,
5649 ),
5650 None => mc_trial_typed(
5651 luma,
5652 x,
5653 y,
5654 side,
5655 mv,
5656 true,
5657 reference.0,
5658 reference.1,
5659 reference.2,
5660 reference.3,
5661 false,
5662 search.base_q_idx,
5663 search.deadzone,
5664 fset,
5665 TxType::DctDct,
5666 fctx,
5667 ),
5668 };
5669 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
5670 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
5671 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
5672 let n = TXRD_STATS[0].load(Relaxed);
5673 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
5674 eprintln!(
5675 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
5676 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
5677 sse={:.0} bits={:.1}",
5678 second.is_some(),
5679 flat.sse,
5680 flat.bits,
5681 here.sse,
5682 here.bits,
5683 flat_ref.sse,
5684 flat_ref.bits,
5685 );
5686 }
5687 }
5688 }
5689 // What the caller's already-counted `flat` cost has to be corrected by
5690 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
5691 let flat_gain =
5692 (flat_ref.sse + search.lambda * flat_ref.bits) - (flat.sse + search.lambda * flat.bits);
5693 let eligible = tx_select()
5694 && tx_select_inter()
5695 && !skip
5696 && side >= 16
5697 && (second.is_none() || compound_var_tx())
5698 && (side != BLOCK || tx32_depth_search())
5699 && x + side <= luma.true_width
5700 && y + side <= luma.true_height;
5701 if !eligible {
5702 luma.commit(x, y, side, flat_ref);
5703 count(&[flat_type]);
5704 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
5705 }
5706 let tx = side / 2;
5707 let set = luma_set_for(
5708 if tx >= 32 {
5709 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
5710 TxbSet::Luma32Inter
5711 } else if tx >= 16 {
5712 TxbSet::Luma16Inter
5713 } else {
5714 TxbSet::Luma8Inter
5715 },
5716 search.screen,
5717 );
5718 let mut levels = vec![0i32; side * side];
5719 let (mut sse, mut bits) = (0.0, 0.0);
5720 let mut units = Vec::with_capacity(4);
5721 // The split units are smaller than their block, so their `txb_skip`
5722 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
5723 // each unit's own commit publishes what the next one reads, coding order.
5724 luma.ctx.tu_split = true;
5725 // One type per unit in the writer's own raster order (tile.rs
5726 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
5727 let mut split_types = vec![TxType::DctDct; 4];
5728 for tu_row in 0..2 {
5729 for tu_col in 0..2 {
5730 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
5731 let unit = |tx_type: TxType| match second {
5732 Some((mv1, ref1)) => mc_trial_compound_typed(
5733 luma,
5734 tu_x,
5735 tu_y,
5736 tx,
5737 (mv, mv1),
5738 true,
5739 reference,
5740 ref1,
5741 search.base_q_idx,
5742 search.deadzone,
5743 set,
5744 tx_type,
5745 fctx,
5746 ),
5747 None => mc_trial_typed(
5748 luma,
5749 tu_x,
5750 tu_y,
5751 tx,
5752 mv,
5753 true,
5754 reference.0,
5755 reference.1,
5756 reference.2,
5757 reference.3,
5758 false,
5759 search.base_q_idx,
5760 search.deadzone,
5761 set,
5762 tx_type,
5763 fctx,
5764 ),
5765 };
5766 let mut best: Option<(f64, TxType, Trial)> = None;
5767 for &tx_type in inter_tx_type_candidates(set, search.screen) {
5768 let candidate = unit(tx_type);
5769 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
5770 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
5771 best = Some((cost, tx_type, candidate));
5772 }
5773 }
5774 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
5775 split_types[tu_row * 2 + tu_col] = tx_type;
5776 sse += trial.sse;
5777 bits += trial.bits;
5778 for row in 0..tx {
5779 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
5780 .copy_from_slice(&trial.levels[row * tx..][..tx]);
5781 }
5782 units.push((tu_x, tu_y, trial));
5783 }
5784 }
5785 luma.ctx.tu_split = false;
5786 let split_rate = bits + txfm_split_bits(side, 1);
5787 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
5788 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
5789 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
5790 if split_census_on() {
5791 split_census(
5792 1,
5793 false,
5794 side,
5795 split_cost < flat_cost,
5796 (split_rate, sse),
5797 (flat_rate, flat_ref.sse),
5798 );
5799 }
5800 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
5801 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
5802 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
5803 // in the leaf row (class `gate-blind-to-feature`).
5804 let counted = side <= BLOCK;
5805 if split_cost < flat_cost {
5806 for (tu_x, tu_y, trial) in &units {
5807 luma.commit(*tu_x, *tu_y, tx, trial);
5808 }
5809 if counted {
5810 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5811 }
5812 count(&split_types);
5813 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
5814 }
5815 if counted {
5816 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5817 }
5818 luma.commit(x, y, side, flat_ref);
5819 count(&[flat_type]);
5820 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
5821}
5822
5823/// The largest distinct-colour count a block may hold and still be offered a
5824/// palette candidate at all: past it the k-means quantisation costs more
5825/// error than the map saves rate, and every trial is wasted wall.
5826///
5827/// Swept on the gate's own screen capture (lane-av1pal2, the
5828/// `unswept-decision-constants` class): 32 (the value this lane inherited)
5829/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
5830/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
5831/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
5832/// binds on nothing this content holds. 128 ships: best BD against both
5833/// references and no wall cost at all (6.1s, the same as at 32, because the
5834/// blocks it newly admits are ones the RD then keeps).
5835/// `EC_AV1_PAL_MAXCOLORS`.
5836fn palette_max_colors() -> usize {
5837 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5838 *N.get_or_init(|| {
5839 std::env::var("EC_AV1_PAL_MAXCOLORS")
5840 .ok()
5841 .and_then(|v| v.parse().ok())
5842 .unwrap_or(128)
5843 })
5844}
5845
5846/// The palettes worth trying for one block's luma, in the shape libaom's
5847/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
5848/// distinct colours takes them ALL (the prediction is then exact and the
5849/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
5850/// one-dimensional Lloyd iteration seeded evenly across its range -- both
5851/// offered, because which wins is an RD question the caller answers.
5852/// `block` is `side*side` source samples, row-major.
5853fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
5854 let mut histogram = [0u32; 256];
5855 for &v in block {
5856 histogram[usize::from(v)] += 1;
5857 }
5858 let present: Vec<u16> = (0..256u16)
5859 .filter(|&v| histogram[usize::from(v)] > 0)
5860 .collect();
5861 if present.len() < 2 {
5862 return Vec::new();
5863 }
5864 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
5865 let mut base = [0u16; 8];
5866 base[..colors.len()].copy_from_slice(colors);
5867 let map = block
5868 .iter()
5869 .map(|&v| {
5870 colors
5871 .iter()
5872 .enumerate()
5873 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
5874 .map(|(i, _)| i as u8)
5875 .expect("a palette holds at least two colours")
5876 })
5877 .collect();
5878 crate::tile::PaletteY {
5879 size: colors.len() as u8,
5880 colors: base,
5881 map,
5882 }
5883 };
5884 if present.len() <= 8 {
5885 return vec![exact(&present)];
5886 }
5887 if present.len() > palette_max_colors() {
5888 return Vec::new();
5889 }
5890 let (lo, hi) = (i32::from(present[0]), i32::from(present[present.len() - 1]));
5891 let mut out = Vec::with_capacity(2);
5892 for n in [8usize, 4] {
5893 // Even seeding across the block's own range, then four Lloyd passes
5894 // over the histogram (256 bins, not `side*side` pixels).
5895 let mut centres: Vec<f64> = (0..n)
5896 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
5897 .collect();
5898 for _ in 0..4 {
5899 let mut sums = vec![0f64; n];
5900 let mut counts = vec![0u32; n];
5901 for (v, &count) in histogram.iter().enumerate() {
5902 if count == 0 {
5903 continue;
5904 }
5905 let k = (0..n)
5906 .min_by(|&a, &b| {
5907 (centres[a] - v as f64)
5908 .abs()
5909 .total_cmp(&(centres[b] - v as f64).abs())
5910 })
5911 .expect("n >= 2");
5912 sums[k] += (v as u32 * count) as f64;
5913 counts[k] += count;
5914 }
5915 for k in 0..n {
5916 if counts[k] > 0 {
5917 centres[k] = sums[k] / f64::from(counts[k]);
5918 }
5919 }
5920 }
5921 let mut colors: Vec<u16> = centres
5922 .iter()
5923 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
5924 .collect();
5925 colors.sort_unstable();
5926 colors.dedup();
5927 if colors.len() >= 2 {
5928 out.push(exact(&colors));
5929 }
5930 }
5931 out
5932}
5933
5934#[allow(clippy::too_many_arguments)]
5935// ---------------------------------------------------------------------------
5936// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
5937// validity). A key frame that detected screen content and finds enough exact
5938// repeats in its own source sets `allow_intrabc`, which the spec forces every
5939// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
5940// its place when the copied blocks pay back the deblock/CDEF/LR the frame
5941// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
5942// ---------------------------------------------------------------------------
5943
5944/// Whether intra block copy is offered at all. **Off by default** --
5945/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
5946/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
5947/// but on the gate's real screen capture it MEASURED WORSE: setting
5948/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
5949/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
5950/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
5951/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
5952/// that detected no screen content.
5953fn intrabc_enabled() -> bool {
5954 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
5955 return forced;
5956 }
5957 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5958 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
5959}
5960
5961thread_local! {
5962 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
5963 /// probe runs both arms in one process, and the suite is one process, so
5964 /// an environment variable cannot separate them (same reason
5965 /// [`SCREEN_FORCE`] exists).
5966 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
5967}
5968
5969#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5970pub(crate) fn force_intrabc(value: Option<bool>) {
5971 INTRABC_FORCE.with(|c| c.set(value));
5972}
5973
5974/// How many of a screen frame's 16x16 blocks must have an exact repeat
5975/// somewhere else in the source before `allow_intrabc` is worth the in-loop
5976/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
5977/// constant class: `probe_intrabc_threshold` measures the arm at several
5978/// values.
5979fn intrabc_pct() -> usize {
5980 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5981 *N.get_or_init(|| {
5982 std::env::var("EC_AV1_INTRABC_PCT")
5983 .ok()
5984 .and_then(|v| v.parse().ok())
5985 .unwrap_or(10)
5986 })
5987}
5988
5989/// The pixel grid intrabc source positions are hashed on
5990/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
5991/// which keeps the block-hash table (and so the search) linear in the frame
5992/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
5993/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
5994/// bilinear interpolation decode.rs applies but this encoder does not.
5995fn intrabc_step() -> usize {
5996 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5997 *N.get_or_init(|| {
5998 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
5999 .ok()
6000 .and_then(|v| v.parse().ok())
6001 .unwrap_or(4);
6002 if n % 2 == 0 { n.max(2) } else { 4 }
6003 })
6004}
6005
6006/// The side of the luma square the block-hash table is keyed on.
6007const IBC_HASH: usize = 16;
6008
6009/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
6010/// the current one the source's bottom-right corner must already be. Under
6011/// 128 superblocks the same 256 pixels are two superblocks, which
6012/// [`Ibc::dv_valid`] derives from the size itself.
6013const INTRABC_DELAY_SB64: i32 = 4;
6014
6015/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
6016fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
6017 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
6018 for row in 0..IBC_HASH {
6019 let base = (y + row) * width + x;
6020 for &v in &plane[base..base + IBC_HASH] {
6021 h ^= u64::from(v);
6022 h = h.wrapping_mul(0x100_0000_01b3);
6023 }
6024 }
6025 h
6026}
6027
6028/// Every `intrabc_step()`-aligned position of `plane` inside
6029/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
6030fn ibc_index(
6031 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
6032 plane: &[u8],
6033 width: usize,
6034 (x0, y0): (usize, usize),
6035 (x1, y1): (usize, usize),
6036) {
6037 let step = intrabc_step();
6038 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
6039 return;
6040 }
6041 let mut y = y0.next_multiple_of(step);
6042 while y + IBC_HASH <= y1 {
6043 let mut x = x0.next_multiple_of(step);
6044 while x + IBC_HASH <= x1 {
6045 table
6046 .entry(ibc_hash(plane, width, x, y))
6047 .or_default()
6048 .push((x as u32, y as u32));
6049 x += step;
6050 }
6051 y += step;
6052 }
6053}
6054
6055/// Whether `screen`-detected source `y` repeats itself enough to be worth
6056/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
6057/// content appears at some other position, against [`intrabc_pct`]. Returns
6058/// the share as well, for the gate's own print.
6059fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
6060 if true_width < 4 * 64 || true_height < 2 * 64 {
6061 return (false, 0.0);
6062 }
6063 let mut table = std::collections::HashMap::new();
6064 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
6065 let (mut total, mut matched) = (0usize, 0usize);
6066 let mut by = 0;
6067 while by + IBC_HASH <= true_height {
6068 let mut bx = 0;
6069 while bx + IBC_HASH <= true_width {
6070 total += 1;
6071 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
6072 if hits
6073 .iter()
6074 .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by))
6075 {
6076 matched += 1;
6077 }
6078 }
6079 bx += IBC_HASH;
6080 }
6081 by += IBC_HASH;
6082 }
6083 let share = if total == 0 {
6084 0.0
6085 } else {
6086 matched as f64 / total as f64
6087 };
6088 (share * 100.0 >= intrabc_pct() as f64, share)
6089}
6090
6091/// One tile's intrabc search state: a block-hash table over the part of the
6092/// tile's own reconstruction that is already final (whole superblock rows --
6093/// the in-loop filters are off on this frame, so a coded superblock row never
6094/// changes again), plus the last DV chosen, which the RD price uses as its
6095/// predictor estimate.
6096struct Ibc {
6097 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
6098 /// source repeats exactly where a lossily coded reconstruction only
6099 /// nearly does, so an exact-match table over the reconstruction finds
6100 /// almost nothing. The candidate is then SCORED against the
6101 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
6102 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
6103 /// The tile's own luma rect, in samples.
6104 tile: (usize, usize, usize, usize),
6105 /// The DV the previous intrabc block of this tile took -- the *estimate*
6106 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
6107 /// against. The writer computes the true predictor off its own mi grid
6108 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
6109 /// a slightly mispriced candidate, never a wrong bitstream.
6110 last_dv: Option<(i32, i32)>,
6111 /// How many blocks took intrabc, and how many hash lookups found at least
6112 /// one valid candidate -- the gate's own fire counts.
6113 hits: usize,
6114 lookups: usize,
6115 found: usize,
6116}
6117
6118impl Ibc {
6119 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
6120 let mut table = std::collections::HashMap::new();
6121 ibc_index(
6122 &mut table,
6123 source,
6124 width,
6125 (tile.0, tile.1),
6126 (tile.2, tile.3),
6127 );
6128 Self {
6129 table,
6130 tile,
6131 last_dv: None,
6132 hits: 0,
6133 lookups: 0,
6134 found: 0,
6135 }
6136 }
6137
6138 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
6139 /// (1/8 pel), with this lane's own extra restriction on top: the source
6140 /// must lie entirely in a COMPLETED superblock row, which is exactly the
6141 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
6142 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
6143 /// wavefront's own diagonal) are legal and not searched; the upgrade path
6144 /// is to index the current row's finished superblocks too.
6145 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
6146 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
6147 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
6148 return false;
6149 }
6150 let (tx0, ty0, tx1, ty1) = (
6151 self.tile.0 as i32,
6152 self.tile.1 as i32,
6153 self.tile.2 as i32,
6154 self.tile.3 as i32,
6155 );
6156 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
6157 let (w, h) = (w as i32, h as i32);
6158 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
6159 return false;
6160 }
6161 // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
6162 // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
6163 // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
6164 // Counting 64s under a 128 superblock let the search take a source
6165 // from a 64 row the 128 visit order had not reconstructed yet.
6166 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
6167 let delay: i32 = if sb_log2 == 7 {
6168 INTRABC_DELAY_SB64 / 2
6169 } else {
6170 INTRABC_DELAY_SB64
6171 };
6172 let active_sb_row = (y as i32 - ty0) >> sb_log2;
6173 let active_sb_col = (x as i32 - tx0) >> sb_log2;
6174 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
6175 let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
6176 // This lane's own restriction (see the doc comment).
6177 if src_sb_row >= active_sb_row {
6178 return false;
6179 }
6180 let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
6181 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
6182 return false;
6183 }
6184 // libaom's wavefront: only the top-left cone of the frame is legal.
6185 let wf = (1 + delay) * (active_sb_row - src_sb_row);
6186 src_sb_col < active_sb_col - delay + wf
6187 }
6188}
6189
6190/// How many block searches ran, how many found at least one VALID candidate,
6191/// and how many won on rate-distortion -- the hash hit rate a gate prints
6192/// (class `gate-blind-to-feature`: "the search ran" and "the search found
6193/// something" and "the block took it" are three different claims).
6194static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
6195 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
6196
6197impl Drop for Ibc {
6198 fn drop(&mut self) {
6199 for (slot, n) in [self.lookups, self.found, self.hits]
6200 .into_iter()
6201 .enumerate()
6202 {
6203 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
6204 }
6205 }
6206}
6207
6208/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
6209/// its own encode.
6210#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6211pub(crate) fn take_intrabc_search() -> [usize; 3] {
6212 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
6213}
6214
6215/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
6216/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
6217/// infers rather than codes.
6218fn dv_component_bits(diff: i32) -> f64 {
6219 let z = diff.unsigned_abs() as i32 - 1;
6220 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
6221 let class = mv_class_of(z);
6222 bits += symbol_bits(&cdf::MV_CLASS, class);
6223 let local = z - mv_class_base(class);
6224 if class == 0 {
6225 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
6226 } else {
6227 let d = local >> 3;
6228 for i in 0..class {
6229 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
6230 }
6231 }
6232 bits
6233}
6234
6235/// What one block vector costs against `pred`, plus the `skip` and
6236/// `use_intrabc` flags the block carries and the ordinary intra block does
6237/// not pay in this currency.
6238fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
6239 let diff = (dv.0 - pred.0, dv.1 - pred.1);
6240 let joint = match (diff.0 != 0, diff.1 != 0) {
6241 (false, false) => 0,
6242 (false, true) => 1,
6243 (true, false) => 2,
6244 (true, true) => 3,
6245 };
6246 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
6247 if diff.0 != 0 {
6248 bits += dv_component_bits(diff.0);
6249 }
6250 if diff.1 != 0 {
6251 bits += dv_component_bits(diff.1);
6252 }
6253 bits
6254}
6255
6256/// The squared error of copying the `side`-square block at `(sx, sy)` of each
6257/// plane's reconstruction onto the source block at `(x, y)`, luma and both
6258/// chroma planes together -- what an intrabc block's whole (residual-free)
6259/// distortion is.
6260fn ibc_sse(
6261 luma: &Plane,
6262 chroma: &[Plane; 2],
6263 (x, y): (usize, usize),
6264 (sx, sy): (usize, usize),
6265 side: usize,
6266) -> f64 {
6267 // Inside the true frame only, for the reason [`Plane::block_sse`] is
6268 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
6269 // how well it copies the padding.
6270 let mut sse = 0.0f64;
6271 let clip = |whole: usize, inside: usize| match edge_sse() {
6272 true => whole.min(inside),
6273 false => whole,
6274 };
6275 let rows = clip(side, luma.true_height.saturating_sub(y));
6276 let cols = clip(side, luma.true_width.saturating_sub(x));
6277 for row in 0..rows {
6278 let src = &luma.source[(y + row) * luma.width + x..][..cols];
6279 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
6280 for (&s, &r) in src.iter().zip(rec) {
6281 let d = f64::from(i32::from(s) - i32::from(r));
6282 sse += d * d;
6283 }
6284 }
6285 let half = side / 2;
6286 for plane in chroma {
6287 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
6288 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
6289 for row in 0..rows {
6290 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
6291 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
6292 for (&s, &r) in src.iter().zip(rec) {
6293 let d = f64::from(i32::from(s) - i32::from(r));
6294 sse += d * d;
6295 }
6296 }
6297 }
6298 sse
6299}
6300
6301/// Copies the `side`-square block at `(sx, sy)` of each plane's
6302/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
6303/// since it carries no residual (`skip`). Full-pel in both planes by
6304/// construction ([`intrabc_step`] keeps every DV even), which is what makes
6305/// this a plain copy where decode.rs runs the bilinear kernel over the same
6306/// samples.
6307fn ibc_commit(
6308 luma: &mut Plane,
6309 chroma: &mut [Plane; 2],
6310 (x, y): (usize, usize),
6311 (sx, sy): (usize, usize),
6312 side: usize,
6313) {
6314 for row in 0..side {
6315 let from = (sy + row) * luma.width + sx;
6316 let to = (y + row) * luma.width + x;
6317 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
6318 luma.reconstruction[to..to + side].copy_from_slice(&copied);
6319 }
6320 let half = side / 2;
6321 for plane in chroma {
6322 for row in 0..half {
6323 let from = (sy / 2 + row) * plane.width + sx / 2;
6324 let to = (y / 2 + row) * plane.width + x / 2;
6325 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
6326 plane.reconstruction[to..to + half].copy_from_slice(&copied);
6327 }
6328 plane.commit_ctx_zero(x / 2, y / 2, half);
6329 }
6330 luma.commit_ctx_zero(x, y, side);
6331}
6332
6333/// Searches this block's own DV: every hash-table position whose 16x16 luma
6334/// square equals the block's source square, plus the previous block's DV as a
6335/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
6336/// the winning `(dv, cost)`, or `None` when nothing valid was found.
6337fn ibc_search(
6338 ibc: &mut Ibc,
6339 luma: &Plane,
6340 chroma: &[Plane; 2],
6341 (x, y): (usize, usize),
6342 side: usize,
6343 lambda: f64,
6344) -> Option<((i32, i32), f64, (usize, usize))> {
6345 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
6346 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
6347 let consider =
6348 |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
6349 let dv = ((sy as i32 - y as i32) * 8, (sx as i32 - x as i32) * 8);
6350 if !ibc.dv_valid(x, y, side, side, dv) {
6351 return;
6352 }
6353 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
6354 if best.as_ref().is_none_or(|b| cost < b.1) {
6355 *best = Some((dv, cost, (sx, sy)));
6356 }
6357 };
6358 ibc.lookups += 1;
6359 let key = ibc_hash(luma.source, luma.width, x, y);
6360 // The table is filled in raster order, so the entries BEFORE this block's
6361 // own position are exactly the already-coded ones -- and the nearest of
6362 // them costs the fewest DV bits. Walking backwards from the block's own
6363 // slot is what makes the search look up-and-left; taking the newest
6364 // entries outright only ever finds candidates below and to the right,
6365 // every one of which `dv_valid` rejects.
6366 let hits: Vec<(u32, u32)> = ibc
6367 .table
6368 .get(&key)
6369 .map(|h| {
6370 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
6371 h[..end].iter().rev().take(32).copied().collect()
6372 })
6373 .unwrap_or_default();
6374 for (hx, hy) in hits {
6375 consider(&*ibc, hx as usize, hy as usize, &mut best);
6376 }
6377 if let Some(dv) = ibc.last_dv {
6378 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
6379 if sx >= 0 && sy >= 0 {
6380 consider(&*ibc, sx as usize, sy as usize, &mut best);
6381 }
6382 }
6383 if best.is_some() {
6384 ibc.found += 1;
6385 }
6386 best
6387}
6388
6389fn code_square(
6390 luma: &mut Plane,
6391 chroma: &mut [Plane; 2],
6392 (x, y): (usize, usize),
6393 side: usize,
6394 search: &Search,
6395 mode_bits: &[f64; 13],
6396 // The frame header's `tx_mode == TxMode::Select`: the block then searches
6397 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
6398 // transform over its whole side.
6399 tx_select: bool,
6400 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
6401 // header did not set `allow_intrabc`.
6402 ibc: Option<&mut Ibc>,
6403 // Whether this is a KEY frame's block, read only by the split census
6404 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
6405 // which is this lane's whole finding.
6406 census_key: bool,
6407 fctx: &crate::decode::FrameCtx,
6408) -> (BlockCoeffs, f64) {
6409 let (luma_set, chroma_set) = if side == SUPERBLOCK {
6410 // A whole superblock coded as ONE intra block (lane-i64): one
6411 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
6412 // `code_from_prediction` hands back, and one TX_32X32 per chroma
6413 // plane -- the same three sets the key frame writer's
6414 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
6415 // uses (`search_skip_64`).
6416 (TxbSet::Luma64, TxbSet::Chroma32)
6417 } else if side == BLOCK {
6418 (TxbSet::Luma32, TxbSet::Chroma16)
6419 } else if side == 8 {
6420 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
6421 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
6422 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
6423 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
6424 // (this branch is still unreached), so leaving `Chroma8` here would
6425 // silently wire the wrong table the moment one does; `Chroma4` is
6426 // what a real caller needs.
6427 (TxbSet::Luma8, TxbSet::Chroma4)
6428 } else {
6429 (TxbSet::Luma16, TxbSet::Chroma8)
6430 };
6431 let at = At {
6432 x,
6433 y,
6434 side,
6435 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
6436 set: luma_set_for(luma_set, search.screen),
6437 };
6438 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
6439 luma.search_block(at, search, mode_bits, fctx);
6440 let mut luma_tx_types = vec![tx_type];
6441 // The depth search runs on the mode the whole-block transform picked --
6442 // libaom's own ordering, and the reason it costs one extra pass per depth
6443 // rather than one per (mode, depth) pair.
6444 let mut tx_depth = 0u8;
6445 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
6446 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
6447 // pays that zero exactly as a 32x32's depth search makes it pay
6448 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
6449 // below hands the root a symbol for free.
6450 if tx_select && side == SUPERBLOCK {
6451 cost += search.lambda * tx_depth_bits(side, 0);
6452 }
6453 if tx_select && max_tx_depth(side) > 0 {
6454 let mut best = (
6455 cost + search.lambda * tx_depth_bits(side, 0),
6456 0usize,
6457 luma.snapshot(x, y, side),
6458 luma_coeffs,
6459 );
6460 let mut best_types = std::mem::take(&mut luma_tx_types);
6461 // The census wants the flat arm's own (rate, distortion), which
6462 // `search_block` only hands back folded into one cost -- so under the
6463 // env flag alone it is re-coded at depth 0 and the plane restored.
6464 let census_flat = split_census_on().then(|| {
6465 let kept = luma.snapshot(x, y, side);
6466 let (_, sse, bits, _) =
6467 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
6468 luma.restore(x, y, side, &kept);
6469 (bits + tx_depth_bits(side, 0), sse)
6470 });
6471 let mut census_split: Option<(f64, f64)> = None;
6472 for depth in 1..=max_tx_depth(side) {
6473 let (levels, sse, bits, types) =
6474 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
6475 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
6476 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
6477 if census_flat.is_some() {
6478 let c = (bits + tx_depth_bits(side, depth), sse);
6479 if census_split
6480 .is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
6481 {
6482 census_split = Some(c);
6483 }
6484 }
6485 if cost_d < best.0 {
6486 best = (
6487 cost_d,
6488 depth,
6489 luma.snapshot(x, y, side),
6490 coeffs(&levels, side),
6491 );
6492 best_types = types;
6493 }
6494 }
6495 if let (Some(flat), Some(split)) = (census_flat, census_split) {
6496 split_census(0, census_key, side, best.1 > 0, split, flat);
6497 }
6498 luma_tx_types = best_types;
6499 luma.restore(x, y, side, &best.2);
6500 cost = best.0;
6501 tx_depth = best.1 as u8;
6502 luma_coeffs = best.3;
6503 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6504 }
6505 // The palette candidate is priced against the mode the luma search (and
6506 // its transform-depth search) already settled on, so a block only takes
6507 // one when it beats the best ordinary intra coding of the same pixels.
6508 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
6509 // prediction is the colour map, not the DC of its neighbours.
6510 let mut mode = mode;
6511 let mut angle_delta = angle_delta;
6512 let mut palette = None;
6513 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6514 let source: Vec<u8> = (y..y + side)
6515 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
6516 .collect();
6517 let kept = luma.snapshot(x, y, side);
6518 // spec 5.11.50: a block cut by the frame's right/bottom edge codes
6519 // its map over the ON-SCREEN corner only and the decoder replicates
6520 // that outward, so the searched map is folded the same way here --
6521 // the prediction priced, the reconstruction committed and the symbols
6522 // `write_color_index_map` writes are then one and the same map
6523 // (lane-palw).
6524 let on = (
6525 side.min(luma.true_width.saturating_sub(x)),
6526 side.min(luma.true_height.saturating_sub(y)),
6527 );
6528 for mut pal in palette_candidates(&source) {
6529 let n = usize::from(pal.size);
6530 crate::decode::palette_replicate(&mut pal.map, side, side, on);
6531 let prediction: Vec<u8> = pal
6532 .map
6533 .iter()
6534 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
6535 .collect();
6536 let trial = luma.code_from_prediction(
6537 x,
6538 y,
6539 side,
6540 &prediction,
6541 false,
6542 search.base_q_idx,
6543 search.deadzone,
6544 luma_set,
6545 );
6546 let cost_p = trial.sse
6547 + search.lambda
6548 * (trial.bits
6549 + mode_bits[DC_PRED as usize]
6550 + crate::tile::palette_bits(&pal, side, on)
6551 + if tx_select {
6552 tx_depth_bits(side, 0)
6553 } else {
6554 0.0
6555 });
6556 if cost_p < cost {
6557 cost = cost_p;
6558 mode = DC_PRED as u8;
6559 angle_delta = 0;
6560 tx_depth = 0;
6561 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
6562 luma.commit(x, y, side, &trial);
6563 palette = Some(pal);
6564 }
6565 }
6566 if palette.is_none() {
6567 luma.restore(x, y, side, &kept);
6568 }
6569 }
6570
6571 // The five recursive filter-intra modes (spec 5.11.14), priced against
6572 // whatever the mode, transform-depth and palette searches settled on --
6573 // the same "one candidate loop after the incumbent is known" shape the
6574 // palette above uses. A block that takes one is `DC_PRED` with no palette
6575 // by construction (`av1_filter_intra_allowed`), and its luma transform
6576 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
6577 //
6578 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
6579 // depth the ordinary intra search runs, each unit predicting recursively
6580 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
6581 // arm), so a block whose ordinary winner wanted a split transform is
6582 // compared against a filter arm that may split too.
6583 //
6584 // Measured (native BD table, lane-fitu): searching the depths on EVERY
6585 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
6586 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
6587 // locally cheaper reconstruction that the film rows go on to predict from
6588 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
6589 // content is where it pays, and a non-screen frame keeps the depth-0-only
6590 // arm, byte for byte.
6591 let mut filter_intra: Option<u8> = None;
6592 if filter_intra_on()
6593 && palette.is_none()
6594 && let Some(class) = crate::decode::filter_intra_size_class(side)
6595 {
6596 let row = &cdf::FILTER_INTRA[class];
6597 // With the sequence bit on, EVERY `DC_PRED` block without a luma
6598 // palette carries the flag, so the incumbent pays its zero before the
6599 // comparison -- otherwise the candidate is charged a bit the block
6600 // spends either way (class `price-the-narrowing-not-the-table`).
6601 if mode == DC_PRED {
6602 cost += search.lambda * symbol_bits(row, 0);
6603 }
6604 let one_bits = symbol_bits(row, 1);
6605 let kept = luma.snapshot(x, y, side);
6606 let max_depth = if tx_select && search.screen {
6607 max_tx_depth(side)
6608 } else {
6609 0
6610 };
6611 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
6612 for fi in 0..5u8 {
6613 for depth in 0..=max_depth {
6614 // A filter-intra block's units are coded through
6615 // `code_from_prediction`, which is `DCT_DCT` throughout, so
6616 // this arm keeps the empty (all-`DCT_DCT`) type list.
6617 let (levels, sse, bits, _) =
6618 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
6619 let cost_f = sse
6620 + search.lambda
6621 * (bits
6622 + mode_bits[DC_PRED as usize]
6623 + one_bits
6624 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
6625 + if tx_select {
6626 tx_depth_bits(side, depth)
6627 } else {
6628 0.0
6629 });
6630 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
6631 best = Some((
6632 cost_f,
6633 fi,
6634 depth,
6635 luma.snapshot(x, y, side),
6636 coeffs(&levels, side),
6637 ));
6638 }
6639 }
6640 }
6641 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
6642 cost = cost_f;
6643 mode = DC_PRED;
6644 angle_delta = 0;
6645 tx_depth = depth as u8;
6646 luma_coeffs = levels;
6647 luma.restore(x, y, side, &snapshot);
6648 filter_intra = Some(fi);
6649 } else {
6650 luma.restore(x, y, side, &kept);
6651 }
6652 }
6653
6654 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
6655 // planes; what it costs still counts towards the partition decision.
6656 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
6657 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
6658 cost += chroma_cost;
6659
6660 // The intrabc arm is priced against the WHOLE block -- luma and both
6661 // chroma planes, residual-free -- so it is compared after the chroma
6662 // search has added its own cost, not against the luma decision alone.
6663 if let Some(ibc) = ibc {
6664 if let Some((dv, cost_ibc, src)) =
6665 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
6666 {
6667 if cost_ibc < cost {
6668 ibc_commit(luma, chroma, (x, y), src, side);
6669 ibc.last_dv = Some(dv);
6670 ibc.hits += 1;
6671 return (
6672 BlockCoeffs {
6673 skip: true,
6674 dv: Some(dv),
6675 ..BlockCoeffs::default()
6676 },
6677 cost_ibc,
6678 );
6679 }
6680 }
6681 }
6682 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
6683 // (its levels came from `code_from_prediction`), so the searched types
6684 // belong to a block this one no longer is.
6685 if palette.is_some() || filter_intra.is_some() {
6686 luma_tx_types = Vec::new();
6687 }
6688 (
6689 BlockCoeffs {
6690 u,
6691 v,
6692 luma: luma_coeffs,
6693 mode,
6694 uv_mode,
6695 tx_depth,
6696 palette,
6697 palette_uv,
6698 filter_intra,
6699 cfl_alphas,
6700 angle_delta_y: angle_delta as i8,
6701 luma_tx_types,
6702 ..BlockCoeffs::default()
6703 },
6704 cost,
6705 )
6706}
6707
6708/// The chroma modes the search offers, and the only ones it may offer: each
6709/// predicts from the row directly above and the column directly to the left
6710/// and nothing further, so none of them needs the above-right/below-left
6711/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
6712/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
6713/// reconstruction and its own alpha syntax; both are left out here.
6714const CHROMA_MODES: [u8; 7] = [
6715 DC_PRED,
6716 V_PRED,
6717 H_PRED,
6718 SMOOTH_PRED,
6719 SMOOTH_V_PRED,
6720 SMOOTH_H_PRED,
6721 PAETH_PRED,
6722];
6723
6724/// The thirteen intra mode names, for the chroma fire count's print.
6725#[cfg(test)]
6726const UV_MODE_NAMES: [&str; 14] = [
6727 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", "SMOOTH_H",
6728 "PAETH", "CFL",
6729];
6730
6731/// How many blocks each chroma mode has won, indexed by the mode itself --
6732/// the fire count that says whether the search below reaches its candidates
6733/// at all (the `gate-blind-to-feature` class), printed once per gate run.
6734static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
6735 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
6736
6737/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
6738/// won, summed over both chroma planes -- the alpha histogram the gate prints
6739/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
6740/// magnitude only is a search that never left its first candidate).
6741static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
6742 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
6743
6744/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
6745/// zero on a CfL block", `1..=16` the magnitudes.
6746#[cfg(test)]
6747pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
6748 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6749}
6750
6751/// How many directional luma blocks won at each `angle_delta_y`, indexed
6752/// `delta + 3` -- the histogram that says whether the refinement below ever
6753/// leaves zero (`gate-blind-to-feature`).
6754static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
6755 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
6756
6757/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
6758#[cfg(test)]
6759pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
6760 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
6761}
6762
6763/// Whether the luma search refines a directional winner's `angle_delta_y`
6764/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
6765fn angle_delta_on() -> bool {
6766 static ENV: std::sync::LazyLock<Option<bool>> =
6767 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0"));
6768 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
6769}
6770
6771/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
6772/// switches it off, which is how the lane measured its own on/off pair).
6773fn cfl_on() -> bool {
6774 static ENV: std::sync::LazyLock<Option<bool>> =
6775 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0"));
6776 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
6777}
6778
6779/// Whether the intra search offers the five recursive filter-intra modes at
6780/// all, and with them whether the sequence header sets `enable_filter_intra`
6781/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
6782/// its own on/off pair -- and how every byte pin written before it still
6783/// reproduces). It is also a speed lever: on at preset 0, off above it.
6784// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
6785// it off for the whole process (a sequence-header field, so it cannot change
6786// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
6787// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
6788// this workspace.
6789
6790/// Whether a sequence codes 128x128 superblocks when the environment says
6791/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
6792/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
6793/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
6794/// 128x128 block in it every row of the native BD gate is down or flat on
6795/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
6796///
6797/// | row | 64 superblocks | 128 + the 128 root |
6798/// |---|---|---|
6799/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
6800/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
6801/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
6802/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
6803/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
6804///
6805/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
6806/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
6807///
6808/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
6809/// off (the delta_q unit at the 128 superblock, the superblock size travelling
6810/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
6811/// predictor and wavefront, and seven test harnesses that handed the encoder a
6812/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
6813pub(crate) const SB128_DEFAULT: bool = true;
6814
6815/// Whether this process's sequences code 128x128 superblocks. An ENCODER
6816/// knob (like `speed::SPEED`), never read by a decode: read through a
6817/// process-global (not a thread-local) because the tile writers run on
6818/// worker threads; `2` is "the environment has not been read yet".
6819static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
6820
6821/// Whether this process's sequences code 128x128 superblocks.
6822pub(crate) fn sb128_on() -> bool {
6823 use std::sync::atomic::Ordering::Relaxed;
6824 match ENC_SB128.load(Relaxed) {
6825 2 => {
6826 let on = crate::envflags::var("EC_AV1_SB128")
6827 .ok()
6828 .map_or(SB128_DEFAULT, |v| v != "0");
6829 ENC_SB128.store(u8::from(on), Relaxed);
6830 on
6831 }
6832 v => v == 1,
6833 }
6834}
6835
6836/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
6837/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
6838/// exactly like the speed-preset gates.
6839#[cfg(test)]
6840pub(crate) fn force_sb128(on: bool) {
6841 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
6842}
6843
6844/// The luma loop-restoration unit size this sequence codes: a 128 superblock
6845/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
6846/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
6847/// 128), which is the one filter parameter the superblock size moves.
6848pub(crate) fn lr_unit() -> u32 {
6849 if sb128_on() { 128 } else { 64 }
6850}
6851
6852pub(crate) fn filter_intra_on() -> bool {
6853 #[cfg(test)]
6854 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
6855 return forced;
6856 }
6857 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6858 crate::envflags::var("EC_AV1_FILTER_INTRA")
6859 .ok()
6860 .map(|v| v != "0")
6861 });
6862 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
6863}
6864
6865/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
6866/// to its own encode.
6867#[cfg(test)]
6868pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
6869 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6870}
6871
6872/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
6873/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
6874/// Returns each plane's levels, the mode, and what the pair cost (squared
6875/// error plus lambda times bits, the same currency the luma search speaks).
6876///
6877/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
6878/// which is what the luma mode decision was taken against, so what a
6879/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
6880/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
6881/// writer then has to code.
6882#[allow(clippy::too_many_arguments)]
6883/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
6884/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
6885/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
6886/// trials all seven, as before this lever.
6887///
6888/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
6889/// the search's largest trial population by far -- seven modes times two
6890/// planes for every intra block, against 3.7 luma trials -- and the RD
6891/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
6892/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
6893fn chroma_top_k() -> Option<usize> {
6894 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
6895 crate::envflags::var("EC_AV1_CHROMA_K")
6896 .ok()
6897 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
6898 });
6899 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
6900}
6901
6902/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
6903/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
6904/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
6905/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
6906/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
6907/// BD swings by about a point in either direction as near-tie chroma modes
6908/// flip, which is the measurement's own sensitivity, not a trend: nothing
6909/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
6910/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
6911/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
6912/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
6913pub(crate) const CHROMA_TOP_K: Option<usize> = None;
6914
6915fn search_chroma(
6916 chroma: &mut [Plane; 2],
6917 // The luma plane's RECONSTRUCTION under this block, already committed by
6918 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
6919 luma: &Plane,
6920 (x, y): (usize, usize),
6921 side: usize,
6922 set: TxbSet,
6923 search: &Search,
6924 luma_mode: u8,
6925 fctx: &crate::decode::FrameCtx,
6926) -> (
6927 [Vec<Coeff>; 2],
6928 u8,
6929 f64,
6930 Option<crate::tile::PaletteUv>,
6931 Option<(i32, i32)>,
6932) {
6933 let at = At {
6934 x: x / 2,
6935 y: y / 2,
6936 side: side / 2,
6937 reach: Reach::none(),
6938 set,
6939 };
6940 // The census's cheap proxy for a chroma mode: the SAD of its prediction
6941 // summed over both planes, ranked by the same rule the luma histogram
6942 // uses. Only built under `EC_AV1_CENSUS`.
6943 // The SAD of each mode's prediction, summed over both planes -- the
6944 // census's ranking rule, and what [`chroma_top_k`] prunes by.
6945 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
6946 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6947 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6948 u.iter()
6949 .zip(v.iter())
6950 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
6951 .collect()
6952 };
6953 let modes: Vec<u8> = match chroma_top_k() {
6954 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
6955 _ => CHROMA_MODES.to_vec(),
6956 };
6957 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
6958 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
6959 let ranking: Vec<(f64, u8)> = if census_on() {
6960 sad_scores(chroma)
6961 } else {
6962 Vec::new()
6963 };
6964 census_add(2, 1);
6965 census_add(3, modes.len());
6966 let mut best: Option<(f64, u8, Trial, Trial)> = None;
6967 for mode in modes {
6968 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
6969 if (V_PRED..=D67_PRED).contains(&mode) {
6970 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
6971 }
6972 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
6973 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
6974 // chroma of a 64x64 block is `DCT_DCT` whatever
6975 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
6976 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
6977 // points.
6978 let tx_type = if at.side >= 32 {
6979 TxType::DctDct
6980 } else {
6981 crate::decode::default_intra_tx_type(mode)
6982 };
6983 let u = chroma[0].trial_typed(
6984 at,
6985 mode,
6986 0,
6987 search.base_q_idx,
6988 search.deadzone,
6989 tx_type,
6990 fctx,
6991 );
6992 let v = chroma[1].trial_typed(
6993 at,
6994 mode,
6995 0,
6996 search.base_q_idx,
6997 search.deadzone,
6998 tx_type,
6999 fctx,
7000 );
7001 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
7002 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
7003 best = Some((cost, mode, u, v));
7004 }
7005 }
7006 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
7007 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
7008 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
7009 // what keeps `u_colors` ascending and distinct the way
7010 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
7011 // each cluster's own mean, since the colour-index map is SHARED by the
7012 // two planes. Priced against the best ordinary chroma mode above, so a
7013 // block only takes one when it beats it; a palette block's chroma mode is
7014 // `UV_DC_PRED` by construction.
7015 let mut palette_uv = None;
7016 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
7017 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
7018 let plane_source = |p: &Plane| -> Vec<u8> {
7019 (at.y..at.y + at.side)
7020 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
7021 .collect()
7022 };
7023 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
7024 // The luma on-screen extent carried into this plane exactly as the
7025 // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
7026 let on_uv = crate::decode::palette_onscreen_uv(
7027 (side, side),
7028 (
7029 side.min(luma.true_width.saturating_sub(x)),
7030 side.min(luma.true_height.saturating_sub(y)),
7031 ),
7032 (at.side, at.side),
7033 // The encoder writes 4:2:0 only (`palette_uv_side` above).
7034 (1, 1),
7035 );
7036 for mut pal in palette_candidates(&u_source) {
7037 let n = usize::from(pal.size);
7038 crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
7039 // V's base colour per cluster: the mean of the samples the shared
7040 // map assigns to it (an empty cluster cannot happen -- every
7041 // colour `palette_candidates` returns is some pixel's nearest).
7042 let mut sums = [0u32; 8];
7043 let mut counts = [0u32; 8];
7044 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
7045 let k = usize::from(i).min(n - 1);
7046 sums[k] += u32::from(sample);
7047 counts[k] += 1;
7048 }
7049 let mut v_colors = [0u16; 8];
7050 for k in 0..n {
7051 v_colors[k] = if counts[k] > 0 {
7052 ((sums[k] + counts[k] / 2) / counts[k]) as u16
7053 } else {
7054 0
7055 };
7056 }
7057 let candidate = crate::tile::PaletteUv {
7058 size: pal.size,
7059 u_colors: pal.colors,
7060 v_colors,
7061 map: pal.map,
7062 };
7063 let predict = |colors: &[u16; 8]| -> Vec<u8> {
7064 candidate
7065 .map
7066 .iter()
7067 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
7068 .collect()
7069 };
7070 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
7071 let u_trial = chroma[0].code_from_prediction(
7072 at.x,
7073 at.y,
7074 at.side,
7075 &pu,
7076 false,
7077 search.base_q_idx,
7078 search.deadzone,
7079 set,
7080 );
7081 let v_trial = chroma[1].code_from_prediction(
7082 at.x,
7083 at.y,
7084 at.side,
7085 &pv,
7086 false,
7087 search.base_q_idx,
7088 search.deadzone,
7089 set,
7090 );
7091 let cost_p = u_trial.sse
7092 + v_trial.sse
7093 + search.lambda
7094 * (u_trial.bits
7095 + v_trial.bits
7096 + crate::tile::palette_uv_bits(&candidate, side, on_uv));
7097 if cost_p < cost {
7098 cost = cost_p;
7099 mode = DC_PRED;
7100 u = u_trial;
7101 v = v_trial;
7102 palette_uv = Some(candidate);
7103 }
7104 }
7105 }
7106 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
7107 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
7108 // nudges every sample by `alpha_q3` times the block's subsampled,
7109 // average-subtracted luma reconstruction. Offered only where
7110 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
7111 // and priced against the best ordinary chroma mode above, palette
7112 // included, so a block only takes it when it beats both.
7113 let mut cfl_alphas = None;
7114 if side <= 32 && cfl_on() {
7115 // The AC signal, through the decoder's own
7116 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
7117 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
7118 i32::from(luma.reconstruction[ly * luma.width + lx])
7119 });
7120 let dc_prediction = |plane: &Plane| -> Vec<u8> {
7121 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
7122 let (above, left, corner) =
7123 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
7124 let mut prediction = vec![0u8; at.side * at.side];
7125 intra_predict_u8(
7126 DC_PRED,
7127 0,
7128 above,
7129 left,
7130 corner,
7131 at.side,
7132 at.side,
7133 false,
7134 false,
7135 &mut prediction,
7136 fctx,
7137 );
7138 prediction
7139 };
7140 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
7141 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
7142 // add the residual -- which is what [`Plane::code_from_prediction`]
7143 // does with what this returns.
7144 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
7145 base.iter()
7146 .zip(ac.iter())
7147 .map(|(&b, &a)| {
7148 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
7149 })
7150 .collect()
7151 };
7152 // The least-squares alpha, then its two neighbours: minimising
7153 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
7154 // dot-product ratio, and the quantised optimum is one of the two
7155 // integers around it (the clamp and the Q6 rounding are what the SSE
7156 // check below re-decides). libaom sweeps all sixteen magnitudes under
7157 // full RD; three predictions per plane buy nearly the same alpha for a
7158 // thirtieth of the search.
7159 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
7160 let (mut num, mut den) = (0.0f64, 0.0f64);
7161 for row in 0..at.side {
7162 for col in 0..at.side {
7163 let i = row * at.side + col;
7164 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
7165 - f64::from(base[i]);
7166 num += d * f64::from(ac[i]);
7167 den += f64::from(ac[i]) * f64::from(ac[i]);
7168 }
7169 }
7170 if den == 0.0 {
7171 return 0;
7172 }
7173 let ideal = 64.0 * num / den;
7174 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
7175 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
7176 let alpha = alpha.clamp(-16, 16) as i32;
7177 if alpha == 0 {
7178 continue;
7179 }
7180 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
7181 if sse < best.0 {
7182 best = (sse, alpha);
7183 }
7184 }
7185 best.1
7186 };
7187 let picked = [
7188 pick_alpha(&chroma[0], &bases[0]),
7189 pick_alpha(&chroma[1], &bases[1]),
7190 ];
7191 if picked != [0, 0] {
7192 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
7193 let trial = |plane_idx: usize, alpha: i32| -> Trial {
7194 let prediction = if alpha == 0 {
7195 bases[plane_idx].clone()
7196 } else {
7197 apply(&bases[plane_idx], alpha)
7198 };
7199 chroma[plane_idx].code_from_prediction(
7200 at.x,
7201 at.y,
7202 at.side,
7203 &prediction,
7204 false,
7205 search.base_q_idx,
7206 search.deadzone,
7207 set,
7208 )
7209 };
7210 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
7211 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
7212 let combos: [(i32, i32); 3] = [(picked[0], picked[1]), (picked[0], 0), (0, picked[1])];
7213 for &(alpha_u, alpha_v) in &combos {
7214 if (alpha_u, alpha_v) == (0, 0) {
7215 continue;
7216 }
7217 let cu = trial(0, alpha_u);
7218 let cv = trial(1, alpha_v);
7219 let bits =
7220 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
7221 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
7222 if cost_cfl < cost {
7223 cost = cost_cfl;
7224 mode = crate::tile::UV_CFL_PRED as u8;
7225 u = cu;
7226 v = cv;
7227 palette_uv = None;
7228 cfl_alphas = Some((alpha_u, alpha_v));
7229 }
7230 }
7231 }
7232 }
7233 if let Some((alpha_u, alpha_v)) = cfl_alphas {
7234 for alpha in [alpha_u, alpha_v] {
7235 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
7236 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7237 }
7238 }
7239 if census_on() {
7240 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
7241 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7242 }
7243 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7244 chroma[0].commit(at.x, at.y, at.side, &u);
7245 chroma[1].commit(at.x, at.y, at.side, &v);
7246 (
7247 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
7248 mode,
7249 cost,
7250 palette_uv,
7251 cfl_alphas,
7252 )
7253}
7254
7255/// Codes one leaf of a straddling quadrant as whichever costs least of intra
7256/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
7257/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
7258/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
7259/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
7260/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
7261/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
7262/// attempted here: these leaves only ever fill the sliver of real content a
7263/// true edge lands in the middle of a larger block, not a leaf worth a full
7264/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
7265/// (see `write_inter_frame_leaf`'s doc comment).
7266#[allow(clippy::too_many_arguments)]
7267/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
7268/// as [`code_square_inter`] wants them: empty on a frame that codes no
7269/// `reference_select`, or when the leaf compound candidates are switched off.
7270/// One helper because THREE leaf call sites need it -- the split quadrants
7271/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
7272/// `&[]` and so coded no compound block anywhere along the frame's true edge.
7273#[allow(clippy::too_many_arguments)]
7274fn leaf_compound_stacks<'a>(
7275 grid: &MiGrid,
7276 mi_row: usize,
7277 mi_col: usize,
7278 bw4: usize,
7279 bh4: usize,
7280 mi_cols: usize,
7281 mi_rows: usize,
7282 reference_select: bool,
7283 golden: Option<&'a Picture>,
7284 altref: Option<&'a Picture>,
7285) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
7286 if !(reference_select && leaf_compound()) {
7287 return Vec::new();
7288 }
7289 [
7290 (crate::mvstack::GOLDEN_FRAME, golden),
7291 (crate::mvstack::ALTREF_FRAME, altref),
7292 ]
7293 .into_iter()
7294 .filter_map(|(r, pic)| {
7295 pic.map(|p| {
7296 (
7297 r,
7298 p,
7299 crate::mvstack::find_mv_stack_compound(
7300 grid,
7301 mi_row,
7302 mi_col,
7303 bw4,
7304 bh4,
7305 (crate::mvstack::LAST_FRAME, r),
7306 mi_cols,
7307 mi_rows,
7308 grid.sign_bias_table(),
7309 &[(0, 0); 7],
7310 None,
7311 ),
7312 )
7313 })
7314 })
7315 .collect()
7316}
7317
7318/// The OBMC prediction of one square single-reference block: this block's own
7319/// translation prediction (`mc::predict`) with every bordering above/left
7320/// neighbour blended into the overlap strips by the DECODER's own plan and
7321/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
7322/// the search prices is what a decoder reconstructs -- never a second
7323/// implementation of the blend. `None` when the block has no overlappable
7324/// neighbour at all (the writer would then code no `motion_mode` symbol) or
7325/// when the plan cannot be built (a neighbour naming a reference this encode
7326/// does not hold).
7327#[allow(clippy::too_many_arguments)]
7328fn obmc_prediction(
7329 grid: &MiGrid,
7330 (mi_row, mi_col): (usize, usize),
7331 (mi_rows, mi_cols): (usize, usize),
7332 (x, y): (usize, usize),
7333 side: usize,
7334 mv: (i32, i32),
7335 refs: &[Option<&Picture>; 8],
7336 // This block's OWN reference planes, luma then both chroma, each as
7337 // (samples, stride, true width, true height).
7338 ref_planes: [(&[u16], usize, usize, usize); 3],
7339 frame_width: usize,
7340 fctx: &crate::decode::FrameCtx,
7341) -> Option<[Vec<u8>; 3]> {
7342 let n4 = side / 4;
7343 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
7344 return None;
7345 }
7346 let refpix = crate::decode::RefPix::ready(*refs);
7347 let plan = crate::decode::obmc_plan(
7348 grid,
7349 &[],
7350 &[],
7351 mi_row,
7352 mi_col,
7353 n4,
7354 n4,
7355 mi_rows,
7356 mi_cols,
7357 side,
7358 side,
7359 side,
7360 crate::decode::ss_x(fctx),
7361 crate::decode::ss_y(fctx),
7362 side / 2,
7363 x,
7364 y,
7365 x / 2,
7366 y / 2,
7367 &refpix,
7368 Some(fctx.interp_filter.get()),
7369 frame_width,
7370 )
7371 .ok()?;
7372 let mut pred = [
7373 vec![0u16; side * side],
7374 vec![0u16; side * side / 4],
7375 vec![0u16; side * side / 4],
7376 ];
7377 for (i, r) in ref_planes.into_iter().enumerate() {
7378 let luma_plane = i == 0;
7379 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
7380 let s = if luma_plane { side } else { side / 2 };
7381 mc::predict(
7382 r.0,
7383 r.1,
7384 r.2,
7385 r.3,
7386 mv_to_q4(px, mv.1, luma_plane),
7387 mv_to_q4(py, mv.0, luma_plane),
7388 s,
7389 s,
7390 &mut pred[i],
7391 fctx,
7392 );
7393 }
7394 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
7395 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
7396 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
7397 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
7398}
7399
7400fn code_square_inter(
7401 luma: &mut Plane,
7402 chroma: &mut [Plane; 2],
7403 (x, y): (usize, usize),
7404 side: usize,
7405 search: &Search,
7406 mode_bits: &[f64; 13],
7407 reference: &Picture,
7408 stack: &MvStack,
7409 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
7410 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
7411 // `reference_select`, and at the straddling call sites).
7412 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
7413 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
7414 // (`record_mi`, in the writer's own coding order) and this leaf's place in
7415 // it -- what the OBMC candidate's eligibility walk and neighbour plan
7416 // read, the same state the tile writer reads when it codes the leaf's
7417 // `motion_mode` symbol.
7418 grid: &MiGrid,
7419 (mi_row, mi_col): (usize, usize),
7420 (mi_rows, mi_cols): (usize, usize),
7421 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
7422 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
7423 refs: &[Option<&Picture>; 8],
7424 fctx: &crate::decode::FrameCtx,
7425) -> (BlockCoeffs, f64) {
7426 // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra
7427 // candidate at all -- `intra_cost` stays at infinity, so every
7428 // comparison below takes an inter candidate and the fallback arm at the
7429 // tail is unreachable. The planes hold what the caller snapshotted until
7430 // the winner commits: the intra trial used to commit here and be
7431 // overwritten by the inter commit, so skipping it changes no committed
7432 // sample, only work.
7433 let (intra_block, intra_cost) = if search.arf_leaf_intra {
7434 code_square(
7435 luma,
7436 chroma,
7437 (x, y),
7438 side,
7439 search,
7440 mode_bits,
7441 tx_select() && tx_select_inter(),
7442 None,
7443 false,
7444 fctx,
7445 )
7446 } else {
7447 arfmode_hit(0);
7448 (BlockCoeffs::default(), f64::INFINITY)
7449 };
7450 let luma_set = if side == 8 {
7451 TxbSet::Luma8Inter
7452 } else {
7453 TxbSet::Luma16Inter
7454 };
7455 let chroma_set = if side == 8 {
7456 TxbSet::Chroma4
7457 } else {
7458 TxbSet::Chroma8
7459 };
7460
7461 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
7462 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
7463 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
7464 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
7465 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
7466 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
7467
7468 let mv = stack.nearest_mv;
7469 let ref_luma = (
7470 &reference.y,
7471 reference.width,
7472 luma.true_width,
7473 luma.true_height,
7474 );
7475 let ref_u = (
7476 &reference.u,
7477 reference.width / 2,
7478 chroma[0].true_width,
7479 chroma[0].true_height,
7480 );
7481 let ref_v = (
7482 &reference.v,
7483 reference.width / 2,
7484 chroma[1].true_width,
7485 chroma[1].true_height,
7486 );
7487 let luma_trial = mc_trial(
7488 luma,
7489 x,
7490 y,
7491 side,
7492 mv,
7493 true,
7494 ref_luma.0,
7495 ref_luma.1,
7496 ref_luma.2,
7497 ref_luma.3,
7498 false,
7499 search.base_q_idx,
7500 search.deadzone,
7501 luma_set,
7502 fctx,
7503 );
7504 let u = mc_trial(
7505 &chroma[0],
7506 x / 2,
7507 y / 2,
7508 side / 2,
7509 mv,
7510 false,
7511 ref_u.0,
7512 ref_u.1,
7513 ref_u.2,
7514 ref_u.3,
7515 false,
7516 search.base_q_idx,
7517 search.deadzone,
7518 chroma_set,
7519 fctx,
7520 );
7521 let v = mc_trial(
7522 &chroma[1],
7523 x / 2,
7524 y / 2,
7525 side / 2,
7526 mv,
7527 false,
7528 ref_v.0,
7529 ref_v.1,
7530 ref_v.2,
7531 ref_v.3,
7532 false,
7533 search.base_q_idx,
7534 search.deadzone,
7535 chroma_set,
7536 fctx,
7537 );
7538 let skip = luma_trial.levels.iter().all(|&l| l == 0)
7539 && u.levels.iter().all(|&l| l == 0)
7540 && v.levels.iter().all(|&l| l == 0);
7541 let inter_cost = luma_trial.sse
7542 + u.sse
7543 + v.sse
7544 + search.lambda
7545 * (skip_bits(skip)
7546 + intra_inter_bits(true)
7547 + single_ref_bits
7548 + mode_bits_inter
7549 + if skip {
7550 0.0
7551 } else {
7552 luma_trial.bits + u.bits + v.bits
7553 });
7554
7555 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
7556 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
7557 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
7558 // scan's own coverage already reached as far) but a real gap at 4-mi
7559 // leaf geometry. r3 ported the extended scan and, while proving it a
7560 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
7561 // `mvstack.rs`), found and fixed a second bug the extended scan's
7562 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
7563 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
7564 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
7565 // regardless of whether it also casts a ref-frame-matching vote) --
7566 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
7567 // branches), which is what made 8-mi geometry a true no-op instead of
7568 // one that only held when every neighbour happened to be inter.
7569 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
7570 // only ever took the stack's NEARESTMV candidate or went intra, so a
7571 // 32x32 block splitting because its four quarters MOVE differently could
7572 // not code the movement it split for. Same candidate `search_inter_block`
7573 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
7574 // a vector the residual syntax can name -- at this leaf's own side.
7575 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
7576 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
7577 // re-price below can hand it back as the winner's own mode info.
7578 let nearest_info = InterInfo {
7579 ref1: None,
7580 mv1: (0, 0),
7581 ref_frame: crate::mvstack::LAST_FRAME,
7582 mode: InterMode::NearestMv,
7583 mv,
7584 ref_mv_idx: 0,
7585 };
7586 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
7587 // syntax, apart from its residual: the OBMC candidate re-prices the same
7588 // syntax against a different prediction, so both sides of that comparison
7589 // carry it.
7590 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
7591 // This leaf's own `NEWMV` vector, kept whether or not it won the
7592 // single-reference comparison: it seeds the compound half-new candidate
7593 // below, exactly as `search_inter_block` seeds its own from the searches
7594 // it already ran.
7595 let mut searched_new: Option<(i32, i32)> = None;
7596 // What that search cost, kept for the second reference's own early-out
7597 // below (`None` when this leaf ran no search at all).
7598 let mut searched_new_cost: Option<f64> = None;
7599 let source_block = luma.source_block(x, y, side);
7600 if leaf_new_mv() {
7601 let (seeds, seed_n) = mv_seeds(stack);
7602 let found = motion::search(
7603 ref_luma.0,
7604 ref_luma.1,
7605 ref_luma.2,
7606 ref_luma.3,
7607 &source_block,
7608 x,
7609 y,
7610 side,
7611 side,
7612 stack.pred_mv,
7613 &seeds[..seed_n],
7614 search.lambda,
7615 fctx,
7616 1,
7617 );
7618 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
7619 searched_new_cost = Some(found.cost);
7620 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
7621 if mv_residual.is_none() {
7622 // lane-newmv: a vector the writer cannot name never reaches RD.
7623 newmv_census_block(
7624 side,
7625 false,
7626 f64::INFINITY,
7627 best.0,
7628 new_mv,
7629 stack.nearest_mv,
7630 0.0,
7631 );
7632 }
7633 if let Some(mv_bits) = mv_residual {
7634 searched_new = Some(new_mv);
7635 // Same reuse as `search_inter_block`: a NEWMV equal to the
7636 // stack's NEARESTMV is the same three trials, already run above.
7637 let (luma_new, u_new, v_new) = if new_mv == mv {
7638 (luma_trial.clone(), u.clone(), v.clone())
7639 } else {
7640 (
7641 mc_trial(
7642 luma,
7643 x,
7644 y,
7645 side,
7646 new_mv,
7647 true,
7648 ref_luma.0,
7649 ref_luma.1,
7650 ref_luma.2,
7651 ref_luma.3,
7652 false,
7653 search.base_q_idx,
7654 search.deadzone,
7655 luma_set,
7656 fctx,
7657 ),
7658 mc_trial(
7659 &chroma[0],
7660 x / 2,
7661 y / 2,
7662 side / 2,
7663 new_mv,
7664 false,
7665 ref_u.0,
7666 ref_u.1,
7667 ref_u.2,
7668 ref_u.3,
7669 false,
7670 search.base_q_idx,
7671 search.deadzone,
7672 chroma_set,
7673 fctx,
7674 ),
7675 mc_trial(
7676 &chroma[1],
7677 x / 2,
7678 y / 2,
7679 side / 2,
7680 new_mv,
7681 false,
7682 ref_v.0,
7683 ref_v.1,
7684 ref_v.2,
7685 ref_v.3,
7686 false,
7687 search.base_q_idx,
7688 search.deadzone,
7689 chroma_set,
7690 fctx,
7691 ),
7692 )
7693 };
7694 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
7695 && u_new.levels.iter().all(|&l| l == 0)
7696 && v_new.levels.iter().all(|&l| l == 0);
7697 let drl_bits = if stack.entries.len() > 1 {
7698 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
7699 } else {
7700 0.0
7701 };
7702 let cost_new = luma_new.sse
7703 + u_new.sse
7704 + v_new.sse
7705 + search.lambda
7706 * (skip_bits(skip_new)
7707 + intra_inter_bits(true)
7708 + single_ref_bits
7709 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7710 + drl_bits
7711 + mv_bits
7712 + mv_rate_surcharge(mv_bits)
7713 + if skip_new {
7714 0.0
7715 } else {
7716 luma_new.bits + u_new.bits + v_new.bits
7717 });
7718 newmv_census_block(
7719 side,
7720 true,
7721 cost_new,
7722 best.0,
7723 new_mv,
7724 stack.nearest_mv,
7725 mv_bits,
7726 );
7727 if cost_new < best.0 {
7728 single_syntax = intra_inter_bits(true)
7729 + single_ref_bits
7730 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7731 + drl_bits
7732 + mv_bits;
7733 best = (
7734 cost_new,
7735 Some((
7736 luma_new,
7737 u_new,
7738 v_new,
7739 skip_new,
7740 InterInfo {
7741 ref1: None,
7742 mv1: (0, 0),
7743 ref_frame: crate::mvstack::LAST_FRAME,
7744 mode: InterMode::NewMv,
7745 mv: new_mv,
7746 ref_mv_idx: 0,
7747 },
7748 )),
7749 );
7750 }
7751 }
7752 }
7753
7754 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
7755 // `search_inter_block` prices for a whole 32x32 block:
7756 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
7757 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
7758 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
7759 // too. Priced with the same static-CDF approximation, plus the
7760 // compound-only syntax the writer emits.
7761 if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() {
7762 // lane-arfmode: arm 4 drops this leaf's compound set (counted once
7763 // per leaf, not once per pair); the single-reference candidates
7764 // above stay.
7765 arfmode_hit(2);
7766 }
7767 for (ref1, g, cstack) in compound
7768 .iter()
7769 .filter(|_| leaf_compound() && search.arf_leaf_compound)
7770 {
7771 let (ref1, g) = (*ref1, *g);
7772 // The whole `comp_mode` + reference-pair tree at the writer's own
7773 // contexts, for THIS pair (lane-ctx).
7774 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
7775 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7776 let mode_bits_of =
7777 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7778 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7779 (
7780 cstack.nearest_mv,
7781 mode_bits_of(0),
7782 InterInfo {
7783 ref_frame: crate::mvstack::LAST_FRAME,
7784 mode: InterMode::NearestNearestMv,
7785 mv: cstack.nearest_mv.0,
7786 mv1: cstack.nearest_mv.1,
7787 ref1: Some(ref1),
7788 ref_mv_idx: 0,
7789 },
7790 ),
7791 (
7792 ((0, 0), (0, 0)),
7793 mode_bits_of(6),
7794 InterInfo {
7795 ref_frame: crate::mvstack::LAST_FRAME,
7796 mode: InterMode::GlobalGlobalMv,
7797 mv: (0, 0),
7798 mv1: (0, 0),
7799 ref1: Some(ref1),
7800 ref_mv_idx: 0,
7801 },
7802 ),
7803 ];
7804 // Every compound MV residual here is priced against compound stack
7805 // entry 0, which is what `assign_compound_mv` predicts from at
7806 // `ref_mv_idx = 0` -- so it is also what the second-reference search
7807 // below seeds from and rounds to, and no candidate it finds can then
7808 // fail `mv_residual_bits`.
7809 let cbase = cstack
7810 .entries
7811 .first()
7812 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
7813 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
7814 // it a leaf could only name a stack vector for the second half, and
7815 // screen capture showed the consequence: every leaf compound block
7816 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
7817 // extra-reference `NEWMV`, when this reference's own
7818 // `NEAREST_NEARESTMV` vector already prices `margin` times better
7819 // than the `LAST` search of this same leaf did -- one candidate
7820 // evaluation standing in for a whole search.
7821 let margin = leaf_second_new_margin();
7822 let mut second_new: Option<(i32, i32)> = None;
7823 if leaf_second_new_mv() {
7824 newmv_census_global(2);
7825 let skip = margin > 0.0
7826 && searched_new_cost.is_some_and(|last| {
7827 motion::cost_at(
7828 &g.y,
7829 g.width,
7830 luma.true_width,
7831 luma.true_height,
7832 &source_block,
7833 x,
7834 y,
7835 side,
7836 side,
7837 cstack.nearest_mv.1,
7838 cbase.1,
7839 search.lambda,
7840 fctx,
7841 ) * margin
7842 <= last
7843 });
7844 if skip {
7845 newmv_census_global(3);
7846 }
7847 if !skip {
7848 let mut seeds = [(0, 0); 4];
7849 let mut seed_n = 1;
7850 for e in cstack.entries.iter().take(3) {
7851 seeds[seed_n] = e.mv1;
7852 seed_n += 1;
7853 }
7854 let found = motion::search(
7855 &g.y,
7856 g.width,
7857 luma.true_width,
7858 luma.true_height,
7859 &source_block,
7860 x,
7861 y,
7862 side,
7863 side,
7864 cbase.1,
7865 &seeds[..seed_n],
7866 search.lambda,
7867 fctx,
7868 ref_distance(ref1),
7869 );
7870 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
7871 }
7872 }
7873 if let Some(new_mv) = searched_new {
7874 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
7875 ccands.push((
7876 (new_mv, cstack.nearest_mv.1),
7877 mode_bits_of(3) + b0,
7878 InterInfo {
7879 ref_frame: crate::mvstack::LAST_FRAME,
7880 mode: InterMode::NewNearestMv,
7881 mv: new_mv,
7882 mv1: cstack.nearest_mv.1,
7883 ref1: Some(ref1),
7884 ref_mv_idx: 0,
7885 },
7886 ));
7887 }
7888 }
7889 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
7890 // searches this leaf ran, each residual priced against `cbase`.
7891 if let Some(mv1) = second_new {
7892 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
7893 ccands.push((
7894 (cstack.nearest_mv.0, mv1),
7895 mode_bits_of(2) + b1,
7896 InterInfo {
7897 ref_frame: crate::mvstack::LAST_FRAME,
7898 mode: InterMode::NearestNewMv,
7899 mv: cstack.nearest_mv.0,
7900 mv1,
7901 ref1: Some(ref1),
7902 ref_mv_idx: 0,
7903 },
7904 ));
7905 if let Some((new_mv, b0)) =
7906 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
7907 {
7908 ccands.push((
7909 (new_mv, mv1),
7910 mode_bits_of(7) + b0 + b1,
7911 InterInfo {
7912 ref_frame: crate::mvstack::LAST_FRAME,
7913 mode: InterMode::NewNewMv,
7914 mv: new_mv,
7915 mv1,
7916 ref1: Some(ref1),
7917 ref_mv_idx: 0,
7918 },
7919 ));
7920 }
7921 }
7922 }
7923 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
7924 ccands.dedup_by_key(|c| c.0);
7925 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
7926 let g_u = (
7927 g.u.as_slice(),
7928 g.width / 2,
7929 chroma[0].true_width,
7930 chroma[0].true_height,
7931 );
7932 let g_v = (
7933 g.v.as_slice(),
7934 g.width / 2,
7935 chroma[1].true_width,
7936 chroma[1].true_height,
7937 );
7938 for (mvs, bits, info) in ccands {
7939 let luma_c = mc_trial_compound(
7940 luma,
7941 x,
7942 y,
7943 side,
7944 mvs,
7945 true,
7946 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7947 g_luma,
7948 search.base_q_idx,
7949 search.deadzone,
7950 luma_set,
7951 fctx,
7952 );
7953 let u_c = mc_trial_compound(
7954 &chroma[0],
7955 x / 2,
7956 y / 2,
7957 side / 2,
7958 mvs,
7959 false,
7960 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7961 g_u,
7962 search.base_q_idx,
7963 search.deadzone,
7964 chroma_set,
7965 fctx,
7966 );
7967 let v_c = mc_trial_compound(
7968 &chroma[1],
7969 x / 2,
7970 y / 2,
7971 side / 2,
7972 mvs,
7973 false,
7974 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7975 g_v,
7976 search.base_q_idx,
7977 search.deadzone,
7978 chroma_set,
7979 fctx,
7980 );
7981 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
7982 && u_c.levels.iter().all(|&l| l == 0)
7983 && v_c.levels.iter().all(|&l| l == 0);
7984 let cost_c = luma_c.sse
7985 + u_c.sse
7986 + v_c.sse
7987 + search.lambda
7988 * (skip_bits(skip_c)
7989 + intra_inter_bits(true)
7990 + bits
7991 + if skip_c {
7992 0.0
7993 } else {
7994 luma_c.bits + u_c.bits + v_c.bits
7995 });
7996 if cost_c < best.0 {
7997 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
7998 }
7999 }
8000 }
8001
8002 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
8003 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
8004 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
8005 // the writer codes no symbol for one. The prediction is the decoder's own
8006 // plan and blend over the neighbours this leaf's `grid` already carries
8007 // (published by `record_mi` in the writer's coding order), so the
8008 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
8009 // offered this only at 32x32, which is not where libaom cashes its OBMC
8010 // gain.
8011 let mut motion_won = 0u8;
8012 let single = match &best.1 {
8013 None => Some(nearest_info),
8014 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
8015 Some(_) => None,
8016 };
8017 if let Some(info) = single.filter(|i| {
8018 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
8019 && i.ref_frame == crate::mvstack::LAST_FRAME
8020 }) {
8021 let planes = [
8022 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8023 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
8024 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
8025 ];
8026 // Which alphabet this block's writer will code the symbol against
8027 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
8028 // 3-symbol one only under `allow_warped_motion` and at least one warp
8029 // sample. Mirrored here so the candidates are priced against the
8030 // table the tile really narrows.
8031 let warp_alphabet = warp_on()
8032 && crate::decode::num_proj_ref(
8033 grid,
8034 mi_row,
8035 mi_col,
8036 side / 4,
8037 side / 4,
8038 mi_cols,
8039 mi_rows,
8040 info.ref_frame,
8041 fctx,
8042 ) >= 1;
8043 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
8044 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
8045 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
8046 if let Some(pred) = obmc_prediction(
8047 grid,
8048 (mi_row, mi_col),
8049 (mi_rows, mi_cols),
8050 (x, y),
8051 side,
8052 info.mv,
8053 refs,
8054 planes,
8055 reference.width,
8056 fctx,
8057 ) {
8058 candidates.push((1, pred));
8059 }
8060 }
8061 if warp_alphabet {
8062 if let Some(pred) = warp_prediction(
8063 grid,
8064 (mi_row, mi_col),
8065 (mi_rows, mi_cols),
8066 (x, y),
8067 side,
8068 info.mv,
8069 info.ref_frame,
8070 planes,
8071 fctx,
8072 ) {
8073 candidates.push((2, pred));
8074 }
8075 }
8076 for (motion, pred) in candidates {
8077 let luma_o = luma.code_from_prediction(
8078 x,
8079 y,
8080 side,
8081 &pred[0],
8082 false,
8083 search.base_q_idx,
8084 search.deadzone,
8085 luma_set,
8086 );
8087 let u_o = chroma[0].code_from_prediction(
8088 x / 2,
8089 y / 2,
8090 side / 2,
8091 &pred[1],
8092 false,
8093 search.base_q_idx,
8094 search.deadzone,
8095 chroma_set,
8096 );
8097 let v_o = chroma[1].code_from_prediction(
8098 x / 2,
8099 y / 2,
8100 side / 2,
8101 &pred[2],
8102 false,
8103 search.base_q_idx,
8104 search.deadzone,
8105 chroma_set,
8106 );
8107 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
8108 && u_o.levels.iter().all(|&l| l == 0)
8109 && v_o.levels.iter().all(|&l| l == 0);
8110 let cost_o = luma_o.sse
8111 + u_o.sse
8112 + v_o.sse
8113 + search.lambda
8114 * (skip_bits(skip_o)
8115 + single_syntax
8116 + mm(motion)
8117 + if skip_o {
8118 0.0
8119 } else {
8120 luma_o.bits + u_o.bits + v_o.bits
8121 });
8122 // The incumbent pays the motion_mode symbol IT would code, so
8123 // both sides of the comparison carry that syntax.
8124 if cost_o < best.0 + search.lambda * mm(motion_won) {
8125 motion_won = motion;
8126 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
8127 }
8128 }
8129 }
8130
8131 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
8132 if cost < intra_cost {
8133 // A compound winner commits the flat trial it was priced from:
8134 // `commit_inter_luma`'s var-tx trial set is single-reference
8135 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
8136 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
8137 // predicting each half-side trial from BOTH references, verified
8138 // byte-identical to this when its split is disabled) and MEASURED
8139 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
8140 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
8141 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
8142 // compound block's residual is small enough that the four extra
8143 // per-unit txb_skip/eob symbols cost more ladder bytes than this
8144 // encoder's static-CDF estimate prices them at, so the local RD
8145 // win does not convert. lane-av1txbits REBUILT it on top of a
8146 // search that prices against the tables the frame is really
8147 // written with (`tile::arm_pricing_cdfs`, the estimate error on
8148 // these very blocks measured down from +31% to +3%) and measured
8149 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
8150 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
8151 // same build without it. The static-CDF estimate was NOT what
8152 // held the compound var-tx trial back. The flat trial stays.
8153 // An OBMC winner commits the flat trial too: `commit_inter_luma`
8154 // re-predicts each var-tx unit by plain translation, which is not
8155 // the prediction this candidate was priced from.
8156 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
8157 // 0.05 (both rejections above were measured at 0.1, the weight
8158 // the lambda lane showed was 2x too heavy): a compound winner is
8159 // offered the same var-tx split, its units predicted from BOTH
8160 // references (`mc_trial_compound`). RE-MEASURED native: film
8161 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
8162 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
8163 // one row 0.2 down, two flat, short of the two-down-one-flat keep
8164 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
8165 // rather than change the default on a single 0.2 row. It fires:
8166 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
8167 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
8168 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
8169 // 1.3/1.2 down there, which is where the upgrade path is if this
8170 // is picked up again.
8171 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
8172 refs[r as usize].map(|g| {
8173 (
8174 info.mv1,
8175 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
8176 )
8177 })
8178 });
8179 let (levels, tx_depth, dcost, luma_tx_types) =
8180 if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {
8181 luma.commit(x, y, side, &luma_new);
8182 (luma_new.levels.clone(), 0, 0.0, Vec::new())
8183 } else {
8184 commit_inter_luma(
8185 luma,
8186 (x, y),
8187 side,
8188 info.mv,
8189 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8190 search,
8191 &luma_new,
8192 skip_new,
8193 second,
8194 fctx,
8195 )
8196 };
8197 // lane-txrd: chroma follows the luma type the search just chose.
8198 let [u_new, v_new] = match luma_tx_types.first().copied() {
8199 Some(t) => recode_inter_chroma(
8200 chroma,
8201 (x, y),
8202 side,
8203 info.mv,
8204 [
8205 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
8206 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
8207 ],
8208 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
8209 refs[r as usize].map(|g| {
8210 (
8211 info.mv1,
8212 [
8213 (
8214 g.u.as_slice(),
8215 g.width / 2,
8216 chroma[0].true_width,
8217 chroma[0].true_height,
8218 ),
8219 (
8220 g.v.as_slice(),
8221 g.width / 2,
8222 chroma[1].true_width,
8223 chroma[1].true_height,
8224 ),
8225 ],
8226 )
8227 })
8228 }),
8229 search,
8230 chroma_set,
8231 t,
8232 fctx,
8233 )
8234 .unwrap_or([u_new, v_new]),
8235 None => [u_new, v_new],
8236 };
8237 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
8238 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
8239 return (
8240 BlockCoeffs {
8241 angle_delta_y: 0,
8242 cfl_alphas: None,
8243 filter_intra: None,
8244 luma: coeffs(&levels, side),
8245 u: coeffs(&u_new.levels, side / 2),
8246 v: coeffs(&v_new.levels, side / 2),
8247 mode: DC_PRED as u8,
8248 uv_mode: DC_PRED,
8249 skip: skip_new,
8250 eight: None,
8251 dv: None,
8252 palette: None,
8253 palette_uv: None,
8254 tx_depth,
8255 luma_tx_types,
8256 inter: Some(info),
8257 motion_mode: motion_won,
8258 },
8259 cost + dcost,
8260 );
8261 }
8262 }
8263
8264 census_add(8, 1);
8265 if skip {
8266 census_add(10, 1);
8267 }
8268 if inter_cost >= intra_cost {
8269 census_add(9, 1);
8270 }
8271 if inter_cost < intra_cost {
8272 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
8273 luma,
8274 (x, y),
8275 side,
8276 mv,
8277 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8278 search,
8279 &luma_trial,
8280 skip,
8281 None,
8282 fctx,
8283 );
8284 // lane-txrd: chroma follows the luma type (this tail's block is
8285 // single-reference `NEARESTMV`, so no compound second half).
8286 let [u, v] = match luma_tx_types.first().copied() {
8287 Some(t) => recode_inter_chroma(
8288 chroma,
8289 (x, y),
8290 side,
8291 mv,
8292 [
8293 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
8294 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
8295 ],
8296 None,
8297 search,
8298 chroma_set,
8299 t,
8300 fctx,
8301 )
8302 .unwrap_or([u, v]),
8303 None => [u, v],
8304 };
8305 chroma[0].commit(x / 2, y / 2, side / 2, &u);
8306 chroma[1].commit(x / 2, y / 2, side / 2, &v);
8307 (
8308 BlockCoeffs {
8309 luma_tx_types,
8310 angle_delta_y: 0,
8311 cfl_alphas: None,
8312 filter_intra: None,
8313 luma: coeffs(&levels, side),
8314 u: coeffs(&u.levels, side / 2),
8315 v: coeffs(&v.levels, side / 2),
8316 mode: DC_PRED as u8,
8317 uv_mode: DC_PRED,
8318 skip,
8319 eight: None,
8320 dv: None,
8321 palette: None,
8322 palette_uv: None,
8323 tx_depth,
8324 motion_mode: 0,
8325 inter: Some(InterInfo {
8326 ref1: None,
8327 mv1: (0, 0),
8328 ref_frame: crate::mvstack::LAST_FRAME,
8329 mode: InterMode::NearestMv,
8330 mv,
8331 ref_mv_idx: 0,
8332 }),
8333 },
8334 inter_cost + dcost,
8335 )
8336 } else {
8337 (intra_block, intra_cost)
8338 }
8339}
8340
8341/// Publishes one coded inter-frame block into the `mi` grid the next block's
8342/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
8343/// block casts no vote but is still a coded cell (see `code_square_inter`'s
8344/// note on `processed_rows`/`processed_cols`).
8345fn record_mi(
8346 grid: &mut MiGrid,
8347 mi_row: usize,
8348 mi_col: usize,
8349 size: u8,
8350 inter: Option<InterInfo>,
8351 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
8352 // the RD pricer the two cells the writer's `skip_ctx` sums.
8353 skip: bool,
8354) {
8355 let info = match inter {
8356 Some(info) => MiInfo {
8357 is_inter: true,
8358 ref_frame: info.ref_frame,
8359 // A COMPOUND block votes with BOTH of its references and both of
8360 // its vectors, exactly as the tile writer publishes it: recording
8361 // a compound block as a single-reference one here left the
8362 // encoder's own grid disagreeing with the writer's from the first
8363 // compound block on, so every later stack it searched against was
8364 // not the stack the decoder derives.
8365 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8366 mv1: mv16(info.mv1),
8367 mv: mv16(info.mv),
8368 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
8369 // side, compound modes 2/3/7 on the other.
8370 is_new_mv: matches!(
8371 info.mode,
8372 InterMode::NewMv
8373 | InterMode::NewNewMv
8374 | InterMode::NearestNewMv
8375 | InterMode::NewNearestMv
8376 ),
8377 size,
8378 size_h: size,
8379 is_global_mv0: false,
8380 is_global_mv1: false,
8381 },
8382 None => MiInfo {
8383 is_inter: false,
8384 ref_frame: -1,
8385 ref_frame1: NO_REF1,
8386 mv1: (0, 0),
8387 mv: (0, 0),
8388 is_new_mv: false,
8389 size,
8390 size_h: size,
8391 is_global_mv0: false,
8392 is_global_mv1: false,
8393 },
8394 };
8395 for dr in 0..usize::from(size) {
8396 for dc in 0..usize::from(size) {
8397 grid.set(mi_row + dr, mi_col + dc, info);
8398 grid.set_skip(mi_row + dr, mi_col + dc, skip);
8399 }
8400 }
8401}
8402
8403/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
8404/// writer's own `write_inter_block_128_rect` makes, so the second half of a
8405/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
8406fn record_mi_rect(
8407 grid: &mut MiGrid,
8408 mi_row: usize,
8409 mi_col: usize,
8410 (w_mi, h_mi): (usize, usize),
8411 inter: Option<InterInfo>,
8412 skip: bool,
8413) {
8414 record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
8415 // `record_mi` stamped the square corner; widen it to the true footprint,
8416 // with the block's own (rect) size fields.
8417 let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
8418 info.size = w_mi as u8;
8419 info.size_h = h_mi as u8;
8420 for dr in 0..h_mi {
8421 for dc in 0..w_mi {
8422 grid.set(mi_row + dr, mi_col + dc, info);
8423 grid.set_skip(mi_row + dr, mi_col + dc, skip);
8424 }
8425 }
8426}
8427
8428/// The reconstructed samples one 32x32 square covers in all three planes, so
8429/// that a partition trial can be undone.
8430/// One square of a plane, row-major, the inverse of [`Plane::restore`].
8431///
8432/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
8433/// which allocated and freed a `Vec` per row of every block it copied --
8434/// `Plane::snapshot` runs once per partition trial.
8435fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
8436 let mut out = vec![0u8; side * side];
8437 for row in 0..side {
8438 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
8439 }
8440 out
8441}
8442
8443fn snapshot(
8444 luma: &Plane,
8445 chroma: &[Plane; 2],
8446 (x, y): (usize, usize),
8447 side: usize,
8448) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
8449 [
8450 luma.snapshot(x, y, side),
8451 chroma[0].snapshot(x / 2, y / 2, side / 2),
8452 chroma[1].snapshot(x / 2, y / 2, side / 2),
8453 ]
8454}
8455
8456/// Puts such a snapshot back.
8457fn restore(
8458 luma: &mut Plane,
8459 chroma: &mut [Plane; 2],
8460 (x, y): (usize, usize),
8461 side: usize,
8462 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
8463) {
8464 luma.restore(x, y, side, &saved[0]);
8465 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
8466 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
8467}
8468
8469/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
8470/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
8471/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
8472/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
8473/// rule shared with the key-frame path, not a second one that could diverge.
8474fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
8475 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
8476 let dc_entry = dc_pos.map(|i| scored.remove(i));
8477 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
8478 scored.truncate(if dc_entry.is_some() {
8479 top_k.saturating_sub(1)
8480 } else {
8481 top_k
8482 });
8483 if let Some(dc_entry) = dc_entry {
8484 scored.push(dc_entry);
8485 }
8486 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
8487 modes.iter().copied().filter(|m| keep.contains(m)).collect()
8488}
8489
8490fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
8491 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
8492 [INTRA_MODE_CTX[usize::from(left_mode)]];
8493 std::array::from_fn(|mode| {
8494 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
8495 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
8496 } else {
8497 0.0
8498 };
8499 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
8500 })
8501}
8502
8503/// What the luma mode search picks between, and under what terms.
8504#[derive(Clone, Copy)]
8505struct Search<'a> {
8506 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
8507 /// luma search then offers a palette candidate beside the intra modes.
8508 screen: bool,
8509 base_q_idx: u8,
8510 deadzone: f64,
8511 lambda: f64,
8512 modes: &'a [u8],
8513 /// How many of `modes` the full RD trial (forward transform, quantize,
8514 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
8515 /// pre-pass on the prediction residual alone plus DC (always kept, since
8516 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
8517 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
8518 /// mode through full RD, unchanged from before this lever.
8519 top_k: Option<usize>,
8520 /// lane-arfmode: the top ARF's offer set ([`crate::speed::ARFMODE`])
8521 /// -- `false` cuts the named candidate group from the whole-32 search
8522 /// ([`search_inter_block`]), the 16x16/8x8 leaf search
8523 /// ([`code_square_inter`]) and the 8x8 split offer, at the top ARF
8524 /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is
8525 /// the pre-lane behaviour: the mid and quarter hidden frames, the shown
8526 /// leaves and the flat path keep intra and compound, and the
8527 /// straddling-edge 8x8s are only mode-gated, never partition-gated.
8528 /// The probe's correction: with the leaf gate ALONE the film A stream
8529 /// was byte-identical to the control -- the ARF's intra area lives at
8530 /// the whole-32 level, so the intra arm must cut it there too.
8531 arf_leaf_intra: bool,
8532 arf_leaf8: bool,
8533 arf_leaf_compound: bool,
8534}
8535
8536/// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what
8537/// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the
8538/// shipped table -- 0, bit-exact with the pre-lane encoder).
8539fn arfmode() -> u8 {
8540 match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
8541 u8::MAX => {}
8542 n => return n,
8543 }
8544 static ENV: std::sync::LazyLock<Option<u8>> = std::sync::LazyLock::new(|| {
8545 crate::envflags::var("EC_AV1_ARFMODE")
8546 .ok()
8547 .and_then(|v| v.parse().ok())
8548 });
8549 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE))
8550}
8551
8552/// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.
8553static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
8554
8555/// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
8556/// process constant ([`crate::envflags`]), so an in-process witness needs
8557/// this to arm the lever.
8558#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
8559pub(crate) fn set_arfmode(n: Option<u8>) {
8560 ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed);
8561}
8562
8563/// How often each armed [`crate::speed::ARFMODE`] arm actually fired since
8564/// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded
8565/// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8
8566/// split the search would have offered and the arm refused, 2 = a top-ARF
8567/// leaf whose compound set was dropped. A green gate over counts of zero
8568/// proves nothing about the lever.
8569static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [
8570 std::sync::atomic::AtomicUsize::new(0),
8571 std::sync::atomic::AtomicUsize::new(0),
8572 std::sync::atomic::AtomicUsize::new(0),
8573];
8574
8575/// Records one such hit.
8576fn arfmode_hit(which: usize) {
8577 ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8578}
8579
8580/// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer
8581/// condition, so the counter only runs when every other prune let the split
8582/// through and the arm alone refuses it.
8583fn arfmode_hit_and_no() -> bool {
8584 arfmode_hit(1);
8585 false
8586}
8587
8588/// Takes (and clears) the counts. `pub` for `examples/enc_probe`, so a
8589/// probe point can print a non-zero engagement count under the env knob
8590/// itself -- the counter the gate BD numbers are read against.
8591pub fn take_arfmode_hits() -> [usize; 3] {
8592 [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
8593}
8594
8595fn prune_top_k() -> Option<usize> {
8596 #[cfg(test)]
8597 {
8598 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
8599 return k;
8600 }
8601 }
8602 let swept = std::env::var("EC_AV1_PRUNE_K")
8603 .ok()
8604 .and_then(|v| v.parse::<usize>().ok());
8605 match swept {
8606 Some(k) if cfg!(test) => Some(k),
8607 _ => crate::speed::at(&crate::speed::PRUNE_K),
8608 }
8609}
8610
8611// A per-thread override [`prune_top_k`] checks first, so one test can sweep
8612// `top_k` in-process without mutating the environment (forbidden here --
8613// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
8614#[cfg(test)]
8615thread_local! {
8616 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
8617 const { std::cell::Cell::new(None) };
8618}
8619
8620#[cfg(test)]
8621fn set_test_top_k_override(value: Option<usize>) {
8622 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
8623}
8624
8625/// The default: unpruned, thirteen full trials per block, same as before this
8626/// lever. Set from the sweep in the lane report if the quality gate clears it.
8627pub(crate) const PRUNE_TOP_K: Option<usize> = None;
8628
8629/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
8630/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
8631/// quality gates were measured separately and may land on different
8632/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
8633/// [`EC_AV1_PRUNE_K`] or the key-frame path.
8634fn prune_top_k_inter() -> Option<usize> {
8635 #[cfg(test)]
8636 {
8637 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
8638 return k;
8639 }
8640 }
8641 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
8642 .ok()
8643 .and_then(|v| v.parse::<usize>().ok());
8644 match swept {
8645 Some(k) if cfg!(test) => Some(k),
8646 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
8647 }
8648}
8649
8650// A per-thread override [`prune_top_k_inter`] checks first, same reason as
8651// [`TEST_TOP_K_OVERRIDE`].
8652#[cfg(test)]
8653thread_local! {
8654 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
8655 const { std::cell::Cell::new(None) };
8656}
8657
8658#[cfg(test)]
8659fn set_test_top_k_override_inter(value: Option<usize>) {
8660 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
8661}
8662
8663/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
8664/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
8665/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
8666/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
8667/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
8668/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
8669/// pruning them costs less quality here.
8670pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
8671
8672// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
8673// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
8674// inter frame's cost can be attributed to a bucket without changing what
8675// the search actually does. Index: 0 = whole-call time inside
8676// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
8677// [`crate::mc::predict`] (every call, from the motion search's own
8678// candidates and from a committed inter block's final prediction alike),
8679// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
8680#[cfg(test)]
8681thread_local! {
8682 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
8683 std::cell::Cell::new(0),
8684 std::cell::Cell::new(0),
8685 std::cell::Cell::new(0),
8686 std::cell::Cell::new(0),
8687 ];
8688}
8689
8690/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
8691/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
8692/// per transform trial and per `mc::predict` call whether or not anyone was
8693/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
8694/// The clock is now read only when [`crate::par::stage_times`] is on, which
8695/// is what prints the breakdown in the first place.
8696#[cfg(test)]
8697pub(crate) fn stage_start() -> Option<std::time::Instant> {
8698 crate::par::stage_times().then(std::time::Instant::now)
8699}
8700
8701#[cfg(test)]
8702pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
8703 if let Some(t) = t {
8704 stage_add(bucket, t.elapsed());
8705 }
8706}
8707
8708#[cfg(test)]
8709pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
8710 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
8711}
8712
8713#[cfg(test)]
8714fn stage_reset() {
8715 crate::par::set_stage_times(true);
8716 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
8717}
8718
8719#[cfg(test)]
8720fn stage_read() -> [std::time::Duration; 4] {
8721 crate::par::set_stage_times(false);
8722 STAGE_NS.with(|c| {
8723 c.each_ref()
8724 .map(|cell| std::time::Duration::from_nanos(cell.get()))
8725 })
8726}
8727
8728/// One mode's coding of one block, before it is committed.
8729#[derive(Clone)]
8730struct Trial {
8731 levels: Vec<i32>,
8732 reconstruction: Vec<u8>,
8733 sse: f64,
8734 bits: f64,
8735}
8736
8737/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
8738/// of a 64-point transform that is actually coded (everything outside it is
8739/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
8740fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
8741 let mut out = vec![0i32; to * to];
8742 for row in 0..to {
8743 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
8744 }
8745 out
8746}
8747
8748/// The non-zero levels of a block, as the tile writer takes them.
8749fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
8750 levels
8751 .iter()
8752 .enumerate()
8753 .filter(|&(_, &level)| level != 0)
8754 .map(|(i, &level)| Coeff {
8755 row: (i / side) as u8,
8756 col: (i % side) as u8,
8757 level,
8758 })
8759 .collect()
8760}
8761
8762thread_local! {
8763 /// The tile grid the next frame is coded with, as `(TileColsLog2,
8764 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
8765 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
8766 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
8767 /// one tile per frame, what every caller that never arms anything gets
8768 /// and what every stream this crate wrote before tiles existed carries.
8769 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
8770}
8771
8772/// Arms this thread's next frame encodes with a tile grid (log2 counts).
8773pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
8774 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
8775}
8776
8777fn armed_tiles() -> (u32, u32) {
8778 let armed = TILE_LOG2.with(std::cell::Cell::get);
8779 if armed != (0, 0) {
8780 return armed;
8781 }
8782 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
8783 // (which codes through `encode_sequence`, not the facade) can measure what
8784 // a tile grid costs without a knob of its own -- same shape as
8785 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
8786 match std::env::var("EC_AV1_TILES").ok() {
8787 Some(v) if cfg!(test) => {
8788 let mut f = v.split(':');
8789 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
8790 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
8791 (cols, rows)
8792 }
8793 _ => armed,
8794 }
8795}
8796
8797/// Codes a frame's `tiles` tiles, each entirely on its own (see
8798/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
8799/// the crate's own pool, and hands back their payloads in tile order plus
8800/// whatever `code` returned for tile `store` -- the CDF state
8801/// `context_update_tile_id` names. The result cannot depend on the thread
8802/// count: each job writes one tile from the frame's own starting tables into
8803/// its own slot.
8804fn write_tiles<F>(
8805 tiles: usize,
8806 store: usize,
8807 code: F,
8808) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
8809where
8810 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
8811{
8812 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
8813 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
8814 let threads = crate::par::tile_threads().min(tiles);
8815 let mut slots: Vec<Slot> = Vec::new();
8816 if threads <= 1 {
8817 for index in 0..tiles {
8818 slots.push(Some(code(index)));
8819 }
8820 } else {
8821 let done: std::sync::Mutex<Vec<Slot>> =
8822 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8823 {
8824 let batch = crate::par::Batch::new("ec-av1-tile");
8825 for (from, to) in crate::par::bands(tiles, threads) {
8826 let done = &done;
8827 let code = &code;
8828 batch.submit(move || {
8829 for index in from..to {
8830 let coded = code(index);
8831 done.lock().expect("tile slots")[index] = Some(coded);
8832 }
8833 });
8834 }
8835 }
8836 slots = done.into_inner().expect("tile slots");
8837 }
8838 let mut out = Vec::with_capacity(tiles);
8839 let mut stored = None;
8840 for (index, slot) in slots.into_iter().enumerate() {
8841 let (bytes, cdfs) = slot.expect("every tile was coded")?;
8842 if index == store {
8843 stored = cdfs;
8844 }
8845 out.push(bytes);
8846 }
8847 Ok((out, stored))
8848}
8849
8850/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
8851/// workers, and returns the results in tile order. The counterpart of
8852/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
8853/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
8854/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
8855/// availability is already tile-relative (`clip_planes_to_tile`,
8856/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
8857/// other tiles have run -- gated by
8858/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
8859/// covers the search as well as the write.
8860///
8861/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
8862/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
8863/// does it for the decoder's filter bands.
8864fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
8865where
8866 T: Send,
8867 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
8868{
8869 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
8870 let threads = crate::par::tile_threads().min(tiles);
8871 if threads <= 1 {
8872 return (0..tiles).map(|index| job(index, fctx)).collect();
8873 }
8874 type Slot<T> = Option<Result<T>>;
8875 let done: std::sync::Mutex<Vec<Slot<T>>> =
8876 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8877 {
8878 let batch = crate::par::Batch::new("ec-av1-tile-search");
8879 for (from, to) in crate::par::bands(tiles, threads) {
8880 let done = &done;
8881 let job = &job;
8882 let ctx = crate::decode::filter_ctx_copy(fctx);
8883 batch.submit(move || {
8884 for index in from..to {
8885 let searched = job(index, &ctx);
8886 done.lock().expect("tile slots")[index] = Some(searched);
8887 }
8888 });
8889 }
8890 }
8891 done.into_inner()
8892 .expect("tile slots")
8893 .into_iter()
8894 .map(|slot| slot.expect("every tile was searched"))
8895 .collect()
8896}
8897
8898/// One tile job's own copy of a plane: the frame's source, a blank
8899/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
8900/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
8901/// of the frame's reconstruction because a tile's prediction never reads a
8902/// sample outside its own rectangle, and every sample inside it is written
8903/// before it is read.
8904fn fresh_plane(
8905 source: &[u8],
8906 width: usize,
8907 height: usize,
8908 true_width: usize,
8909 true_height: usize,
8910) -> Plane<'_> {
8911 Plane {
8912 source,
8913 reconstruction: vec![128; source.len()],
8914 width,
8915 height,
8916 true_width,
8917 true_height,
8918 tile_x0: 0,
8919 tile_y0: 0,
8920 tile_x1: width,
8921 tile_y1: height,
8922 ctx: CoefCtxMap::default(),
8923 }
8924}
8925
8926/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
8927/// the frame's plane, through the [`crate::par::Shared`] every job holds.
8928///
8929/// corner-cut: the disjointness that makes the aliasing sound is the caller's
8930/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
8931/// rectangles partition it -- checked end-to-end by
8932/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
8933/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
8934/// row-range `split_at_mut` plumbing through `Plane`, which would have to
8935/// thread an origin offset through every prediction and transform call site
8936/// for the same bytes.
8937#[allow(unsafe_code)]
8938fn copy_rect(
8939 dst: crate::par::Shared<'_, Vec<u8>>,
8940 src: &[u8],
8941 stride: usize,
8942 x0: usize,
8943 y0: usize,
8944 x1: usize,
8945 y1: usize,
8946) {
8947 // SAFETY: this job touches only its own tile rectangle (see above).
8948 let dst = unsafe { dst.get() };
8949 for y in y0..y1 {
8950 let (a, b) = (y * stride + x0, y * stride + x1);
8951 dst[a..b].copy_from_slice(&src[a..b]);
8952 }
8953}
8954
8955/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
8956/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
8957/// tables the frame stores (spec 7.20), which is what
8958/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
8959/// below publish.
8960fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
8961 ec_av1_syntax::TileInfo {
8962 uniform_spacing: true,
8963 cols: layout.cols(),
8964 rows: layout.rows(),
8965 cols_log2: layout.cols_log2,
8966 rows_log2: layout.rows_log2,
8967 mi_col_starts: layout.mi_col_starts(),
8968 mi_row_starts: layout.mi_row_starts(),
8969 context_update_tile_id: layout.largest_tile() as u32,
8970 tile_size_bytes,
8971 }
8972}
8973
8974/// Clips the three planes' intra edge reads to `rect`, the tile the
8975/// superblock about to be searched belongs to (the encoder side of the
8976/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
8977/// raster order -- which is a linear extension of every tile's own coding
8978/// order, so a block still only ever predicts from samples already
8979/// reconstructed -- and only availability is tile-relative.
8980fn clip_planes_to_tile(
8981 luma: &mut Plane<'_>,
8982 chroma: &mut [Plane<'_>; 2],
8983 rect: crate::tile::TileRect,
8984) {
8985 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8986 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8987 luma.set_tile(x0, y0, x1, y1);
8988 for plane in chroma.iter_mut() {
8989 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
8990 }
8991}
8992
8993/// Encodes one picture as a key frame.
8994///
8995/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
8996/// picks its coefficient CDFs from one of four q contexts by that index.
8997/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
8998/// smaller values trade fidelity for rate.
8999///
9000/// The picture may be any even width and height: the encoder pads it by edge
9001/// replication to a whole number of 32x32 blocks internally, and the frame it
9002/// writes crops back to the picture's own size (`render_width`/
9003/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
9004/// own size, never the padded one.
9005///
9006/// # Errors
9007/// Returns an error when the picture's width or height is zero or odd, or
9008/// when its planes are not 4:2:0 of that size.
9009/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
9010/// stream. The per-frame decode state this needs lives for exactly this call.
9011///
9012/// # Errors
9013/// Returns an error under the same conditions
9014/// [`encode_key_frame_with_modes`] does.
9015pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
9016 encode_key_frame_with_ctx(
9017 picture,
9018 base_q_idx,
9019 deadzone,
9020 &crate::decode::FrameCtx::for_encoder(),
9021 )
9022}
9023
9024/// [`encode_key_frame`] with the per-block intra modes given rather than
9025/// searched.
9026///
9027/// # Errors
9028/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
9029/// is empty, or when a block's coefficients do not fit the coded frame.
9030pub fn encode_key_frame_with_modes(
9031 picture: &Picture,
9032 base_q_idx: u8,
9033 deadzone: f64,
9034 modes: &[u8],
9035) -> Result<Encoded> {
9036 encode_key_frame_with_modes_with_ctx(
9037 picture,
9038 base_q_idx,
9039 deadzone,
9040 modes,
9041 &crate::decode::FrameCtx::for_encoder(),
9042 )
9043}
9044
9045/// Codes `pictures` as one key frame followed by inter frames.
9046///
9047/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
9048/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
9049/// `show_existing_frame` header, so `stream` is in CODING order while
9050/// `frames` stays in display order (`EncodedSequence::coding_order` is the
9051/// map). Screen content codes flat, decided once per sequence by the same
9052/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
9053/// puts every stream back on the flat path for an A/B.
9054///
9055/// # Errors
9056/// Returns an error under the same conditions [`encode_key_frame`] and the
9057/// inter frame path do.
9058pub fn encode_sequence(
9059 pictures: &[Picture],
9060 base_q_idx: u8,
9061 deadzone: f64,
9062) -> Result<EncodedSequence> {
9063 encode_sequence_with_ctx(
9064 pictures,
9065 base_q_idx,
9066 deadzone,
9067 &crate::decode::FrameCtx::for_encoder(),
9068 )
9069}
9070
9071/// Codes one padded picture as a key frame whose HEADER declares
9072/// `frame_width` x `frame_height` -- a frame size the picture's own
9073/// `width`/`height` need not be, and in particular need not be even.
9074///
9075/// [`encode_key_frame`] derives the declared size from the picture and
9076/// refuses an odd one, which is a property of a 4:2:0 SOURCE (an odd luma
9077/// column has no chroma sample of its own to be fed), not of the format: a
9078/// 65-wide 4:2:0 frame is a legal AV1 frame, with
9079/// `ROUND_POWER_OF_TWO(65, 1) = 33` chroma columns (libaom
9080/// `av1_common_plane_width` / `ROUND_POWER_OF_TWO`, `av1/common/
9081/// av1_common_int.h`), and aomenc never emits one only because it rounds the
9082/// coded size down to even before it looks at the picture
9083/// (`av1enc_set_frame_size`). This is the entry that can produce one, and it
9084/// is what the odd-luma coverage fixture is built with: the caller hands
9085/// over a picture already padded to the block grid and names the size to
9086/// declare, so the block walk codes exactly the `mi_cols`/`mi_rows` a
9087/// decoder derives from the declared size (spec `compute_image_size`).
9088///
9089/// # Errors
9090/// Returns an error when `picture` is not a whole number of 32x32 blocks
9091/// ([`Picture::check`]'s own rule), when either declared size is zero or
9092/// larger than the padded picture's, or when the mode search fails -- the
9093/// same conditions [`encode_key_frame`] reports for a malformed picture.
9094pub fn encode_key_frame_at_size(
9095 picture: &Picture,
9096 frame_width: usize,
9097 frame_height: usize,
9098 base_q_idx: u8,
9099 deadzone: f64,
9100) -> Result<Encoded> {
9101 picture.check()?;
9102 if frame_width == 0
9103 || frame_height == 0
9104 || frame_width > picture.width
9105 || frame_height > picture.height
9106 {
9107 return Err(Error::unsupported(
9108 "AV1 encode",
9109 "the declared frame size must be nonzero and fit inside the padded picture",
9110 ));
9111 }
9112 let encoded = encode_key_frame_inner(
9113 picture,
9114 base_q_idx,
9115 deadzone,
9116 &KEY_FRAME_MODES,
9117 split_blocks(),
9118 (frame_width, frame_height),
9119 unspecified_color_config(),
9120 &crate::decode::FrameCtx::for_encoder(),
9121 )?;
9122 Ok(crop_encoded(&encoded, frame_width, frame_height))
9123}
9124
9125pub(crate) fn encode_key_frame_with_ctx(
9126 picture: &Picture,
9127 base_q_idx: u8,
9128 deadzone: f64,
9129 fctx: &crate::decode::FrameCtx,
9130) -> Result<Encoded> {
9131 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
9132}
9133
9134/// Encodes one picture as a key frame, choosing each block's luma mode from
9135/// `modes` alone.
9136///
9137/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
9138/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
9139/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
9140/// uses.
9141///
9142/// # Errors
9143/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
9144/// names a mode [`crate::intra::predict`] does not predict.
9145pub(crate) fn encode_key_frame_with_modes_with_ctx(
9146 picture: &Picture,
9147 base_q_idx: u8,
9148 deadzone: f64,
9149 modes: &[u8],
9150 fctx: &crate::decode::FrameCtx,
9151) -> Result<Encoded> {
9152 picture.check_even()?;
9153 let padded = picture.padded_to(BLOCK);
9154 let encoded = encode_key_frame_inner(
9155 &padded,
9156 base_q_idx,
9157 deadzone,
9158 modes,
9159 split_blocks(),
9160 (picture.width, picture.height),
9161 unspecified_color_config(),
9162 fctx,
9163 )?;
9164 Ok(crop_encoded(&encoded, picture.width, picture.height))
9165}
9166
9167/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
9168/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
9169/// already padded to a whole number of 32x32 blocks; `render` is the real
9170/// (pre-pad) size the frame header tells a decoder to crop back to.
9171pub(crate) fn encode_key_frame_inner(
9172 picture: &Picture,
9173 base_q_idx: u8,
9174 deadzone: f64,
9175 modes: &[u8],
9176 split_blocks: bool,
9177 render: (usize, usize),
9178 color_config: ColorConfig,
9179 fctx: &crate::decode::FrameCtx,
9180) -> Result<Encoded> {
9181 // lane-refs: an intra frame runs no motion compensation, and the
9182 // context is shared across the sequence -- put the kernel back to the
9183 // default so nothing reads the previous inter frame's.
9184 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
9185 picture.check()?;
9186 if modes.is_empty() {
9187 return Err(Error::unsupported(
9188 "AV1 encode",
9189 "a mode search needs at least one mode to choose from",
9190 ));
9191 }
9192 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
9193 return Err(Error::unsupported(
9194 "AV1 encode",
9195 format!("intra mode {bad} is not one the encoder predicts"),
9196 ));
9197 }
9198 // The header carries the frame's true (unpadded) size as `frame_width`/
9199 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
9200 // `mi_rows` derived from that same true size (spec `compute_image_size`).
9201 // `render_width`/`render_height` come out equal to it too, so
9202 // `render_and_frame_size_different` is false and no render_size bits are
9203 // written, mirroring libaom/rav1e: the padded `picture` below is only the
9204 // internal coding surface, never what the header names.
9205 // Screen-content detection runs on the SOURCE luma, before any header is
9206 // built: it decides this sequence's `seq_force_screen_content_tools` (and
9207 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
9208 // this frame's own `allow_screen_content_tools`.
9209 let screen = screen_content(
9210 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
9211 picture.width,
9212 (picture.width).min(render.0),
9213 (picture.height).min(render.1),
9214 );
9215 arm_seq_screen(screen);
9216 // A key frame's writer really does start from the defaults, and a search
9217 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
9218 // disarm, or a key frame's bits would depend on which thread searched it.
9219 crate::tile::arm_pricing_cdfs(None, false);
9220 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
9221 // forces deblocking, CDEF and loop restoration OFF for this frame
9222 // (frame.rs:194/210/252/272), so it is only set when the source repeats
9223 // itself enough for the copied blocks to pay that back
9224 // ([`intrabc_worth_it`]).
9225 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
9226 // grid across every tile while this writer builds one per tile, so a
9227 // multi-tile allow_intrabc frame would predict its DVs off a different
9228 // grid than the decoder does. corner-cut, ceiling named: the upgrade
9229 // path is a frame-scoped grid shared by the tile writers.
9230 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
9231 intrabc_worth_it(
9232 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
9233 picture.width,
9234 picture.width.min(render.0),
9235 picture.height.min(render.1),
9236 )
9237 } else {
9238 (false, 0.0)
9239 };
9240 IBC_SHARE.with(|c| c.set(ibc_share));
9241 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
9242 header.allow_screen_content_tools = screen;
9243 // lane-txi: the wider `tx_type` alphabets, gated by the same content
9244 // rule the type search itself stands behind ([`wide_tx_set`]).
9245 header.reduced_tx_set = !wide_tx_set(screen);
9246 header.allow_intrabc = allow_intrabc;
9247 header.render_width = render.0 as u32;
9248 header.render_height = render.1 as u32;
9249 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
9250 // its luma transform below its own side (`crate::tile::write_luma_select`).
9251 // Set here rather than in `key_frame_headers_colour` so the header
9252 // builders' other callers -- the hand-built tile writers, which code no
9253 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
9254 let tx_select = tx_select();
9255 if tx_select {
9256 header.tx_mode = TxMode::Select;
9257 }
9258 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
9259
9260 // Prediction reads no further than this, in each plane's own units --
9261 // see `Plane::true_width`/`true_height`.
9262 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
9263 // lane-palw: the encoder's own in-process reconstruct reads its palette
9264 // colour-index maps back through `decode::palette_onscreen`, which takes
9265 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
9266 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
9267 // them here so the reconstruct clamps a block cut by the frame edge
9268 // exactly as the writer now does.
9269 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
9270 fctx.seg_mi_dims.set(frame_mi_dims);
9271 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
9272 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
9273 // design (see `intra_predict_u8`'s doc comment), so narrow the source
9274 // once here.
9275 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
9276 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
9277 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
9278 let mut luma = Plane {
9279 source: &picture_y8,
9280 reconstruction: vec![128; picture_y8.len()],
9281 width: picture.width,
9282 height: picture.height,
9283 true_width,
9284 true_height,
9285 tile_x0: 0,
9286 tile_y0: 0,
9287 tile_x1: picture.width,
9288 tile_y1: picture.height,
9289 ctx: CoefCtxMap::default(),
9290 };
9291 let mut chroma = [
9292 Plane {
9293 source: &picture_u8,
9294 reconstruction: vec![128; picture_u8.len()],
9295 width: picture.width / 2,
9296 height: picture.height / 2,
9297 true_width: true_width / 2,
9298 true_height: true_height / 2,
9299 tile_x0: 0,
9300 tile_y0: 0,
9301 tile_x1: picture.width / 2,
9302 tile_y1: picture.height / 2,
9303 ctx: CoefCtxMap::default(),
9304 },
9305 Plane {
9306 source: &picture_v8,
9307 reconstruction: vec![128; picture_v8.len()],
9308 width: picture.width / 2,
9309 height: picture.height / 2,
9310 true_width: true_width / 2,
9311 true_height: true_height / 2,
9312 tile_x0: 0,
9313 tile_y0: 0,
9314 tile_x1: picture.width / 2,
9315 tile_y1: picture.height / 2,
9316 ctx: CoefCtxMap::default(),
9317 },
9318 ];
9319
9320 // The search trades a bit for the squared error it saves, in the units the
9321 // reconstruction is measured in: one step of the quantizer, squared.
9322 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
9323 let search = Search {
9324 base_q_idx,
9325 deadzone,
9326 lambda: lambda_scale() * key_lambda_factor() * step * step,
9327 modes,
9328 top_k: prune_top_k(),
9329 screen,
9330 arf_leaf_intra: true,
9331 arf_leaf8: true,
9332 arf_leaf_compound: true,
9333 };
9334
9335 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
9336 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
9337 // which may be fewer columns/rows than the padded picture has room for
9338 // -- a block whose origin sits past the true bound is not coded at all,
9339 // matching what a decoder derives from `frame_width`/`frame_height` and
9340 // so never visits either.
9341 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9342 let (cols, rows) = (cols as usize, rows as usize);
9343 // The luma mode of the block above and of the block to the left, which is
9344 // what picks the CDF the next block's mode is coded against -- the same
9345 // bookkeeping the tile writer keeps, so that the search is costing the
9346 // symbol the writer will actually write.
9347 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
9348 // because a 32x32 block may be split into four 16x16 ones.
9349 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9350 // This frame's tile grid (one tile unless the facade armed more).
9351 let layout = crate::tile::TileLayout::new(
9352 header.mi_cols,
9353 header.mi_rows,
9354 tile_cols_log2,
9355 tile_rows_log2,
9356 );
9357 header.tile_info = tile_info_of(&layout, 1);
9358 // The filter search re-decodes this frame's tiles; the decoder derives
9359 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
9360 // `mi_row_starts`), which is what makes the writer's rects and the
9361 // reader's the same rects.
9362 let header_tile_info = header.tile_info.clone();
9363 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
9364 // once over the whole frame. Each tile job builds its own reconstruction
9365 // planes and its own `above_mode`/`left_mode` bands, which is also what
9366 // the tile writer reads -- a tile resets its neighbour contexts (spec
9367 // 5.11.1), so a block at a tile's left edge must cost its mode against
9368 // the default context, not against whatever the tile to its west left in
9369 // that row. At one tile the bands are the frame's, exactly as before.
9370 let (frame_width, frame_height) = (picture.width, picture.height);
9371 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
9372 let [cb, cr] = &mut chroma;
9373 let chroma_out = [
9374 crate::par::Shared::new(&mut cb.reconstruction),
9375 crate::par::Shared::new(&mut cr.reconstruction),
9376 ];
9377 let search_tile = |index: usize,
9378 fctx: &crate::decode::FrameCtx|
9379 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
9380 crate::tile::arm_pricing_cdfs(None, false);
9381 let rect = layout.rect(index);
9382 let mut luma = fresh_plane(
9383 &picture_y8,
9384 frame_width,
9385 frame_height,
9386 true_width,
9387 true_height,
9388 );
9389 let mut chroma = [
9390 fresh_plane(
9391 &picture_u8,
9392 frame_width / 2,
9393 frame_height / 2,
9394 true_width / 2,
9395 true_height / 2,
9396 ),
9397 fresh_plane(
9398 &picture_v8,
9399 frame_width / 2,
9400 frame_height / 2,
9401 true_width / 2,
9402 true_height / 2,
9403 ),
9404 ];
9405 clip_planes_to_tile(&mut luma, &mut chroma, rect);
9406 let mut above_mode = vec![DC_PRED; cols * 2];
9407 let mut left_mode = vec![DC_PRED; rows * 2];
9408 let mut ibc = allow_intrabc.then(|| {
9409 Ibc::new(
9410 (
9411 rect.mi_col0 as usize * 4,
9412 rect.mi_row0 as usize * 4,
9413 (rect.mi_col1 as usize * 4).min(true_width),
9414 (rect.mi_row1 as usize * 4).min(true_height),
9415 ),
9416 &picture_y8,
9417 frame_width,
9418 )
9419 });
9420 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
9421 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
9422 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
9423 let mut modes = Vec::with_capacity(4);
9424 // The quadrants of a superblock are coded in the order the decoder
9425 // walks them, which for a 64x64 split into 32x32 blocks is raster
9426 // order among the quadrants that are inside the frame.
9427 let mut blocks = Vec::with_capacity(4);
9428 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
9429 // BEFORE its quadrants (so both start from the same
9430 // reconstruction) and compared against the four of them below --
9431 // the shape the inter frame's own 64 root takes
9432 // (`search_skip_64`). A frame that allows intrabc is refused
9433 // outright ([`I64_ROOT`]) because the quadrant searches below
9434 // carry DV state a discarded trial would desync.
9435 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
9436 // lane-corner LIFTED the two guards this root shipped with: the
9437 // frame no longer has to be a whole number of superblocks, and
9438 // the superblock no longer has to be wholly inside the frame.
9439 // The desync the guards were written for (a 248x152 corner's
9440 // chroma disagreeing three ways) does NOT reproduce at this
9441 // revision -- see
9442 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
9443 // which pins all three planes of the encoder's reconstruction,
9444 // our decoder and ffmpeg on four straddling sizes, three of them
9445 // cut on BOTH axes, with the edge fire count asserted. What the
9446 // guards cost was every key-frame root on an arbitrary export
9447 // size (the `aligned` line switched the whole feature off on, for
9448 // instance, a 1920x792 frame).
9449 let whole_inside =
9450 x64 + SUPERBLOCK <= luma.true_width && y64 + SUPERBLOCK <= luma.true_height;
9451 // lane-corner: and the superblock the true frame edge CUTS
9452 // THROUGH with more than half of each axis still inside, which is
9453 // all AV1 asks of a `PARTITION_NONE` root (spec
9454 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
9455 // key writer's `Superblock::Whole` arm checks) -- the shape the
9456 // inter root already takes ([`b64_edge`]).
9457 let edge_inside = edge_root_enabled()
9458 && crate::tile::has_half(
9459 sb_col as u32 * crate::tile::SB_MI,
9460 crate::tile::SB_MI,
9461 header.mi_cols,
9462 )
9463 && crate::tile::has_half(
9464 sb_row as u32 * crate::tile::SB_MI,
9465 crate::tile::SB_MI,
9466 header.mi_rows,
9467 );
9468 let sb64_legal = i64_root()
9469 && ibc.is_none()
9470 && sb_row * 2 + 1 < rows
9471 && sb_col * 2 + 1 < cols
9472 && (whole_inside || edge_inside);
9473 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
9474 if sb64_legal {
9475 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9476 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
9477 let (c64, r64) = (sb_col * 4, sb_row * 4);
9478 let (block, cost) = code_square(
9479 &mut luma,
9480 &mut chroma,
9481 (x64, y64),
9482 SUPERBLOCK,
9483 &search,
9484 &mode_bits(above_mode[c64], left_mode[r64]),
9485 tx_select,
9486 None,
9487 true,
9488 fctx,
9489 );
9490 let cost =
9491 cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
9492 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
9493 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
9494 sb64 = Some((cost, block, after));
9495 }
9496 // A superblock whose 64x64 trial already codes almost nothing per
9497 // pixel is taken outright and its quadrants are never searched --
9498 // `split_rd_breakout` one size up, at the threshold the inter
9499 // root clamps to ([`b64_breakout_threshold`]), where this lever
9500 // BUYS wall instead of spending it.
9501 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
9502 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
9503 });
9504 // What the four quadrants cost together, including the split
9505 // partition symbol at the superblock level, so the two arms are
9506 // one comparable number.
9507 let mut sb_cost = match sb64 {
9508 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
9509 None => 0.0,
9510 };
9511 for quadrant in 0..if early64 { 0 } else { 4 } {
9512 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
9513 if col >= cols || row >= rows {
9514 continue;
9515 }
9516 let (x, y) = (col * BLOCK, row * BLOCK);
9517 let (c0, r0) = (col * 2, row * 2);
9518 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
9519
9520 // spec `decode_partition`'s hasRows/hasCols recomputed at this
9521 // 32x32 block's own half (see `crate::tile::has_half`): the
9522 // true frame edge can fall inside a quadrant a superblock-level
9523 // check already let through. A quadrant that fails either may
9524 // not be left whole; a 16x16 sub-block that fails either (once
9525 // split) is a leaf this writer has no rectangular transform
9526 // for, so the search must not pick a split that would need one.
9527 let (has_cols32, has_rows32) = (
9528 crate::tile::has_half(
9529 col as u32 * crate::tile::BLOCK_MI,
9530 crate::tile::BLOCK_MI,
9531 header.mi_cols,
9532 ),
9533 crate::tile::has_half(
9534 row as u32 * crate::tile::BLOCK_MI,
9535 crate::tile::BLOCK_MI,
9536 header.mi_rows,
9537 ),
9538 );
9539 let whole_legal = has_cols32 && has_rows32;
9540 // A 16x16 sub-block's own hasCols/hasRows (spec
9541 // `decode_partition`, recomputed at this leaf's own half):
9542 // either axis false is a straddling leaf this writer codes as
9543 // the 8x8 leaves that are inside it
9544 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
9545 // false is the same split with the partition symbol inferred
9546 // rather than coded -- no rectangular transform is needed
9547 // (lane-av1rect).
9548 let sub_half = |sr: usize, sc: usize| {
9549 (
9550 crate::tile::has_half(
9551 sc as u32 * crate::tile::SUB_MI,
9552 crate::tile::SUB_MI,
9553 header.mi_cols,
9554 ),
9555 crate::tile::has_half(
9556 sr as u32 * crate::tile::SUB_MI,
9557 crate::tile::SUB_MI,
9558 header.mi_rows,
9559 ),
9560 )
9561 };
9562 // What the whole 32x32 costs, including the partition symbol
9563 // that says it is not split.
9564 let (whole, mut cost_whole) = code_square(
9565 &mut luma,
9566 &mut chroma,
9567 (x, y),
9568 BLOCK,
9569 &search,
9570 &mode_bits(above_mode[c0], left_mode[r0]),
9571 tx_select,
9572 ibc.as_mut(),
9573 true,
9574 fctx,
9575 );
9576 cost_whole += search.lambda * partition_bits(BLOCK, false);
9577 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
9578
9579 // What four 16x16 blocks cost instead, each searched against
9580 // the reconstruction the ones before it left.
9581 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
9582 let mut split = Vec::with_capacity(4);
9583 let mut cost_split = search.lambda
9584 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
9585 let mut split_modes = Vec::with_capacity(4);
9586 for sub in 0..4 {
9587 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
9588 // Same filter as the writer's `sub_positions` (spec
9589 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
9590 // return): a sub-block whose own origin sits past the
9591 // true frame is never coded, so it must not be searched
9592 // or pushed onto `split` either, or the writer's block
9593 // count will not match what it is prepared to name.
9594 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
9595 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
9596 {
9597 continue;
9598 }
9599 let (has_cols16, has_rows16) = sub_half(sr, sc);
9600 if has_cols16 && has_rows16 {
9601 let (block, cost) = code_square(
9602 &mut luma,
9603 &mut chroma,
9604 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
9605 SUB,
9606 &search,
9607 &mode_bits(above_mode[sc], left_mode[sr]),
9608 tx_select,
9609 ibc.as_mut(),
9610 true,
9611 fctx,
9612 );
9613 cost_split += cost;
9614 split_modes.push(block.mode);
9615 above_mode[sc] = block.mode;
9616 left_mode[sr] = block.mode;
9617 split.push(block);
9618 } else {
9619 // A straddling 16x16: two (or, at a true corner, one)
9620 // 8x8 leaves, in the raster order `write_leaf8`'s
9621 // caller expects. Both leaves cost against the SAME
9622 // enclosing-slot mode context (see
9623 // `crate::tile::write_leaf8`'s doc), and neither
9624 // updates `above_mode`/`left_mode` at this SUB slot --
9625 // the writer never does either, so the search must
9626 // not diverge from what it will actually read next.
9627 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
9628 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
9629 let mut leaves = Vec::with_capacity(2);
9630 for i in 0..4 {
9631 let leaf_x = x_sub + (i % 2) * 8;
9632 let leaf_y = y_sub + (i / 2) * 8;
9633 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
9634 continue;
9635 }
9636 let (leaf, cost) = code_square(
9637 &mut luma,
9638 &mut chroma,
9639 (leaf_x, leaf_y),
9640 8,
9641 &search,
9642 &leaf_mode_bits,
9643 tx_select,
9644 None,
9645 true,
9646 fctx,
9647 );
9648 cost_split += cost;
9649 split_modes.push(leaf.mode);
9650 leaves.push(leaf);
9651 }
9652 split.push(BlockCoeffs {
9653 eight: Some(leaves),
9654 ..BlockCoeffs::default()
9655 });
9656 }
9657 }
9658
9659 // A split whose subs are all whole 16x16 is a real quality
9660 // alternative to `whole`, exactly as before. Through r14, a
9661 // split carrying an 8x8-leaf sub was only ever forced
9662 // (`!whole_legal`), never chosen on cost, because the leaf
9663 // path was not yet proven against a real decoder; r15 proved
9664 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
9665 // the read path (`decode_leaf8`), so leaf8 can now win on
9666 // cost anywhere, same as any other split.
9667 if !whole_legal || (split_blocks && cost_split < cost_whole) {
9668 sb_cost += cost_split;
9669 modes.extend_from_slice(&split_modes);
9670 blocks.push(Quadrant::Split(split));
9671 } else {
9672 sb_cost += cost_whole;
9673 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
9674 for cell in 0..2 {
9675 above_mode[c0 + cell] = whole.mode;
9676 left_mode[r0 + cell] = whole.mode;
9677 }
9678 modes.push(whole.mode);
9679 blocks.push(Quadrant::Whole(whole));
9680 }
9681 }
9682 let index = sb_row * sb_cols + sb_col;
9683 match sb64 {
9684 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
9685 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
9686 for cell in 0..4 {
9687 above_mode[sb_col * 4 + cell] = block.mode;
9688 left_mode[sb_row * 4 + cell] = block.mode;
9689 }
9690 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9691 if !whole_inside {
9692 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9693 }
9694 let mode = block.mode;
9695 coded.push((index, Superblock::Whole(block), vec![mode]));
9696 }
9697 _ => coded.push((index, Superblock::Split(blocks), modes)),
9698 }
9699 }
9700 }
9701 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
9702 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
9703 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
9704 for (&out, tile) in chroma_out.iter().zip(&chroma) {
9705 copy_rect(
9706 out,
9707 &tile.reconstruction,
9708 frame_width / 2,
9709 x0 / 2,
9710 y0 / 2,
9711 x1.div_ceil(2),
9712 y1.div_ceil(2),
9713 );
9714 }
9715 Ok(coded)
9716 };
9717 let searched = search_tiles(layout.count(), fctx, search_tile)?;
9718 // Back into frame raster order: the tile writer indexes `superblocks` by
9719 // the frame's own superblock index, and `modes` is the coding order the
9720 // ablation drivers read.
9721 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> =
9722 (0..sb_cols * sb_rows).map(|_| None).collect();
9723 for (at, superblock, block_modes) in searched.into_iter().flatten() {
9724 in_order[at] = Some((superblock, block_modes));
9725 }
9726 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
9727 let mut modes = Vec::with_capacity(cols * rows);
9728 for slot in in_order {
9729 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
9730 superblocks.push(superblock);
9731 modes.extend_from_slice(&block_modes);
9732 }
9733
9734 #[cfg(test)]
9735 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(
9736 &superblocks,
9737 base_q_idx,
9738 ));
9739 // A key frame always starts from the defaults (`primary_ref_frame` is
9740 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
9741 // set, so what it stores into the slots it refreshes is exactly those
9742 // defaults again (spec 7.20's `started_from` arm) -- the first inter
9743 // frame after it therefore starts from the defaults too.
9744 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
9745 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
9746 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
9747 // from -- `Cdfs::txb` widens every luma set under it.
9748 cdfs.reduced_tx_set = header.reduced_tx_set;
9749 let start_cdfs = CdfSnapshot(cdfs);
9750 // The luma restoration-unit grid this frame's `lr_params` implies
9751 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
9752 // swallowed by the one before it), for the tile writer's own per-unit
9753 // walk.
9754 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
9755 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
9756 // Every tile is coded from this frame's OWN starting tables and leaves
9757 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
9758 // loop-restoration reference and its neighbour contexts), so the tiles
9759 // are independent of each other and of the order they are written in.
9760 let code_tiles = |bits: u8,
9761 sb_cols: usize,
9762 grid: &[u8],
9763 units: &[Option<crate::restoration::WienerInfo>]|
9764 -> Result<Vec<Vec<u8>>> {
9765 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
9766 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
9767 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
9768 crate::tile::arm_sb128(sb128_on());
9769 let mut cdfs = start_cdfs.0.clone();
9770 crate::tile::arm_screen(screen);
9771 crate::tile::arm_frame_mi_dims(frame_mi_dims);
9772 crate::tile::arm_filter_intra(filter_intra_on());
9773 crate::tile::arm_intrabc(allow_intrabc);
9774 crate::tile::arm_pricing_cdfs(None, false);
9775 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
9776 mi_cols,
9777 mi_rows,
9778 base_q_idx,
9779 &superblocks,
9780 tx_select,
9781 &mut cdfs,
9782 layout.rect(index),
9783 )?;
9784 Ok((bytes, None))
9785 })?;
9786 Ok(out)
9787 };
9788 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
9789 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
9790 // the tile just coded back to the decoder under each candidate (see
9791 // `crate::filter_search`), and keep the filtered picture that wins as
9792 // the reconstruction -- what a decoder outputs, and what the next
9793 // frame predicts from.
9794 pick_and_apply_filters(
9795 &mut header,
9796 &mut luma,
9797 &mut chroma,
9798 [&picture_y8, &picture_u8, &picture_v8],
9799 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
9800 // and loop restoration off and codes none of their parameters
9801 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
9802 // the encoder's reconstruction is already what a decoder produces.
9803 !allow_intrabc,
9804 &mut tiles,
9805 search.lambda,
9806 fctx,
9807 // A key frame codes no 128x128 root block (the writer has no intra
9808 // path at that size), so every unit carries its own literal.
9809 &[],
9810 // Every re-code starts from this frame's OWN starting tables, never
9811 // from where the first write left them: the second tile is the same
9812 // symbol sequence plus new ones, so it must adapt from the same
9813 // point the decoder will.
9814 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
9815 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
9816 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
9817 crate::decode::decode_key_frame_tiles_lr(
9818 &payloads,
9819 &header_tile_info,
9820 h.mi_cols,
9821 h.mi_rows,
9822 base_q_idx,
9823 h.frame_width,
9824 h.frame_height,
9825 seq.enable_filter_intra,
9826 cdef,
9827 lf,
9828 tx_select,
9829 h.reduced_tx_set,
9830 h.allow_screen_content_tools,
9831 h.allow_intrabc,
9832 lr,
9833 fctx,
9834 )
9835 },
9836 )?;
9837 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
9838 header.tile_info.tile_size_bytes = tile_size_bytes;
9839 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
9840 let mut stream = temporal_delimiter();
9841 stream.extend_from_slice(&sequence_header_obu(&seq)?);
9842 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
9843
9844 let [u, v] = chroma;
9845 Ok(Encoded {
9846 stream,
9847 modes,
9848 inter_block_share: 0.0,
9849 reconstruction: Picture {
9850 width: luma.width,
9851 height: luma.height,
9852 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9853 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9854 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9855 },
9856 tile,
9857 mi_cols: header.mi_cols,
9858 mi_rows: header.mi_rows,
9859 base_q_idx,
9860 tx_select,
9861 // A key frame codes no inter block, so no motion_mode symbol.
9862 switchable_motion_mode: false,
9863 screen,
9864 reduced_tx_set: header.reduced_tx_set,
9865 next_cdfs: Box::new(start_cdfs.clone()),
9866 start_cdfs: Box::new(start_cdfs),
9867 loop_filter: header.loop_filter,
9868 cdef: header.cdef,
9869 loop_restoration: header.loop_restoration,
9870 allow_intrabc,
9871 delta: header.delta.clone(),
9872 })
9873}
9874
9875/// Chooses this frame's deblocking levels and CDEF strengths, writes them
9876/// into `header` and
9877/// replaces the frame's own region of the encoder's reconstruction with the
9878/// filtered picture the decoder produced under them
9879/// ([`crate::filter_search::pick_deblock`]).
9880///
9881/// `search == false` leaves the header at level 0 (deblocking off) and the
9882/// reconstruction untouched: the caller's stream is one this crate's own
9883/// decoder cannot read back, so there is nothing to search against.
9884///
9885/// # Errors
9886/// The decoder's own error, when it refuses the tile the encoder just wrote
9887/// -- that is an encoder defect, not a filter one, so it is propagated
9888/// rather than swallowed into "no deblocking".
9889fn pick_and_apply_filters(
9890 header: &mut FrameHeader,
9891 luma: &mut Plane<'_>,
9892 chroma: &mut [Plane<'_>; 2],
9893 source: [&[u8]; 3],
9894 search: bool,
9895 // The coded tiles, one payload per tile of the frame's grid, replaced in
9896 // place when the search chooses a per-64x64 `cdef_idx` list
9897 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
9898 // tile is written a second time under `recode` and the winner
9899 // re-decoded from them.
9900 tiles: &mut Vec<Vec<u8>>,
9901 lambda: f64,
9902 fctx: &crate::decode::FrameCtx,
9903 // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles
9904 // carry -- empty (the identity map) for a frame whose every block covers
9905 // one 64x64 CDEF unit.
9906 cdef_owner: &[u32],
9907 recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<Vec<u8>>>,
9908 decode: impl Fn(
9909 &LoopFilterParams,
9910 &CdefParams,
9911 &FrameHeader,
9912 &[Vec<u8>],
9913 &LoopRestorationParams,
9914 ) -> Result<Picture>,
9915) -> Result<()> {
9916 if !search {
9917 return Ok(());
9918 }
9919 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
9920 let hdr = header.clone();
9921 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
9922 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
9923 let damping = 3 + (header.quantization.base_q_idx >> 6);
9924 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9925 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
9926 let none_lr = LoopRestorationParams::default();
9927 // Every candidate scores the same coded tile: decode it once and re-run
9928 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
9929 // the encoder's profile before this). The per-64x64 error the CDEF
9930 // preset search reads comes off the REPLAYED picture, which is the same
9931 // picture a decode produces -- that is what the replay is pinned on.
9932 crate::decode::clear_filter_replay();
9933 // lane-av1fpar: the per-tile search is over, so every core is idle from
9934 // here to the end of the frame -- band each candidate's deblock/CDEF
9935 // replay, the capture decode's own filter chain and the loop-restoration
9936 // passes across the same workers the search used.
9937 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
9938 let ft = crate::par::timer(crate::par::S_FILTER);
9939 let search_result = crate::filter_search::pick_filters(
9940 |lf, cdef| {
9941 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
9942 return Ok(picture);
9943 }
9944 crate::decode::arm_filter_replay();
9945 let _t = crate::par::timer(crate::par::S_FIRST);
9946 decode(lf, cdef, &hdr, tiles, &none_lr)
9947 },
9948 source,
9949 luma.width,
9950 (fw, fh),
9951 damping,
9952 (sb_cols, sb_rows),
9953 lambda,
9954 cdef_owner,
9955 );
9956 drop(ft);
9957 let (lf, cdef, idx_grid, picture) = search_result?;
9958 header.loop_filter = lf;
9959 header.cdef = cdef;
9960 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
9961 // in the frame header, so a re-decode under candidate parameters cannot
9962 // search them the way deblocking and CDEF are searched above. What the
9963 // decoder hands back instead is its own filter chain's intermediates
9964 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
9965 // those, through the decoder's own Wiener kernel.
9966 //
9967 // The capture rides the decode this stage was already going to do: the
9968 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
9969 // decode of the tile as it stands. That decode's header still says
9970 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
9971 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
9972 // an approximation inside the SEARCH only; the reconstruction this
9973 // function ends up splicing is always a real decode of the real tile.
9974 let lr_on = restoration_enabled();
9975 // The `cdef_idx` literals live in the tile payload, so a frame that
9976 // chose a per-64x64 preset list codes its tiles a second time.
9977 if !idx_grid.is_empty() {
9978 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
9979 }
9980 // lane-av1cap: that re-coded tile used to be DECODED here as well --
9981 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
9982 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
9983 // and the picture this function splices. Both come out of ONE more
9984 // replay of the winning parameters on the same captured pre-filter
9985 // planes every candidate was scored on: the same two filter kernels, on
9986 // the same input, in the same order, so the same bytes. Re-coding the
9987 // tile does not move the reconstruction the replay holds -- `cdef_idx`
9988 // is an equiprobable literal, so it adapts no CDF and changes no
9989 // residual.
9990 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
9991 #[cfg(test)]
9992 let replay_was_used = replayed.is_some();
9993 let (mut filtered, mut stages) = match replayed {
9994 Some((picture, stages)) => (picture, stages),
9995 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
9996 // refuses): every candidate was a full decode, so the winner's own
9997 // picture stands, and the stages still need a capturing decode.
9998 None => {
9999 fctx.capture_stages.set(lr_on);
10000 let picture = if idx_grid.is_empty() && !lr_on {
10001 picture
10002 } else {
10003 let _t = crate::par::timer(crate::par::S_CAPTURE);
10004 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
10005 };
10006 fctx.capture_stages.set(false);
10007 (picture, crate::decode::take_filter_stages(fctx))
10008 }
10009 };
10010 #[cfg(test)]
10011 if crate::decode::verify_final_replay() && replay_was_used {
10012 fctx.capture_stages.set(lr_on);
10013 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
10014 fctx.capture_stages.set(false);
10015 let want_stages = crate::decode::take_filter_stages(fctx);
10016 assert!(
10017 (want.width, want.height) == (filtered.width, filtered.height)
10018 && want.y == filtered.y
10019 && want.u == filtered.u
10020 && want.v == filtered.v,
10021 "the final filter replay is not the capture decode it stands in for",
10022 );
10023 // Only the frame's own cropped region: the plane is padded to the
10024 // superblock grid and the columns past the mi extent are written by
10025 // nothing (the decoder's plane pool leaves whatever the last frame
10026 // put there), while the restoration search reads strictly inside
10027 // `fw x fh` -- `restoration::lr_sample` clamps its column to
10028 // `plane_w - 1` and its row to the frame's, and
10029 // `filter_search::pick_restoration`'s own SSE walk never leaves the
10030 // crop either.
10031 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
10032 for row in 0..h {
10033 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
10034 assert!(
10035 x == y,
10036 "{what}: the replayed filter stages are not the ones the capture \
10037 decode returns (row {row} of {h}, width {w}, stride {stride})",
10038 );
10039 }
10040 };
10041 match (&want_stages, &stages) {
10042 (Some(a), Some(b)) => {
10043 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
10044 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
10045 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
10046 region(
10047 &a.deblocked[i],
10048 &b.deblocked[i],
10049 a.stride[i],
10050 w,
10051 h,
10052 "deblocked",
10053 );
10054 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
10055 }
10056 }
10057 (None, None) => {}
10058 _ => panic!("one path captured filter stages and the other did not"),
10059 }
10060 }
10061 // lane-av1cap2: the capture stays live past the restoration search --
10062 // `crate::decode::replay_restoration` filters the same post-CDEF plane
10063 // rather than decoding the re-coded tile. Cleared at the end instead.
10064 let mut lr = LoopRestorationParams::default();
10065 if lr_on {
10066 let unit = lr_unit();
10067 let mut want = LoopRestorationParams {
10068 loop_restoration_size: [unit, unit, unit],
10069 uses_lr: true,
10070 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
10071 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
10072 lr_unit_shift: u8::from(unit == 128),
10073 ..LoopRestorationParams::default()
10074 };
10075 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
10076 let lrt = crate::par::timer(crate::par::S_LR);
10077 let units = match stages.take() {
10078 Some(stages) => crate::filter_search::pick_restoration(
10079 &stages,
10080 source[0],
10081 luma.width,
10082 (fw, fh),
10083 &want,
10084 lambda,
10085 fctx,
10086 ),
10087 None => Vec::new(),
10088 };
10089 // A frame no unit restores keeps `RESTORE_NONE` on every plane
10090 // rather than paying ~1 bit per 64x64 for a tile full of
10091 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
10092 // clip whose units never take a filter).
10093 drop(lrt);
10094 if units.iter().any(Option::is_some) {
10095 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
10096 let _t = crate::par::timer(crate::par::S_CAPTURE);
10097 // lane-av1cap2: that re-coded tile used to be DECODED here to
10098 // reach the restored reference frame -- 5.6% of a 4K frame,
10099 // for a filter that reads nothing of the tile but the per-unit
10100 // Wiener filters this stage just chose. Run the decoder's own
10101 // restoration kernel on the replay's post-CDEF plane instead
10102 // (`crate::decode::replay_restoration`), with the real
10103 // post-deblock stripe borders.
10104 match crate::decode::replay_restoration(&want, &units, fctx) {
10105 Some(y) => {
10106 #[cfg(test)]
10107 let margin = fctx
10108 .last_frame_wide_margin
10109 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
10110 #[cfg(test)]
10111 if crate::decode::verify_final_replay() {
10112 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
10113 assert!(
10114 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
10115 && want_pic.u == filtered.u
10116 && want_pic.v == filtered.v,
10117 "the restoration replay moved a chroma plane or the picture size",
10118 );
10119 assert!(
10120 want_pic.y == y,
10121 "the restoration replay is not the decode of the re-coded tile",
10122 );
10123 assert!(
10124 fctx.last_frame_wide_margin
10125 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
10126 == margin,
10127 "the restoration replay's wide-margin luma is not the decode's",
10128 );
10129 }
10130 filtered.y = y;
10131 }
10132 // Nothing captured: the winner came out of a full decode,
10133 // so this one does too.
10134 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
10135 }
10136 *tiles = coded;
10137 lr = want;
10138 }
10139 }
10140 crate::decode::clear_filter_replay();
10141 header.loop_restoration = lr;
10142 let dec_cw = filtered.width.div_ceil(2);
10143 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
10144 crate::filter_search::splice(
10145 &mut luma.reconstruction,
10146 luma.width,
10147 &filtered.y,
10148 filtered.width,
10149 fw,
10150 fh,
10151 );
10152 crate::filter_search::splice(
10153 &mut chroma[0].reconstruction,
10154 chroma[0].width,
10155 &filtered.u,
10156 dec_cw,
10157 cw,
10158 ch,
10159 );
10160 crate::filter_search::splice(
10161 &mut chroma[1].reconstruction,
10162 chroma[1].width,
10163 &filtered.v,
10164 dec_cw,
10165 cw,
10166 ch,
10167 );
10168 Ok(())
10169}
10170
10171/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
10172/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
10173/// since every block this crate's inter tile writer codes is 32x32.
10174const SIZE_GROUP_32: usize = 3;
10175
10176/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
10177/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
10178/// stack this encoder builds is ever asked to predict against.
10179const LAST_FRAME: i8 = 1;
10180
10181/// What an inter frame's intra branch spends to name each of the thirteen
10182/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
10183/// context, since an inter frame's intra blocks do not read their
10184/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
10185/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
10186/// state, so it is built once per frame.
10187fn inter_mode_bits() -> [f64; 13] {
10188 std::array::from_fn(|mode| {
10189 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
10190 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
10191 } else {
10192 0.0
10193 };
10194 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
10195 + angle
10196 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
10197 })
10198}
10199
10200/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
10201/// [`mc::predict`] takes, in the units of the plane it predicts into.
10202///
10203/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
10204/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
10205/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
10206/// domain. `luma` picks which.
10207fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
10208 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
10209}
10210
10211/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
10212/// that module): the magnitude an `MV_CLASS_n` component's own bits start
10213/// counting from.
10214fn mv_class_base(class: usize) -> i32 {
10215 if class == 0 { 0 } else { 2i32 << (class + 2) }
10216}
10217
10218/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
10219/// `tile::mv_class_of`.
10220fn mv_class_of(z: i32) -> usize {
10221 let mut class = 0;
10222 while class < 10 && mv_class_base(class + 1) <= z {
10223 class += 1;
10224 }
10225 class
10226}
10227
10228/// What [`crate::tile::write_mv_component`] (private to that module) would
10229/// spend coding one non-zero motion vector component, against the same
10230/// static default CDFs the writer starts a frame from — the same
10231/// static-table approximation [`mode_bits`] costs the luma mode symbol
10232/// through, not the tile writer's own adapting state, which this encoder has
10233/// no way to read without duplicating it block for block.
10234///
10235/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
10236/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
10237/// exists to avoid ever happening.
10238fn mv_component_bits(diff: i32) -> Option<f64> {
10239 let hp_frame = crate::tile::high_precision_mv();
10240 let mag = diff.unsigned_abs() as i32;
10241 let z = mag - 1;
10242 if !hp_frame && z & 1 == 0 {
10243 return None;
10244 }
10245 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
10246 let class = mv_class_of(z);
10247 bits += symbol_bits(&cdf::MV_CLASS, class);
10248 let local = z - mv_class_base(class);
10249 let hp = (local & 1) as usize;
10250 if class == 0 {
10251 let bit = (local >> 3) & 1;
10252 let fr = (local >> 1) & 3;
10253 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
10254 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
10255 // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
10256 // frame, so the pricer charges for it there and only there.
10257 if hp_frame {
10258 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
10259 }
10260 } else {
10261 let d = local >> 3;
10262 let fr = (local >> 1) & 3;
10263 for i in 0..class {
10264 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
10265 }
10266 bits += symbol_bits(&cdf::MV_FR, fr as usize);
10267 if hp_frame {
10268 bits += symbol_bits(&cdf::MV_HP, hp);
10269 }
10270 }
10271 Some(bits)
10272}
10273
10274/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
10275/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
10276/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
10277/// value without the second motion search's wall.
10278fn last2_new_mv() -> bool {
10279 match std::env::var("EC_AV1_LAST2_NEW").ok() {
10280 Some(v) => v != "0",
10281 None => true,
10282 }
10283}
10284
10285/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
10286/// own -- a second motion search per block against that reference's picture,
10287/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
10288/// off in a test build (what the lane measured both arms with).
10289fn extra_ref_new_mv() -> bool {
10290 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
10291 Some(v) if cfg!(test) => v != "0",
10292 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
10293 }
10294}
10295
10296/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
10297/// flat slot plan (`inter_frame_headers_slots`): every reference but
10298/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
10299/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
10300/// frame two back when there is one (otherwise it, too, names the key frame's
10301/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
10302pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
10303 let last = order_hint.wrapping_sub(1) & 0x7f;
10304 let alt = if has_altref {
10305 order_hint.wrapping_sub(2) & 0x7f
10306 } else {
10307 key_hint
10308 };
10309 [last, last, last, key_hint, last, last, alt]
10310}
10311
10312/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
10313/// header bit that lets each block choose between a single and a compound
10314/// reference. Off by default until compound prediction is measured to pay;
10315/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
10316/// runs as), and every block still codes SINGLE, so the only cost is one
10317/// `comp_mode` symbol per inter block.
10318pub(crate) const REFERENCE_SELECT: bool = true;
10319
10320/// [`REFERENCE_SELECT`], with the test-build environment override.
10321pub(crate) fn reference_select() -> bool {
10322 match std::env::var("EC_AV1_COMPOUND").ok() {
10323 Some(v) if cfg!(test) => v != "0",
10324 _ => crate::speed::at(&crate::speed::COMPOUND),
10325 }
10326}
10327
10328/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
10329/// per entry past `start`, `1` to advance and `0` to stop, at most two.
10330fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
10331 let mut bits = 0.0;
10332 let mut idx = start;
10333 while idx < start + 2 && stack.entries.len() > idx + 1 {
10334 let advance = idx < target;
10335 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
10336 if !advance {
10337 break;
10338 }
10339 idx += 1;
10340 }
10341 bits
10342}
10343
10344/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
10345/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
10346/// `assign_mv`), so the same vector costs a different residual from each.
10347fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
10348 let mut best: Option<(f64, u8)> = None;
10349 for idx in 0..3usize {
10350 if idx > 0 && stack.entries.len() <= idx {
10351 break;
10352 }
10353 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
10354 if let Some(b) = mv_residual_bits(mv, base) {
10355 let total = b + drl_bits_for(stack, 0, idx);
10356 if best.is_none_or(|(t, _)| total < t) {
10357 best = Some((total, idx as u8));
10358 }
10359 }
10360 }
10361 best
10362}
10363
10364/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
10365/// zero vector and the stack's own candidates. A neighbour block's vector is
10366/// where this block's motion most often already is, which is what pays for
10367/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
10368/// vs libaom for 0.2 s off a 6 s ladder).
10369fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
10370 let mut seeds = [(0, 0); 4];
10371 let mut n = 1;
10372 for e in stack.entries.iter().take(3) {
10373 seeds[n] = e.mv;
10374 n += 1;
10375 }
10376 (seeds, n)
10377}
10378
10379/// What [`crate::tile::write_mv`] (private to that module) would spend
10380/// coding `mv` as a residual against `pred`: the joint symbol naming which
10381/// components differ, then each differing component. `None` under the same
10382/// condition [`mv_component_bits`] returns `None`.
10383/// How many frames back `ref_frame` sits from the frame being coded, off the
10384/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
10385/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
10386/// what [`crate::motion::search`] scales its starting step by.
10387fn ref_distance(ref_frame: i8) -> u32 {
10388 let (bits, order_hint, hints) = crate::tile::order_hints();
10389 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
10390 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
10391 .unsigned_abs()
10392 .max(1);
10393 if crate::envflags::env_flag!("EC_TRACE_DIST") {
10394 eprintln!(
10395 "EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}",
10396 hints[i]
10397 );
10398 }
10399 d
10400}
10401
10402fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
10403 let diff = (mv.0 - pred.0, mv.1 - pred.1);
10404 let joint = match (diff.0 != 0, diff.1 != 0) {
10405 (false, false) => 0,
10406 (false, true) => 1,
10407 (true, false) => 2,
10408 (true, true) => 3,
10409 };
10410 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
10411 for d in [diff.0, diff.1] {
10412 if d != 0 {
10413 bits += mv_component_bits(d)?;
10414 }
10415 }
10416 Some(bits)
10417}
10418
10419/// Rounds `mv` so that its residual against `pred` is one
10420/// [`crate::tile::write_mv_component`] can actually code: each component's
10421/// difference is either zero or has an even magnitude (the eighth-pel bit
10422/// `allow_high_precision_mv` off always infers as one forces the coded
10423/// magnitude odd one step further in, which comes out even here since this
10424/// crate's motion search works in whole units of that same step). Rounding
10425/// down keeps every coded MV — and so every `nearest_mv` a later block's
10426/// stack votes with — built from an even displacement from `(0, 0)`, so the
10427/// invariant holds without this function seeing the whole stack.
10428/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
10429/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
10430/// always), the shape [`set_frame_interp`] has: the witness that has to see
10431/// `mv_hp` symbols coded turns it on through this while holding
10432/// [`crate::speed::knob_write`].
10433static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
10434
10435/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
10436#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
10437pub(crate) fn set_high_precision_mv(on: Option<bool>) {
10438 HP_MV_OVERRIDE.store(
10439 on.map_or(u8::MAX, u8::from),
10440 std::sync::atomic::Ordering::Relaxed,
10441 );
10442}
10443
10444/// The qindex below which an inter frame codes `allow_high_precision_mv`
10445/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
10446/// crate's shipped value, i.e. high-precision motion vectors off in every
10447/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
10448pub(crate) const HP_MV_QTHRESH: u8 = 0;
10449
10450/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
10451/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
10452/// always, any number as the threshold) so the BD gate can sweep the policy
10453/// without a rebuild.
10454pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
10455 match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
10456 0 => return false,
10457 1 => return true,
10458 _ => {}
10459 }
10460 static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
10461 let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
10462 Some("all" | "always") => 256,
10463 Some("0" | "off") => 0,
10464 Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
10465 None => u16::from(HP_MV_QTHRESH),
10466 });
10467 u16::from(base_q_idx) < threshold
10468}
10469
10470fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
10471 // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
10472 // residual is codable and there is nothing to round away.
10473 if crate::tile::high_precision_mv() {
10474 return mv;
10475 }
10476 let round = |m: i32, p: i32| {
10477 let diff = m - p;
10478 let mag = diff.unsigned_abs() as i32;
10479 let even = mag - mag % 2;
10480 if even == 0 {
10481 p
10482 } else {
10483 p + even * diff.signum()
10484 }
10485 };
10486 (round(mv.0, pred.0), round(mv.1, pred.1))
10487}
10488
10489/// Predicts one `side`-square block by motion compensation from `reference`
10490/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
10491#[allow(clippy::too_many_arguments)]
10492fn mc_trial(
10493 plane: &Plane,
10494 x: usize,
10495 y: usize,
10496 side: usize,
10497 mv: (i32, i32),
10498 luma: bool,
10499 reference: &[u16],
10500 stride: usize,
10501 ref_width: usize,
10502 ref_height: usize,
10503 skip: bool,
10504 base_q_idx: u8,
10505 deadzone: f64,
10506 set: TxbSet,
10507 fctx: &crate::decode::FrameCtx,
10508) -> Trial {
10509 mc_trial_typed(
10510 plane,
10511 x,
10512 y,
10513 side,
10514 mv,
10515 luma,
10516 reference,
10517 stride,
10518 ref_width,
10519 ref_height,
10520 skip,
10521 base_q_idx,
10522 deadzone,
10523 set,
10524 TxType::DctDct,
10525 fctx,
10526 )
10527}
10528
10529/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
10530#[allow(clippy::too_many_arguments)]
10531fn mc_trial_typed(
10532 plane: &Plane,
10533 x: usize,
10534 y: usize,
10535 side: usize,
10536 mv: (i32, i32),
10537 luma: bool,
10538 reference: &[u16],
10539 stride: usize,
10540 ref_width: usize,
10541 ref_height: usize,
10542 skip: bool,
10543 base_q_idx: u8,
10544 deadzone: f64,
10545 set: TxbSet,
10546 tx_type: TxType,
10547 fctx: &crate::decode::FrameCtx,
10548) -> Trial {
10549 let x_q4 = mv_to_q4(x, mv.1, luma);
10550 let y_q4 = mv_to_q4(y, mv.0, luma);
10551 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
10552 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
10553 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
10554 // lane-av1speed: both buffers are per-candidate scratch on the hottest
10555 // path in the encoder, so they live on the stack -- `side` is at most
10556 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
10557 // per motion-compensated trial otherwise.
10558 let mut prediction16 = [0u16; BLOCK * BLOCK];
10559 let prediction16 = &mut prediction16[..side * side];
10560 mc::predict(
10561 reference,
10562 stride,
10563 ref_width,
10564 ref_height,
10565 x_q4,
10566 y_q4,
10567 side,
10568 side,
10569 prediction16,
10570 fctx,
10571 );
10572 let mut prediction = [0u8; BLOCK * BLOCK];
10573 let prediction = &mut prediction[..side * side];
10574 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
10575 *dst = src as u8;
10576 }
10577 plane.code_from_prediction_typed(
10578 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
10579 )
10580}
10581
10582/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
10583/// references predict into the `CONV_BUF` intermediate domain
10584/// ([`mc::predict_compound_intermediate`]) and are blended by
10585/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
10586/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
10587/// block, so the encoder's reconstruction is the decoder's.
10588#[allow(clippy::too_many_arguments)]
10589fn mc_trial_compound(
10590 plane: &Plane,
10591 x: usize,
10592 y: usize,
10593 side: usize,
10594 mvs: ((i32, i32), (i32, i32)),
10595 luma: bool,
10596 ref0: (&[u16], usize, usize, usize),
10597 ref1: (&[u16], usize, usize, usize),
10598 base_q_idx: u8,
10599 deadzone: f64,
10600 set: TxbSet,
10601 fctx: &crate::decode::FrameCtx,
10602) -> Trial {
10603 mc_trial_compound_typed(
10604 plane,
10605 x,
10606 y,
10607 side,
10608 mvs,
10609 luma,
10610 ref0,
10611 ref1,
10612 base_q_idx,
10613 deadzone,
10614 set,
10615 TxType::DctDct,
10616 fctx,
10617 )
10618}
10619
10620/// [`mc_trial_compound`] coding its residual with a named transform type
10621/// (lane-txset2).
10622#[allow(clippy::too_many_arguments)]
10623fn mc_trial_compound_typed(
10624 plane: &Plane,
10625 x: usize,
10626 y: usize,
10627 side: usize,
10628 (mv0, mv1): ((i32, i32), (i32, i32)),
10629 luma: bool,
10630 ref0: (&[u16], usize, usize, usize),
10631 ref1: (&[u16], usize, usize, usize),
10632 base_q_idx: u8,
10633 deadzone: f64,
10634 set: TxbSet,
10635 tx_type: TxType,
10636 fctx: &crate::decode::FrameCtx,
10637) -> Trial {
10638 let mut inter0 = [0i32; BLOCK * BLOCK];
10639 let mut inter1 = [0i32; BLOCK * BLOCK];
10640 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
10641 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
10642 mc::predict_compound_intermediate(
10643 r.0,
10644 r.1,
10645 r.2,
10646 r.3,
10647 mv_to_q4(x, mv.1, luma),
10648 mv_to_q4(y, mv.0, luma),
10649 mc::REF_NO_SCALE,
10650 side,
10651 side,
10652 fctx.interp_filter.get(),
10653 fctx.interp_filter.get(),
10654 dst,
10655 fctx,
10656 );
10657 }
10658 let mut blended16 = [0u16; BLOCK * BLOCK];
10659 let blended16 = &mut blended16[..side * side];
10660 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
10661 let mut prediction = [0u8; BLOCK * BLOCK];
10662 let prediction = &mut prediction[..side * side];
10663 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
10664 *dst = src as u8;
10665 }
10666 plane.code_from_prediction_typed(
10667 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
10668 )
10669}
10670
10671/// Codes one 32x32 block of an inter frame as whichever costs least of: each
10672/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
10673/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
10674/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
10675/// coding a real residual (`skip: false`) whenever one prices out cheaper
10676/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
10677/// missing inter `tx_type` symbol (the desync this function's candidates
10678/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
10679/// fixed.
10680///
10681/// The symbol costs this ranks candidates by use fixed contexts (0) for
10682/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
10683/// contexts for those come from its own neighbour bookkeeping
10684/// (`tile::Neighbours`), which is private to that module and not worth
10685/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
10686/// `drl_mode` contexts come straight from `stack`, which is exact, because
10687/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
10688/// the tile writer derives from the same grid state.
10689#[allow(clippy::too_many_arguments)]
10690/// One prediction of `side` x `side` samples from `reference`, as `u8` --
10691/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
10692/// four times the stack scratch that function sizes for [`BLOCK`].
10693fn predict_u8(
10694 reference: &[u16],
10695 stride: usize,
10696 ref_width: usize,
10697 ref_height: usize,
10698 (x, y): (usize, usize),
10699 side: usize,
10700 mv: (i32, i32),
10701 luma: bool,
10702 fctx: &crate::decode::FrameCtx,
10703) -> Vec<u8> {
10704 let mut prediction = vec![0u16; side * side];
10705 mc::predict(
10706 reference,
10707 stride,
10708 ref_width,
10709 ref_height,
10710 mv_to_q4(x, mv.1, luma),
10711 mv_to_q4(y, mv.0, luma),
10712 side,
10713 side,
10714 &mut prediction,
10715 fctx,
10716 );
10717 prediction.iter().map(|&v| v as u8).collect()
10718}
10719
10720/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
10721/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
10722/// references predict into the `CONV_BUF` intermediate domain and are blended
10723/// at the simple-average split `(8, 8)`, the same path (and so the same
10724/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
10725fn predict_compound_u8(
10726 ref0: (&[u16], usize, usize, usize),
10727 ref1: (&[u16], usize, usize, usize),
10728 (x, y): (usize, usize),
10729 side: usize,
10730 (mv0, mv1): ((i32, i32), (i32, i32)),
10731 luma: bool,
10732 fctx: &crate::decode::FrameCtx,
10733) -> Vec<u8> {
10734 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
10735 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
10736 mc::predict_compound_intermediate(
10737 r.0,
10738 r.1,
10739 r.2,
10740 r.3,
10741 mv_to_q4(x, mv.1, luma),
10742 mv_to_q4(y, mv.0, luma),
10743 mc::REF_NO_SCALE,
10744 side,
10745 side,
10746 fctx.interp_filter.get(),
10747 fctx.interp_filter.get(),
10748 dst,
10749 fctx,
10750 );
10751 }
10752 let mut blended = vec![0u16; side * side];
10753 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
10754 blended.iter().map(|&v| v as u8).collect()
10755}
10756
10757/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
10758/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
10759/// one motion vector where the four 64x64 roots below spend four of each.
10760///
10761/// SKIP only (`residual: false`): a 128x128 block's residual is four
10762/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
10763/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
10764/// path for -- offering one here would price a block
10765/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
10766/// the same reason: the compound arm at this size is untested against the
10767/// writer's own `write_compound_block` window.
10768///
10769/// Only a root whose whole 128x128 lies inside the true frame AND inside
10770/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
10771/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
10772/// block would have to be ranked over its inside part alone.
10773///
10774/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
10775/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
10776/// against the four superblocks plus the SPLIT symbol.
10777#[allow(clippy::too_many_arguments)]
10778fn search_root_128(
10779 luma: &mut Plane,
10780 chroma: &mut [Plane; 2],
10781 grid: &crate::mvstack::MiGrid,
10782 (root_r, root_c): (usize, usize),
10783 // The 32x32-block grid this tile's `blocks` vector is indexed on.
10784 (rows, cols): (usize, usize),
10785 // The frame's own mode-info grid, which bounds the root.
10786 (mi_cols, mi_rows): (u32, u32),
10787 search: Search<'_>,
10788 tpl_factors: &Option<Vec<f64>>,
10789 sb_q: Option<&Vec<u8>>,
10790 sb_cols: usize,
10791 tpl_cells_x: usize,
10792 base_q_idx: u8,
10793 // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
10794 // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
10795 dq_res: i32,
10796 reference: &Picture,
10797 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
10798 // built by the caller off the same grid the tile writer rebuilds its
10799 // stack from (empty unless the frame carries `reference_select` and
10800 // [`b128_compound`] is on).
10801 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10802 fctx: &crate::decode::FrameCtx,
10803) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
10804 const SIDE: usize = SUPERBLOCK * 2;
10805 const SIDE_MI: usize = SIDE / 4;
10806 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10807 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10808 if root_r * 2 + 3 >= rows
10809 || root_c * 2 + 3 >= cols
10810 || (mi_row + SIDE_MI) as u32 > mi_rows
10811 || (mi_col + SIDE_MI) as u32 > mi_cols
10812 || x128 + SIDE > luma.true_width
10813 || y128 + SIDE > luma.true_height
10814 {
10815 return None;
10816 }
10817 // One lambda for the whole root, the mean of what its four superblocks
10818 // would each be searched at -- the 128-vs-four comparison weighs one cost
10819 // against four, so both sides have to be priced at the same lambda (the
10820 // same rule the 64 root's own mean-of-sixteen tpl cells follows).
10821 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10822 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10823 (None, Some(f)) => {
10824 let mean = (0..16)
10825 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10826 .sum::<f64>()
10827 / 16.0;
10828 search.lambda * mean
10829 }
10830 (None, None) => search.lambda,
10831 };
10832 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10833 .iter()
10834 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10835 .sum::<f64>()
10836 / 4.0;
10837 // The qindex this root is really quantized at: the delta_q unit is the
10838 // 128 superblock, so the root's own top-left cell is the one coded
10839 // (lane-b128m), and the residual arm below has to quantize at exactly it.
10840 let root_search = Search {
10841 lambda,
10842 ..match sb_q {
10843 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10844 None => search,
10845 }
10846 };
10847 let stack = find_mv_stack(
10848 grid,
10849 mi_row,
10850 mi_col,
10851 SIDE_MI,
10852 SIDE_MI,
10853 LAST_FRAME,
10854 mi_cols as usize,
10855 mi_rows as usize,
10856 );
10857 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10858 let found = search_skip_64(
10859 luma,
10860 chroma,
10861 (x128, y128),
10862 (SIDE, SIDE),
10863 &root_search,
10864 false,
10865 reference,
10866 &stack,
10867 compound,
10868 fctx,
10869 );
10870 let (mut cost, mut block) = found?;
10871 if block.inter.is_some_and(|i| i.ref1.is_some()) {
10872 B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10873 }
10874 // lane-b128r: the same prediction with a REAL residual, priced against
10875 // the skip arm the search just committed to the planes (which IS the
10876 // winner's prediction, sample for sample). The block's residual is four
10877 // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
10878 // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
10879 // sides the forward network already reaches, never as one 128-point
10880 // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
10881 //
10882 // The four `txfm_partition` symbols the writer codes for them are not
10883 // priced, exactly as the 64 root does not price its own (their contexts
10884 // are only known at write time); at four symbols a root this is under a
10885 // bit against residuals of hundreds.
10886 if b128_residual() && block.skip {
10887 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10888 // only its top-left corner), packed per plane into one 64-wide grid
10889 // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
10890 // `write_inter_block_128` slices back out in the same chunk order.
10891 let mut packed = [
10892 vec![0i32; 64 * 64],
10893 vec![0i32; 64 * 64],
10894 vec![0i32; 64 * 64],
10895 ];
10896 let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
10897 let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
10898 for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
10899 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10900 let (cx, cy) = (px / 2, py / 2);
10901 let half = SUPERBLOCK / 2;
10902 let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
10903 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10904 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10905 sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
10906 + chroma[0].block_sse(cx, cy, half, &pred_u)
10907 + chroma[1].block_sse(cx, cy, half, &pred_v);
10908 let trials = [
10909 luma.code_from_prediction(
10910 px,
10911 py,
10912 SUPERBLOCK,
10913 &pred_y,
10914 false,
10915 root_search.base_q_idx,
10916 root_search.deadzone,
10917 TxbSet::Luma64,
10918 ),
10919 chroma[0].code_from_prediction(
10920 cx,
10921 cy,
10922 half,
10923 &pred_u,
10924 false,
10925 root_search.base_q_idx,
10926 root_search.deadzone,
10927 TxbSet::Chroma32,
10928 ),
10929 chroma[1].code_from_prediction(
10930 cx,
10931 cy,
10932 half,
10933 &pred_v,
10934 false,
10935 root_search.base_q_idx,
10936 root_search.deadzone,
10937 TxbSet::Chroma32,
10938 ),
10939 ];
10940 for (plane, trial) in trials.iter().enumerate() {
10941 sse_res += trial.sse;
10942 coeff_bits += trial.bits;
10943 for row in 0..32 {
10944 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10945 .copy_from_slice(&trial.levels[row * 32..][..32]);
10946 }
10947 }
10948 chunks.push(((cr, cc), trials));
10949 }
10950 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
10951 // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
10952 // coefficients.
10953 let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
10954 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10955 if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
10956 B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10957 for ((cr, cc), trials) in &chunks {
10958 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10959 let half = SUPERBLOCK / 2;
10960 luma.commit(px, py, SUPERBLOCK, &trials[0]);
10961 chroma[0].commit(px / 2, py / 2, half, &trials[1]);
10962 chroma[1].commit(px / 2, py / 2, half, &trials[2]);
10963 }
10964 cost = res_cost;
10965 block.skip = false;
10966 block.tx_depth = 0;
10967 block.luma_tx_types = Vec::new();
10968 block.luma = coeffs(&packed[0], 64);
10969 block.u = coeffs(&packed[1], 64);
10970 block.v = coeffs(&packed[2], 64);
10971 }
10972 }
10973 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10974 restore(luma, chroma, (x128, y128), SIDE, &base);
10975 // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
10976 // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
10977 // residual arm above codes it like every other block does.
10978 let dq = if block.skip {
10979 0.0
10980 } else {
10981 delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
10982 };
10983 Some((
10984 cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
10985 lambda,
10986 block,
10987 after,
10988 ))
10989}
10990
10991/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
10992/// arm the caller's [`search_skip_64`] just committed to the planes (which
10993/// IS the winner's prediction, sample for sample -- the same rule
10994/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
10995/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
10996/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
10997/// each trial at sides the forward network already reaches, never a
10998/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
10999/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
11000///
11001/// The depth-0 `txfm_partition` symbols the writer codes for the units are
11002/// not priced, exactly as [`search_root_128`] does not price its four (their
11003/// contexts are only known at write time); at two symbols a half this is
11004/// under a bit against residuals of hundreds. On a win (or under the witness
11005/// force) the trials are committed to the planes, `block` is flipped to
11006/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
11007/// slices back out, and the new cost is returned; otherwise `cost` passes
11008/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
11009#[allow(clippy::too_many_arguments)]
11010fn search_rect_residual(
11011 luma: &mut Plane,
11012 chroma: &mut [Plane; 2],
11013 // The piece's own top-left, in luma samples.
11014 (px, py): (usize, usize),
11015 // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
11016 (w, h): (usize, usize),
11017 cost: f64,
11018 lambda: f64,
11019 search: &Search<'_>,
11020 // The piece's own mv stack, for the skip symbol's cost either way.
11021 stack: &crate::mvstack::MvStack,
11022 block: &mut BlockCoeffs,
11023) -> f64 {
11024 /// The 64x64 "mu" chunk side, luma; chroma halves it.
11025 const MU: usize = SUPERBLOCK;
11026 let chunks: [(usize, usize); 2] = match (w, h) {
11027 (128, 64) => [(0, 0), (0, 1)],
11028 (64, 128) => [(0, 0), (1, 0)],
11029 _ => [(0, 0), (0, 0)],
11030 };
11031 let n = if w.max(h) > MU { 2 } else { 1 };
11032 // Every unit's coded level grid is 32x32 (a 64-point transform codes
11033 // only its top-left corner), packed per plane into one 64-wide grid with
11034 // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
11035 // back out in the same chunk order.
11036 let mut packed = [
11037 vec![0i32; 64 * 64],
11038 vec![0i32; 64 * 64],
11039 vec![0i32; 64 * 64],
11040 ];
11041 let mut sse_skip = 0.0f64;
11042 let mut sse_res = 0.0f64;
11043 let mut coeff_bits = 0.0f64;
11044 let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
11045 for &(cr, cc) in &chunks[..n] {
11046 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
11047 let (cx, cy) = (cxx / 2, cyy / 2);
11048 let half = MU / 2;
11049 let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
11050 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
11051 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
11052 sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
11053 + chroma[0].block_sse(cx, cy, half, &pred_u)
11054 + chroma[1].block_sse(cx, cy, half, &pred_v);
11055 let trials = [
11056 luma.code_from_prediction(
11057 cxx,
11058 cyy,
11059 MU,
11060 &pred_y,
11061 false,
11062 search.base_q_idx,
11063 search.deadzone,
11064 TxbSet::Luma64,
11065 ),
11066 chroma[0].code_from_prediction(
11067 cx,
11068 cy,
11069 half,
11070 &pred_u,
11071 false,
11072 search.base_q_idx,
11073 search.deadzone,
11074 TxbSet::Chroma32,
11075 ),
11076 chroma[1].code_from_prediction(
11077 cx,
11078 cy,
11079 half,
11080 &pred_v,
11081 false,
11082 search.base_q_idx,
11083 search.deadzone,
11084 TxbSet::Chroma32,
11085 ),
11086 ];
11087 for (plane, trial) in trials.iter().enumerate() {
11088 sse_res += trial.sse;
11089 coeff_bits += trial.bits;
11090 for row in 0..32 {
11091 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
11092 .copy_from_slice(&trial.levels[row * 32..][..32]);
11093 }
11094 }
11095 trials_per_chunk.push(trials);
11096 }
11097 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
11098 // pays the same syntax with `skip` coded 0 instead of 1, plus its
11099 // coefficients.
11100 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
11101 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
11102 if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
11103 for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
11104 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
11105 let (cx, cy) = (cxx / 2, cyy / 2);
11106 let half = MU / 2;
11107 luma.commit(cxx, cyy, MU, &trials[0]);
11108 chroma[0].commit(cx, cy, half, &trials[1]);
11109 chroma[1].commit(cx, cy, half, &trials[2]);
11110 }
11111 block.skip = false;
11112 block.tx_depth = 0;
11113 block.luma_tx_types = Vec::new();
11114 block.luma = coeffs(&packed[0], 64);
11115 block.u = coeffs(&packed[1], 64);
11116 block.v = coeffs(&packed[2], 64);
11117 B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11118 res_cost
11119 } else {
11120 cost
11121 }
11122}
11123
11124/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
11125/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
11126/// shipped NONE machinery halved. Skip-only by default, single reference or
11127/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
11128/// ([`search_rect_residual`]) -- exactly what
11129/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
11130/// reads at `sb128_rect`.
11131///
11132/// The FIRST half is published into `grid` before the second is searched --
11133/// the writer publishes it too, so a second half searched against the stale
11134/// grid would be priced (and its mv predicted) off a stack the decoder never
11135/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
11136/// both planes are put back before returning; the caller re-applies the
11137/// winner.
11138///
11139/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
11140/// carrying the root's own partition symbol so it ranks against
11141/// [`search_root_128`] and against the four superblocks below.
11142#[allow(clippy::too_many_arguments)]
11143fn search_root_128_rect(
11144 luma: &mut Plane,
11145 chroma: &mut [Plane; 2],
11146 grid: &mut crate::mvstack::MiGrid,
11147 (root_r, root_c): (usize, usize),
11148 (rows, cols): (usize, usize),
11149 (mi_cols, mi_rows): (u32, u32),
11150 search: Search<'_>,
11151 tpl_factors: &Option<Vec<f64>>,
11152 sb_q: Option<&Vec<u8>>,
11153 sb_cols: usize,
11154 tpl_cells_x: usize,
11155 base_q_idx: u8,
11156 // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
11157 dq_res: i32,
11158 reference: &Picture,
11159 // The `LAST` + extra-reference pairs offered at this root; only the
11160 // reference and its picture are read here, since each HALF derives its
11161 // own compound stack at its own rectangular window.
11162 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11163 horz: bool,
11164 fctx: &crate::decode::FrameCtx,
11165) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
11166 const SIDE: usize = SUPERBLOCK * 2;
11167 const SIDE_MI: usize = SIDE / 4;
11168 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
11169 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
11170 if root_r * 2 + 3 >= rows
11171 || root_c * 2 + 3 >= cols
11172 || (mi_row + SIDE_MI) as u32 > mi_rows
11173 || (mi_col + SIDE_MI) as u32 > mi_cols
11174 || x128 + SIDE > luma.true_width
11175 || y128 + SIDE > luma.true_height
11176 {
11177 return None;
11178 }
11179 // The root's own lambda, the mean of its four superblocks' -- the same
11180 // one [`search_root_128`] prices with, so the three root candidates and
11181 // the four-superblock arm are all comparable.
11182 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
11183 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
11184 (None, Some(f)) => {
11185 let mean = (0..16)
11186 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
11187 .sum::<f64>()
11188 / 16.0;
11189 search.lambda * mean
11190 }
11191 (None, None) => search.lambda,
11192 };
11193 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
11194 .iter()
11195 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
11196 .sum::<f64>()
11197 / 4.0;
11198 let root_search = Search {
11199 lambda,
11200 ..match sb_q {
11201 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
11202 None => search,
11203 }
11204 };
11205 let (w, h) = if horz {
11206 (SIDE, SUPERBLOCK)
11207 } else {
11208 (SUPERBLOCK, SIDE)
11209 };
11210 let (w_mi, h_mi) = (w / 4, h / 4);
11211 let base = snapshot(luma, chroma, (x128, y128), SIDE);
11212 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
11213 let mut cost = 0.0f64;
11214 let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
11215 for i in 0..2usize {
11216 let (mr, mc) = if horz {
11217 (mi_row + i * 16, mi_col)
11218 } else {
11219 (mi_row, mi_col + i * 16)
11220 };
11221 let stack = find_mv_stack(
11222 grid,
11223 mr,
11224 mc,
11225 w_mi,
11226 h_mi,
11227 LAST_FRAME,
11228 mi_cols as usize,
11229 mi_rows as usize,
11230 );
11231 let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
11232 .iter()
11233 .map(|&(r, pic, _)| {
11234 (
11235 r,
11236 pic,
11237 crate::mvstack::find_mv_stack_compound(
11238 grid,
11239 mr,
11240 mc,
11241 w_mi,
11242 h_mi,
11243 (LAST_FRAME, r),
11244 mi_cols as usize,
11245 mi_rows as usize,
11246 grid.sign_bias_table(),
11247 &[(0, 0); 7],
11248 None,
11249 ),
11250 )
11251 })
11252 .collect();
11253 let found = search_skip_64(
11254 luma,
11255 chroma,
11256 (mc * 4, mr * 4),
11257 (w, h),
11258 &root_search,
11259 false,
11260 reference,
11261 &stack,
11262 &half_compound,
11263 fctx,
11264 );
11265 match found {
11266 Some((mut c, mut block)) => {
11267 // lane-rectres: the same prediction with a REAL residual,
11268 // priced against the skip arm the search just committed to
11269 // the planes -- two 64x64 mu chunks for a half.
11270 if rectres() && block.skip {
11271 c = search_rect_residual(
11272 luma,
11273 chroma,
11274 (mc * 4, mr * 4),
11275 (w, h),
11276 c,
11277 root_search.lambda,
11278 &root_search,
11279 &stack,
11280 &mut block,
11281 );
11282 }
11283 cost += c;
11284 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
11285 halves.push(block);
11286 }
11287 None => {
11288 restore(luma, chroma, (x128, y128), SIDE, &base);
11289 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11290 return None;
11291 }
11292 }
11293 }
11294 let after = snapshot(luma, chroma, (x128, y128), SIDE);
11295 restore(luma, chroma, (x128, y128), SIDE, &base);
11296 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11297 let symbol = if horz { 1 } else { 2 };
11298 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
11299 // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
11300 // codes the delta_q group whether it is skipped or not
11301 // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
11302 // half is at a non-origin mi and codes none.
11303 let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
11304 Some((
11305 cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
11306 lambda,
11307 [b0, b1],
11308 after,
11309 ))
11310}
11311
11312/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
11313/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
11314/// decoder's own). Each piece is priced through the same `search_skip_64`
11315/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
11316/// into `grid` before the next is searched -- the writer publishes it too, so
11317/// a later piece searched against a stale grid would be priced (and its mv
11318/// predicted) off a stack the decoder never derives (class
11319/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
11320/// are put back before returning; the caller re-applies the winner.
11321///
11322/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
11323/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
11324/// libaom's own AB shapes earn their keep.
11325///
11326/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
11327/// already carrying the root's own partition symbol so it ranks against the
11328/// other root candidates and against the four superblocks below.
11329#[allow(clippy::too_many_arguments)]
11330fn search_root_128_ab(
11331 luma: &mut Plane,
11332 chroma: &mut [Plane; 2],
11333 grid: &mut crate::mvstack::MiGrid,
11334 (root_r, root_c): (usize, usize),
11335 (rows, cols): (usize, usize),
11336 (mi_cols, mi_rows): (u32, u32),
11337 search: Search<'_>,
11338 tpl_factors: &Option<Vec<f64>>,
11339 sb_q: Option<&Vec<u8>>,
11340 sb_cols: usize,
11341 tpl_cells_x: usize,
11342 base_q_idx: u8,
11343 reference: &Picture,
11344 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11345 // The partition symbol, 4..=7.
11346 symbol: usize,
11347 fctx: &crate::decode::FrameCtx,
11348) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
11349 const SIDE: usize = SUPERBLOCK * 2;
11350 const SIDE_MI: usize = SIDE / 4;
11351 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
11352 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
11353 if root_r * 2 + 3 >= rows
11354 || root_c * 2 + 3 >= cols
11355 || (mi_row + SIDE_MI) as u32 > mi_rows
11356 || (mi_col + SIDE_MI) as u32 > mi_cols
11357 || x128 + SIDE > luma.true_width
11358 || y128 + SIDE > luma.true_height
11359 {
11360 return None;
11361 }
11362 // The root's own lambda, the mean of its four superblocks' -- the same one
11363 // [`search_root_128`] prices with, so every root candidate and the
11364 // four-superblock arm are comparable.
11365 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
11366 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
11367 (None, Some(f)) => {
11368 let mean = (0..16)
11369 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
11370 .sum::<f64>()
11371 / 16.0;
11372 search.lambda * mean
11373 }
11374 (None, None) => search.lambda,
11375 };
11376 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
11377 .iter()
11378 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
11379 .sum::<f64>()
11380 / 4.0;
11381 let root_search = Search {
11382 lambda,
11383 ..match sb_q {
11384 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
11385 None => search,
11386 }
11387 };
11388 let base = snapshot(luma, chroma, (x128, y128), SIDE);
11389 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
11390 let mut cost = 0.0f64;
11391 let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
11392 for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
11393 let (w_mi, h_mi) = (w / 4, h / 4);
11394 let stack = find_mv_stack(
11395 grid,
11396 mr,
11397 mc,
11398 w_mi,
11399 h_mi,
11400 LAST_FRAME,
11401 mi_cols as usize,
11402 mi_rows as usize,
11403 );
11404 let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
11405 .iter()
11406 .map(|&(r, pic, _)| {
11407 (
11408 r,
11409 pic,
11410 crate::mvstack::find_mv_stack_compound(
11411 grid,
11412 mr,
11413 mc,
11414 w_mi,
11415 h_mi,
11416 (LAST_FRAME, r),
11417 mi_cols as usize,
11418 mi_rows as usize,
11419 grid.sign_bias_table(),
11420 &[(0, 0); 7],
11421 None,
11422 ),
11423 )
11424 })
11425 .collect();
11426 let found = search_skip_64(
11427 luma,
11428 chroma,
11429 (mc * 4, mr * 4),
11430 (w, h),
11431 &root_search,
11432 false,
11433 reference,
11434 &stack,
11435 &piece_compound,
11436 fctx,
11437 );
11438 match found {
11439 Some((mut c, mut block)) => {
11440 // lane-rectres: the same prediction with a REAL residual,
11441 // priced against the skip arm the search just committed to
11442 // the planes -- one mu chunk for a 64x64 square, two for a
11443 // half. The 64x64 squares are where libaom's own AB shapes
11444 // earn their keep.
11445 if rectres() && block.skip {
11446 c = search_rect_residual(
11447 luma,
11448 chroma,
11449 (mc * 4, mr * 4),
11450 (w, h),
11451 c,
11452 root_search.lambda,
11453 &root_search,
11454 &stack,
11455 &mut block,
11456 );
11457 }
11458 cost += c;
11459 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
11460 pieces.push(block);
11461 }
11462 None => {
11463 restore(luma, chroma, (x128, y128), SIDE, &base);
11464 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11465 return None;
11466 }
11467 }
11468 }
11469 let after = snapshot(luma, chroma, (x128, y128), SIDE);
11470 restore(luma, chroma, (x128, y128), SIDE, &base);
11471 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11472 let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
11473 Some((
11474 cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
11475 lambda,
11476 [b0, b1, b2],
11477 after,
11478 ))
11479}
11480
11481/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
11482/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
11483/// SKIP, priced through the same `symbol_bits` path every other candidate
11484/// uses. The winner's prediction is committed to the planes (it IS the
11485/// reconstruction -- a skip block has no residual); the caller restores them
11486/// if the four quadrants come out cheaper.
11487///
11488/// `None` when no candidate could be coded at all (a `NEWMV` residual the
11489/// writer cannot name is simply not offered, and the other modes always are,
11490/// so this only happens if every candidate is refused).
11491fn search_skip_64(
11492 luma: &mut Plane,
11493 chroma: &mut [Plane; 2],
11494 (x, y): (usize, usize),
11495 // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
11496 // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
11497 // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
11498 // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
11499 // side (one square when it is square, two otherwise), and the residual
11500 // arm is only ever asked for at 64 -- a 128 block's residual is four
11501 // TX_64X64 units the writer has no path for.
11502 (bw, bh): (usize, usize),
11503 search: &Search,
11504 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
11505 // screen content -- see that function's doc).
11506 residual: bool,
11507 reference: &Picture,
11508 stack: &MvStack,
11509 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
11510 // superblock's 16x16-mi window, built off the same grid the tile writer
11511 // rebuilds it from (empty unless the frame carries `reference_select`).
11512 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11513 fctx: &crate::decode::FrameCtx,
11514) -> Option<(f64, BlockCoeffs)> {
11515 debug_assert!(
11516 (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
11517 "only a 64 root has a residual arm"
11518 );
11519 // The square units every trial below is taken on: the block itself when
11520 // it is square, its two halves otherwise. Luma first (in raster order),
11521 // then each chroma plane over the same tiling at half the side -- which is
11522 // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
11523 let sq = bw.min(bh);
11524 let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
11525 .flat_map(|plane| {
11526 let (ox, oy, s) = if plane == 0 {
11527 (x, y, sq)
11528 } else {
11529 (x / 2, y / 2, sq / 2)
11530 };
11531 (0..bh / sq).flat_map(move |j| {
11532 (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
11533 })
11534 })
11535 .collect();
11536 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11537 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11538 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11539 // What every candidate pays whatever its vector: `skip` coded 1, then
11540 // `is_inter` coded 1, then the LAST chain above.
11541 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
11542 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
11543 ref1: None,
11544 mv1: (0, 0),
11545 ref_frame: crate::mvstack::LAST_FRAME,
11546 mode,
11547 mv,
11548 ref_mv_idx,
11549 };
11550 let mut cands: Vec<(f64, InterInfo)> = vec![
11551 (
11552 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11553 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
11554 ),
11555 (
11556 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11557 info_of(InterMode::GlobalMv, (0, 0), 0),
11558 ),
11559 ];
11560 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11561 for idx in 1..=2usize {
11562 if let Some(e) = stack.entries.get(idx) {
11563 cands.push((
11564 near_bits + drl_bits_for(stack, 1, idx),
11565 info_of(InterMode::NearMv, e.mv, idx as u8),
11566 ));
11567 }
11568 }
11569 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
11570 // candidate below to pair with the second reference's NEAREST half.
11571 let mut last_new_mv: Option<(i32, i32)> = None;
11572 if leaf_new_mv() {
11573 let source_block = luma.source_block_rect(x, y, bw, bh);
11574 let (seeds, seed_n) = mv_seeds(stack);
11575 let found = motion::search(
11576 &reference.y,
11577 reference.width,
11578 luma.true_width,
11579 luma.true_height,
11580 &source_block,
11581 x,
11582 y,
11583 bw,
11584 bh,
11585 stack.pred_mv,
11586 &seeds[..seed_n],
11587 search.lambda,
11588 fctx,
11589 1,
11590 );
11591 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
11592 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
11593 last_new_mv = Some(mv);
11594 cands.push((
11595 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
11596 info_of(InterMode::NewMv, mv, ref_mv_idx),
11597 ));
11598 }
11599 }
11600
11601 let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
11602 for (bits, info) in cands {
11603 let trials: Vec<Trial> = units
11604 .iter()
11605 .map(|&(plane, px, py, s, is_luma)| {
11606 let (samples, stride, w, h) = match plane {
11607 0 => (
11608 &reference.y,
11609 reference.width,
11610 luma.true_width,
11611 luma.true_height,
11612 ),
11613 1 => (
11614 &reference.u,
11615 reference.width / 2,
11616 chroma[0].true_width,
11617 chroma[0].true_height,
11618 ),
11619 _ => (
11620 &reference.v,
11621 reference.width / 2,
11622 chroma[1].true_width,
11623 chroma[1].true_height,
11624 ),
11625 };
11626 let prediction =
11627 predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
11628 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
11629 // `skip` true: the trial is the prediction itself plus its SSE,
11630 // so no transform of any size is involved (the reason a 64x64
11631 // root can be coded at all before a forward TX_64X64 exists).
11632 target.code_from_prediction(
11633 px,
11634 py,
11635 s,
11636 &prediction,
11637 true,
11638 search.base_q_idx,
11639 search.deadzone,
11640 TxbSet::Luma32Inter,
11641 )
11642 })
11643 .collect();
11644 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
11645 if best.as_ref().is_none_or(|b| cost < b.0) {
11646 best = Some((cost, fixed + bits, info, trials));
11647 }
11648 }
11649
11650 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
11651 // superblock can form without a second motion search ([`b64_compound`]),
11652 // priced through the same `symbol_bits` path -- `fixed` minus the single
11653 // reference's tree, plus the pair tree and the compound mode.
11654 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
11655 let (ref1, g) = (*ref1, *g);
11656 // The whole `comp_mode` + reference-pair tree at the writer's own
11657 // contexts, for THIS pair (lane-ctx).
11658 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
11659 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
11660 let mode_bits_of =
11661 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
11662 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
11663 ref1: Some(ref1),
11664 mv1: mvs.1,
11665 ref_frame: crate::mvstack::LAST_FRAME,
11666 mode,
11667 mv: mvs.0,
11668 ref_mv_idx: 0,
11669 };
11670 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
11671 (
11672 cstack.nearest_mv,
11673 mode_bits_of(0),
11674 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
11675 ),
11676 (
11677 ((0, 0), (0, 0)),
11678 mode_bits_of(6),
11679 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
11680 ),
11681 ];
11682 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
11683 // above, its residual priced against compound stack entry 0 -- what
11684 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
11685 let cbase = cstack
11686 .entries
11687 .first()
11688 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
11689 if let Some(new_mv) = last_new_mv
11690 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
11691 {
11692 let mvs = (new_mv, cstack.nearest_mv.1);
11693 ccands.push((
11694 mvs,
11695 mode_bits_of(3) + b0,
11696 compound_info(InterMode::NewNearestMv, mvs),
11697 ));
11698 }
11699 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
11700 ccands.dedup_by_key(|c| c.0);
11701 for (mvs, bits, info) in ccands {
11702 let trials: Vec<Trial> = units
11703 .iter()
11704 .map(|&(plane, px, py, s, is_luma)| {
11705 let (r0, r1) = match plane {
11706 0 => (
11707 (
11708 reference.y.as_slice(),
11709 reference.width,
11710 luma.true_width,
11711 luma.true_height,
11712 ),
11713 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11714 ),
11715 1 => (
11716 (
11717 reference.u.as_slice(),
11718 reference.width / 2,
11719 chroma[0].true_width,
11720 chroma[0].true_height,
11721 ),
11722 (
11723 g.u.as_slice(),
11724 g.width / 2,
11725 chroma[0].true_width,
11726 chroma[0].true_height,
11727 ),
11728 ),
11729 _ => (
11730 (
11731 reference.v.as_slice(),
11732 reference.width / 2,
11733 chroma[1].true_width,
11734 chroma[1].true_height,
11735 ),
11736 (
11737 g.v.as_slice(),
11738 g.width / 2,
11739 chroma[1].true_width,
11740 chroma[1].true_height,
11741 ),
11742 ),
11743 };
11744 let prediction = predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
11745 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
11746 target.code_from_prediction(
11747 px,
11748 py,
11749 s,
11750 &prediction,
11751 true,
11752 search.base_q_idx,
11753 search.deadzone,
11754 TxbSet::Luma32Inter,
11755 )
11756 })
11757 .collect();
11758 let syntax = fixed - ref_bits + bits;
11759 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
11760 if best.as_ref().is_none_or(|b| cost < b.0) {
11761 best = Some((cost, syntax, info, trials));
11762 }
11763 }
11764 }
11765
11766 let (skip_cost, syntax, info, skip_trials) = best?;
11767
11768 // The winner's prediction coded with a REAL residual (lane-tx64): one
11769 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
11770 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
11771 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
11772 // the skip arm already chose is re-coded: the prediction with the lowest
11773 // SSE is also the cheapest residual to code, and a second 64x64 motion
11774 // search per superblock is the wall this root was taken to SAVE.
11775 //
11776 // Priced against the skip arm through the same `symbol_bits` path, so the
11777 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
11778 // arm charges 0 instead and adds its three planes' coefficient bits.
11779 let mut chosen = (skip_cost, true, skip_trials);
11780 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
11781 // into the plane, so the tail below does not commit over its units.
11782 let mut luma_committed = false;
11783 // The residual arm's luma levels and the `txfm_split` depth the writer
11784 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
11785 // four TX_32X32 units in 64x64 ones.
11786 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
11787 if residual {
11788 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
11789 // Square by construction (the `debug_assert` above), so `units` is
11790 // one entry per plane and `chosen.2[plane]` is that plane's trial.
11791 let residual_trials = [0usize, 1, 2].map(|plane| {
11792 let (target, px, py, s) = if plane == 0 {
11793 (&*luma, x, y, bw)
11794 } else {
11795 (&chroma[plane - 1], x / 2, y / 2, bw / 2)
11796 };
11797 target.code_from_prediction(
11798 px,
11799 py,
11800 s,
11801 &chosen.2[plane].reconstruction,
11802 false,
11803 search.base_q_idx,
11804 search.deadzone,
11805 sets[plane],
11806 )
11807 });
11808 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
11809 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
11810 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
11811 // four TX_32X32 units of `txfm_split = 1`, taken by the same
11812 // `commit_inter_luma` every other inter block's is (it commits the
11813 // winner and hands back the cost it took off the flat arm).
11814 let (levels, depth, gain, tx_types) = if b64_var_tx() {
11815 let second = info.ref1.and_then(|r1| {
11816 compound
11817 .iter()
11818 .find(|(r, _, _)| *r == r1)
11819 .map(|&(_, g, _)| {
11820 (
11821 info.mv1,
11822 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11823 )
11824 })
11825 });
11826 luma_committed = true;
11827 commit_inter_luma(
11828 luma,
11829 (x, y),
11830 bw,
11831 info.mv,
11832 (
11833 &reference.y,
11834 reference.width,
11835 luma.true_width,
11836 luma.true_height,
11837 ),
11838 search,
11839 &residual_trials[0],
11840 false,
11841 second,
11842 fctx,
11843 )
11844 } else {
11845 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
11846 };
11847 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
11848 + search.lambda * (syntax + unskip + coeff_bits)
11849 + gain;
11850 if cost < skip_cost {
11851 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11852 if depth == 1 {
11853 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11854 }
11855 luma_levels = Some((levels, depth, tx_types));
11856 chosen = (cost, false, residual_trials.to_vec());
11857 }
11858 }
11859
11860 let (cost, skip, trials) = chosen;
11861 // `commit_inter_luma` already wrote the residual arm's luma (its four
11862 // split units are not one 64-sided trial); a skip winner overwrites it.
11863 for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
11864 match plane {
11865 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
11866 0 => {}
11867 _ => chroma[plane - 1].commit(px, py, s, trial),
11868 }
11869 }
11870 Some((
11871 cost,
11872 BlockCoeffs {
11873 skip,
11874 inter: Some(info),
11875 // The chroma grids are whole TX_32X32; the luma one is the
11876 // 64-point transform's coded 32x32 corner at depth 0 and the
11877 // whole 64-sided block at depth 1 (lane-b64b).
11878 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
11879 luma_tx_types: match (skip, &luma_levels) {
11880 (false, Some((_, _, types))) => types.clone(),
11881 _ => Vec::new(),
11882 },
11883 luma: match (skip, &luma_levels) {
11884 (true, _) => Vec::new(),
11885 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
11886 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
11887 (false, None) => coeffs(&trials[0].levels, BLOCK),
11888 },
11889 u: if skip {
11890 Vec::new()
11891 } else {
11892 coeffs(&trials[1].levels, bw / 2)
11893 },
11894 v: if skip {
11895 Vec::new()
11896 } else {
11897 coeffs(&trials[2].levels, bw / 2)
11898 },
11899 ..BlockCoeffs::default()
11900 },
11901 ))
11902}
11903
11904fn search_inter_block(
11905 luma: &mut Plane,
11906 chroma: &mut [Plane; 2],
11907 (x, y): (usize, usize),
11908 search: &Search,
11909 mode_bits: &[f64; 13],
11910 reference: &Picture,
11911 stack: &MvStack,
11912 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
11913 // for the whole GOP, with the stack this block derives against it. Only
11914 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
11915 // second motion search would double the wall of the stage that already
11916 // owns most of it.
11917 extra: &[(i8, &Picture, &MvStack)],
11918 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
11919 // the caller off the same MI grid the tile writer will (empty unless the
11920 // frame carries `reference_select`).
11921 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11922 // lane-av1obmc: the mi grid this search's neighbours were published into
11923 // (`record_mi`) and this block's own place in it -- what the OBMC
11924 // candidate's eligibility walk and neighbour plan read, the same state
11925 // the tile writer will read when it codes the `motion_mode` symbol.
11926 grid: &MiGrid,
11927 (mi_row, mi_col): (usize, usize),
11928 (mi_rows, mi_cols): (usize, usize),
11929 fctx: &crate::decode::FrameCtx,
11930) -> (BlockCoeffs, f64) {
11931 // `luma_set` is the INTRA candidates' table; the two inter candidates
11932 // below price their coefficients through `TxbSet::Luma32Inter`, which is
11933 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
11934 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
11935 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
11936 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
11937
11938 // skip / intra_inter symbol costs at a fixed context -- see this
11939 // function's doc comment.
11940 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
11941 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
11942
11943 struct Candidate {
11944 cost: f64,
11945 luma: Trial,
11946 u: Trial,
11947 v: Trial,
11948 mode: u8,
11949 skip: bool,
11950 inter: Option<InterInfo>,
11951 /// The mode/mv syntax this candidate pays for, apart from its
11952 /// residual -- what the OBMC candidate below has to re-pay when it
11953 /// re-prices the winner's prediction.
11954 mode_bits: f64,
11955 }
11956 let mut best: Option<Candidate> = None;
11957 let mut consider = |candidate: Candidate| {
11958 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
11959 best = Some(candidate);
11960 }
11961 };
11962
11963 // The chroma trial an intra candidate prices does not depend on `mode`
11964 // at all -- both planes always code `DC_PRED` here (a coding choice this
11965 // search inherited, not this loop's to second-guess) at the same `reach:
11966 // Reach::none()` -- so it is the same call with the same inputs on every
11967 // one of the thirteen iterations below; run it once and reuse the result
11968 // rather than repeat an already-priced transform/quantize/entropy call
11969 // twelve times for nothing (bit-identical: the value each iteration
11970 // reads back is exactly what it used to recompute).
11971 let u_trial = chroma[0].trial(
11972 At {
11973 x: x / 2,
11974 y: y / 2,
11975 side: BLOCK / 2,
11976 reach: Reach::none(),
11977 set: chroma_set,
11978 },
11979 DC_PRED,
11980 0,
11981 search.base_q_idx,
11982 search.deadzone,
11983 fctx,
11984 );
11985 let v_trial = chroma[1].trial(
11986 At {
11987 x: x / 2,
11988 y: y / 2,
11989 side: BLOCK / 2,
11990 reach: Reach::none(),
11991 set: chroma_set,
11992 },
11993 DC_PRED,
11994 0,
11995 search.base_q_idx,
11996 search.deadzone,
11997 fctx,
11998 );
11999
12000 let intra_modes: Vec<u8> = match search.top_k {
12001 Some(k) if k < search.modes.len() => {
12002 let scored = luma.intra_scores(
12003 At {
12004 x,
12005 y,
12006 side: BLOCK,
12007 reach,
12008 set: luma_set,
12009 },
12010 search.modes,
12011 mode_bits,
12012 search.lambda,
12013 fctx,
12014 );
12015 prune_by_sad(search.modes, scored, k)
12016 }
12017 _ => search.modes.to_vec(),
12018 };
12019 census_add(5, 1);
12020 census_add(
12021 6,
12022 if search.arf_leaf_intra {
12023 intra_modes.len()
12024 } else {
12025 0
12026 },
12027 );
12028 // lane-arfmode: arm 1 drops the whole-32 block's intra candidates at the
12029 // top ARF too -- the probe proved the ARF's intra AREA lives HERE, not at
12030 // the leaves (film A arm 1 vs control byte-identical with the leaf gate
12031 // alone), so "the 32x32 whole keeps intra as the scene-cut hatch" was a
12032 // hatch nothing else was using. Counted once per block.
12033 if search.arf_leaf_intra {
12034 for &mode in &intra_modes {
12035 let luma_trial = luma.trial(
12036 At {
12037 x,
12038 y,
12039 side: BLOCK,
12040 reach,
12041 set: luma_set,
12042 },
12043 mode,
12044 0,
12045 search.base_q_idx,
12046 search.deadzone,
12047 fctx,
12048 );
12049 let u = u_trial.clone();
12050 let v = v_trial.clone();
12051 let cost = luma_trial.sse
12052 + u.sse
12053 + v.sse
12054 + search.lambda
12055 * (luma_trial.bits
12056 + u.bits
12057 + v.bits
12058 + mode_bits[usize::from(mode)]
12059 + skip_bits(false)
12060 + intra_inter_bits(false));
12061 consider(Candidate {
12062 cost,
12063 luma: luma_trial,
12064 u,
12065 v,
12066 mode,
12067 skip: false,
12068 inter: None,
12069 mode_bits: mode_bits[usize::from(mode)],
12070 });
12071 }
12072 } else {
12073 arfmode_hit(0);
12074 }
12075
12076 // The reference frame buffer a spec decoder holds is exactly the true
12077 // (unpadded) coded extent -- a superblock whose partition stops early at
12078 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
12079 // beyond it, so those samples are never part of the decoded picture.
12080 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
12081 // reference sample position clamp), not to this crate's own
12082 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
12083 // here would let a fractional-pel read past the true edge pick up this
12084 // encoder's own uncoded padding instead of the true edge's replicated
12085 // value a decoder computes.
12086 let ref_luma = (
12087 &reference.y,
12088 reference.width,
12089 luma.true_width,
12090 luma.true_height,
12091 );
12092 let ref_u = (
12093 &reference.u,
12094 reference.width / 2,
12095 chroma[0].true_width,
12096 chroma[0].true_height,
12097 );
12098 let ref_v = (
12099 &reference.v,
12100 reference.width / 2,
12101 chroma[1].true_width,
12102 chroma[1].true_height,
12103 );
12104 // Every single-reference mode the writer can code (spec 5.11.24's symbol
12105 // chain, mirrored by `tile::write_inter_mode`), priced with the static
12106 // CDFs at this block's own stack contexts. A candidate is a motion
12107 // vector plus the cheapest syntax that reaches it, so two modes landing
12108 // on the same vector share one set of trials: the added modes cost
12109 // mode-bit arithmetic, not another motion compensation.
12110 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
12111 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
12112 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
12113 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
12114 // the loop cannot reach is never offered below -- every candidate's
12115 // index is one this same loop walks to.
12116 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
12117 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
12118 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
12119 (
12120 stack.nearest_mv,
12121 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
12122 InterInfo {
12123 ref1: None,
12124 mv1: (0, 0),
12125 ref_frame: crate::mvstack::LAST_FRAME,
12126 mode: InterMode::NearestMv,
12127 mv: stack.nearest_mv,
12128 ref_mv_idx: 0,
12129 },
12130 ),
12131 // GLOBALMV is the identity model's zero vector -- this encoder writes
12132 // no `gm_params` -- and the cheapest syntax of the four on the static
12133 // content where that vector is also the right one.
12134 (
12135 (0, 0),
12136 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
12137 InterInfo {
12138 ref1: None,
12139 mv1: (0, 0),
12140 ref_frame: crate::mvstack::LAST_FRAME,
12141 mode: InterMode::GlobalMv,
12142 mv: (0, 0),
12143 ref_mv_idx: 0,
12144 },
12145 ),
12146 ];
12147 let near_bits =
12148 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
12149 for idx in 1..=2usize {
12150 if let Some(e) = stack.entries.get(idx) {
12151 cands.push((
12152 e.mv,
12153 near_bits + drl_bits(1, idx),
12154 InterInfo {
12155 ref1: None,
12156 mv1: (0, 0),
12157 ref_frame: crate::mvstack::LAST_FRAME,
12158 mode: InterMode::NearMv,
12159 mv: e.mv,
12160 ref_mv_idx: idx as u8,
12161 },
12162 ));
12163 }
12164 }
12165
12166 let source_block = luma.source_block(x, y, BLOCK);
12167 let (seeds, seed_n) = mv_seeds(stack);
12168 #[cfg(test)]
12169 let t = stage_start();
12170 let found = motion::search(
12171 ref_luma.0,
12172 ref_luma.1,
12173 ref_luma.2,
12174 ref_luma.3,
12175 &source_block,
12176 x,
12177 y,
12178 BLOCK,
12179 BLOCK,
12180 stack.pred_mv,
12181 &seeds[..seed_n],
12182 search.lambda,
12183 fctx,
12184 1,
12185 );
12186 #[cfg(test)]
12187 stage_since(0, t);
12188 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
12189 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
12190 // costs, for the census below (`None` when the writer cannot name it).
12191 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
12192 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
12193 // the same vector costs a different residual from each: take the index
12194 // whose residual plus DRL bits is cheapest, not entry 0 by default.
12195 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
12196 newmv_syntax = Some((mv, bits));
12197 cands.push((
12198 mv,
12199 last_ref_bits
12200 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
12201 + bits
12202 + mv_rate_surcharge(bits),
12203 InterInfo {
12204 ref1: None,
12205 mv1: (0, 0),
12206 ref_frame: crate::mvstack::LAST_FRAME,
12207 mode: InterMode::NewMv,
12208 mv,
12209 ref_mv_idx,
12210 },
12211 ));
12212 }
12213
12214 // Each extra reference's own `NEWMV` vector, for the compound
12215 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
12216 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
12217 for &(ref_frame, g, gstack) in extra {
12218 let g_ref_bits = single_ref_bits(ref_frame, gstack);
12219 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
12220 cands.push((
12221 gstack.nearest_mv,
12222 g_ref_bits
12223 + g_not_new
12224 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
12225 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
12226 InterInfo {
12227 ref1: None,
12228 mv1: (0, 0),
12229 ref_frame,
12230 mode: InterMode::NearestMv,
12231 mv: gstack.nearest_mv,
12232 ref_mv_idx: 0,
12233 },
12234 ));
12235 cands.push((
12236 (0, 0),
12237 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
12238 InterInfo {
12239 ref1: None,
12240 mv1: (0, 0),
12241 ref_frame,
12242 mode: InterMode::GlobalMv,
12243 mv: (0, 0),
12244 ref_mv_idx: 0,
12245 },
12246 ));
12247 // A motion search of this reference's own: without it, GOLDEN/ALTREF
12248 // can only be coded at a vector some neighbour already found, which
12249 // is why they carried a third of the inter blocks at their two
12250 // search-free modes alone.
12251 // The search is skipped when this reference's own NEARESTMV already
12252 // prices out `margin` times better than LAST's best vector does --
12253 // one candidate evaluation (`motion::cost_at`) standing in for a
12254 // whole search of ~50.
12255 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
12256 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
12257 // neighbour already found, which is how GOLDEN/ALTREF were offered
12258 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
12259 // own value from the second motion search's wall.
12260 let searched =
12261 extra_ref_new_mv() && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
12262 let margin = extra_new_skip_margin();
12263 if searched {
12264 newmv_census_global(0);
12265 }
12266 let skip_search = searched
12267 && margin > 0.0
12268 && motion::cost_at(
12269 &g.y,
12270 g.width,
12271 luma.true_width,
12272 luma.true_height,
12273 &source_block,
12274 x,
12275 y,
12276 BLOCK,
12277 BLOCK,
12278 gstack.nearest_mv,
12279 gstack.pred_mv,
12280 search.lambda,
12281 fctx,
12282 ) * margin
12283 <= found.cost;
12284 if skip_search {
12285 newmv_census_global(1);
12286 }
12287 if searched && !skip_search {
12288 let (gseeds, gn) = mv_seeds(gstack);
12289 #[cfg(test)]
12290 let t = stage_start();
12291 let gfound = motion::search(
12292 &g.y,
12293 g.width,
12294 luma.true_width,
12295 luma.true_height,
12296 &source_block,
12297 x,
12298 y,
12299 BLOCK,
12300 BLOCK,
12301 gstack.pred_mv,
12302 &gseeds[..gn],
12303 search.lambda,
12304 fctx,
12305 ref_distance(ref_frame),
12306 );
12307 #[cfg(test)]
12308 stage_since(0, t);
12309 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
12310 extra_new_mvs.push((ref_frame, gmv));
12311 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
12312 cands.push((
12313 gmv,
12314 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
12315 InterInfo {
12316 ref1: None,
12317 mv1: (0, 0),
12318 ref_frame,
12319 mode: InterMode::NewMv,
12320 mv: gmv,
12321 ref_mv_idx,
12322 },
12323 ));
12324 }
12325 }
12326 }
12327
12328 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
12329 // trial set each: both references predict the block and the two
12330 // predictions are averaged, which is what pays on content where neither
12331 // reference alone is right. Priced with the same static-CDF approximation
12332 // the single-reference candidates use, plus the compound-only symbols
12333 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
12334 // The two compound-mode arms, each measured alone on the BD gate before
12335 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
12336 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
12337 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
12338 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
12339 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
12340 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
12341 // the keep rule. Still behind the knob.
12342 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
12343 let half_new = true;
12344 for (ref1, g, cstack) in compound {
12345 let (ref1, g) = (*ref1, *g);
12346 // The whole `comp_mode` + reference-pair tree at the writer's own
12347 // contexts, for THIS pair (lane-ctx).
12348 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
12349 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
12350 let mode_bits_of =
12351 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
12352 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
12353 (
12354 cstack.nearest_mv,
12355 mode_bits_of(0),
12356 InterInfo {
12357 ref_frame: crate::mvstack::LAST_FRAME,
12358 mode: InterMode::NearestNearestMv,
12359 mv: cstack.nearest_mv.0,
12360 mv1: cstack.nearest_mv.1,
12361 ref1: Some(ref1),
12362 ref_mv_idx: 0,
12363 },
12364 ),
12365 (
12366 ((0, 0), (0, 0)),
12367 mode_bits_of(6),
12368 InterInfo {
12369 ref_frame: crate::mvstack::LAST_FRAME,
12370 mode: InterMode::GlobalGlobalMv,
12371 mv: (0, 0),
12372 mv1: (0, 0),
12373 ref1: Some(ref1),
12374 ref_mv_idx: 0,
12375 },
12376 ),
12377 ];
12378 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
12379 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
12380 // the stack is deep enough for that walk to read one.
12381 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
12382 let drl = if cstack.entries.len() > 2 {
12383 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
12384 } else {
12385 0.0
12386 };
12387 ccands.push((
12388 (e.mv0, e.mv1),
12389 mode_bits_of(1) + drl,
12390 InterInfo {
12391 ref_frame: crate::mvstack::LAST_FRAME,
12392 mode: InterMode::NearNearMv,
12393 mv: e.mv0,
12394 mv1: e.mv1,
12395 ref1: Some(ref1),
12396 ref_mv_idx: 0,
12397 },
12398 ));
12399 }
12400 // The half-new modes and `NEW_NEWMV`, all seeded from the two
12401 // single-reference searches this block already ran -- no joint search
12402 // of its own. Every residual is priced against stack entry 0, which
12403 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
12404 let cbase = cstack
12405 .entries
12406 .first()
12407 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
12408 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
12409 ccands.push((
12410 (mv, cstack.nearest_mv.1),
12411 mode_bits_of(3) + b0,
12412 InterInfo {
12413 ref_frame: crate::mvstack::LAST_FRAME,
12414 mode: InterMode::NewNearestMv,
12415 mv,
12416 mv1: cstack.nearest_mv.1,
12417 ref1: Some(ref1),
12418 ref_mv_idx: 0,
12419 },
12420 ));
12421 }
12422 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
12423 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
12424 ccands.push((
12425 (cstack.nearest_mv.0, mv1),
12426 mode_bits_of(2) + b1,
12427 InterInfo {
12428 ref_frame: crate::mvstack::LAST_FRAME,
12429 mode: InterMode::NearestNewMv,
12430 mv: cstack.nearest_mv.0,
12431 mv1,
12432 ref1: Some(ref1),
12433 ref_mv_idx: 0,
12434 },
12435 ));
12436 }
12437 let base = cbase;
12438 if let (Some(b0), Some(b1)) =
12439 (mv_residual_bits(mv, base.0), mv_residual_bits(mv1, base.1))
12440 {
12441 ccands.push((
12442 (mv, mv1),
12443 mode_bits_of(7) + b0 + b1,
12444 InterInfo {
12445 ref_frame: crate::mvstack::LAST_FRAME,
12446 mode: InterMode::NewNewMv,
12447 mv,
12448 mv1,
12449 ref1: Some(ref1),
12450 ref_mv_idx: 0,
12451 },
12452 ));
12453 }
12454 }
12455 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
12456 ccands.dedup_by_key(|c| c.0);
12457 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
12458 let g_u = (
12459 g.u.as_slice(),
12460 g.width / 2,
12461 chroma[0].true_width,
12462 chroma[0].true_height,
12463 );
12464 let g_v = (
12465 g.v.as_slice(),
12466 g.width / 2,
12467 chroma[1].true_width,
12468 chroma[1].true_height,
12469 );
12470 for (mvs, bits, info) in ccands {
12471 let luma_trial = mc_trial_compound(
12472 luma,
12473 x,
12474 y,
12475 BLOCK,
12476 mvs,
12477 true,
12478 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12479 g_luma,
12480 search.base_q_idx,
12481 search.deadzone,
12482 TxbSet::Luma32Inter,
12483 fctx,
12484 );
12485 let u = mc_trial_compound(
12486 &chroma[0],
12487 x / 2,
12488 y / 2,
12489 BLOCK / 2,
12490 mvs,
12491 false,
12492 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12493 g_u,
12494 search.base_q_idx,
12495 search.deadzone,
12496 chroma_set,
12497 fctx,
12498 );
12499 let v = mc_trial_compound(
12500 &chroma[1],
12501 x / 2,
12502 y / 2,
12503 BLOCK / 2,
12504 mvs,
12505 false,
12506 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12507 g_v,
12508 search.base_q_idx,
12509 search.deadzone,
12510 chroma_set,
12511 fctx,
12512 );
12513 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12514 && u.levels.iter().all(|&l| l == 0)
12515 && v.levels.iter().all(|&l| l == 0);
12516 let cost = luma_trial.sse
12517 + u.sse
12518 + v.sse
12519 + search.lambda
12520 * (skip_bits(skip)
12521 + intra_inter_bits(true)
12522 + bits
12523 + if skip {
12524 0.0
12525 } else {
12526 luma_trial.bits + u.bits + v.bits
12527 });
12528 consider(Candidate {
12529 cost,
12530 luma: luma_trial,
12531 u,
12532 v,
12533 mode: DC_PRED,
12534 skip,
12535 mode_bits: bits,
12536 inter: Some(info),
12537 });
12538 }
12539 }
12540
12541 // One trial set per distinct (reference, vector) pair: sort, cheapest
12542 // syntax first, and drop the rest of each pair's run.
12543 cands.sort_by(|a, b| {
12544 (a.2.ref_frame, a.0)
12545 .cmp(&(b.2.ref_frame, b.0))
12546 .then(a.1.total_cmp(&b.1))
12547 });
12548 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
12549 census_add(7, cands.len());
12550 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
12551 // this block reaches WITHOUT it, taken inside the one loop that prices
12552 // them all (a second pricing pass would be a second oracle).
12553 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
12554 {
12555 for (mv, mode_bits_inter, info) in cands {
12556 let (ref_luma, ref_u, ref_v) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame)
12557 {
12558 Some(&(_, g, _)) => (
12559 (&g.y, g.width, luma.true_width, luma.true_height),
12560 (
12561 &g.u,
12562 g.width / 2,
12563 chroma[0].true_width,
12564 chroma[0].true_height,
12565 ),
12566 (
12567 &g.v,
12568 g.width / 2,
12569 chroma[1].true_width,
12570 chroma[1].true_height,
12571 ),
12572 ),
12573 None => (ref_luma, ref_u, ref_v),
12574 };
12575 let luma_trial = mc_trial(
12576 luma,
12577 x,
12578 y,
12579 BLOCK,
12580 mv,
12581 true,
12582 ref_luma.0,
12583 ref_luma.1,
12584 ref_luma.2,
12585 ref_luma.3,
12586 false,
12587 search.base_q_idx,
12588 search.deadzone,
12589 TxbSet::Luma32Inter,
12590 fctx,
12591 );
12592 let u = mc_trial(
12593 &chroma[0],
12594 x / 2,
12595 y / 2,
12596 BLOCK / 2,
12597 mv,
12598 false,
12599 ref_u.0,
12600 ref_u.1,
12601 ref_u.2,
12602 ref_u.3,
12603 false,
12604 search.base_q_idx,
12605 search.deadzone,
12606 chroma_set,
12607 fctx,
12608 );
12609 let v = mc_trial(
12610 &chroma[1],
12611 x / 2,
12612 y / 2,
12613 BLOCK / 2,
12614 mv,
12615 false,
12616 ref_v.0,
12617 ref_v.1,
12618 ref_v.2,
12619 ref_v.3,
12620 false,
12621 search.base_q_idx,
12622 search.deadzone,
12623 chroma_set,
12624 fctx,
12625 );
12626 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12627 && u.levels.iter().all(|&l| l == 0)
12628 && v.levels.iter().all(|&l| l == 0);
12629 let cost = luma_trial.sse
12630 + u.sse
12631 + v.sse
12632 + search.lambda
12633 * (skip_bits(skip)
12634 + intra_inter_bits(true)
12635 + mode_bits_inter
12636 + if skip {
12637 0.0
12638 } else {
12639 luma_trial.bits + u.bits + v.bits
12640 });
12641 consider(Candidate {
12642 cost,
12643 luma: luma_trial,
12644 u,
12645 v,
12646 mode: DC_PRED,
12647 skip,
12648 mode_bits: mode_bits_inter,
12649 inter: Some(info),
12650 });
12651 if newmv_census_on() {
12652 if info.mode == InterMode::NewMv
12653 && info.ref1.is_none()
12654 && info.ref_frame == crate::mvstack::LAST_FRAME
12655 {
12656 new_cost = cost;
12657 } else {
12658 other_cost = other_cost.min(cost);
12659 }
12660 }
12661 }
12662 }
12663 if let Some((new_mv, bits)) = newmv_syntax {
12664 newmv_census_block(
12665 BLOCK,
12666 true,
12667 new_cost,
12668 other_cost,
12669 new_mv,
12670 stack.nearest_mv,
12671 bits,
12672 );
12673 } else {
12674 newmv_census_block(
12675 BLOCK,
12676 false,
12677 f64::INFINITY,
12678 other_cost,
12679 mv,
12680 stack.nearest_mv,
12681 0.0,
12682 );
12683 }
12684
12685 let best = best.expect("the search offers at least the intra modes");
12686 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
12687 // offered to the SINGLE-REFERENCE winner only -- libaom's
12688 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
12689 // compound block, so the writer codes no symbol for one. The prediction
12690 // is built by the DECODER's own plan and blend
12691 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
12692 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
12693 // this search's `grid` already carries, so what is priced here is what a
12694 // decoder reconstructs -- never a second implementation of the blend.
12695 //
12696 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
12697 // on). Native crop BD, the standing recipe, with it on against the same
12698 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
12699 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
12700 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
12701 // one UP -- the keep rule wants two down and one flat, so it stays off.
12702 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
12703 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
12704 // things bound it and are the upgrade path: only the 32x32 winner is
12705 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
12706 // that is where libaom cashes most of its OBMC gain), and the symbol/
12707 // residual price here is the static-CDF estimate.
12708 let mut best = best;
12709 let mut motion_won = 0u8;
12710 if let Some(info) = best
12711 .inter
12712 .filter(|i| i.ref1.is_none() && (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on()))
12713 {
12714 let mut refs: [Option<&Picture>; 8] = [None; 8];
12715 refs[LAST_FRAME as usize] = Some(reference);
12716 for &(r, p, _) in extra {
12717 refs[r as usize] = Some(p);
12718 }
12719 // This block's OWN reference planes: the single-reference winner may
12720 // be one of the extra references, not LAST.
12721 let planes: [(&[u16], usize, usize, usize); 3] =
12722 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12723 Some(&(_, g, _)) => [
12724 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12725 (
12726 g.u.as_slice(),
12727 g.width / 2,
12728 chroma[0].true_width,
12729 chroma[0].true_height,
12730 ),
12731 (
12732 g.v.as_slice(),
12733 g.width / 2,
12734 chroma[1].true_width,
12735 chroma[1].true_height,
12736 ),
12737 ],
12738 None => [
12739 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12740 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12741 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12742 ],
12743 };
12744 // The alphabet `tile::write_motion_mode` will code this block's
12745 // symbol against, mirrored term for term (libaom
12746 // `motion_mode_allowed`).
12747 let warp_alphabet = warp_on()
12748 && crate::decode::num_proj_ref(
12749 grid,
12750 mi_row,
12751 mi_col,
12752 8,
12753 8,
12754 mi_cols,
12755 mi_rows,
12756 info.ref_frame,
12757 fctx,
12758 ) >= 1;
12759 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
12760 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
12761 if crate::envflags::env_flag!("EC_AV1_OBMC") {
12762 if let Some(pred) = obmc_prediction(
12763 grid,
12764 (mi_row, mi_col),
12765 (mi_rows, mi_cols),
12766 (x, y),
12767 BLOCK,
12768 info.mv,
12769 &refs,
12770 planes,
12771 reference.width,
12772 fctx,
12773 ) {
12774 candidates.push((1, pred));
12775 }
12776 }
12777 if warp_alphabet {
12778 if let Some(pred) = warp_prediction(
12779 grid,
12780 (mi_row, mi_col),
12781 (mi_rows, mi_cols),
12782 (x, y),
12783 BLOCK,
12784 info.mv,
12785 info.ref_frame,
12786 planes,
12787 fctx,
12788 ) {
12789 candidates.push((2, pred));
12790 }
12791 }
12792 for (motion, pred) in candidates {
12793 let luma_trial = luma.code_from_prediction(
12794 x,
12795 y,
12796 BLOCK,
12797 &pred[0],
12798 false,
12799 search.base_q_idx,
12800 search.deadzone,
12801 TxbSet::Luma32Inter,
12802 );
12803 let u = chroma[0].code_from_prediction(
12804 x / 2,
12805 y / 2,
12806 BLOCK / 2,
12807 &pred[1],
12808 false,
12809 search.base_q_idx,
12810 search.deadzone,
12811 chroma_set,
12812 );
12813 let v = chroma[1].code_from_prediction(
12814 x / 2,
12815 y / 2,
12816 BLOCK / 2,
12817 &pred[2],
12818 false,
12819 search.base_q_idx,
12820 search.deadzone,
12821 chroma_set,
12822 );
12823 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12824 && u.levels.iter().all(|&l| l == 0)
12825 && v.levels.iter().all(|&l| l == 0);
12826 let cost = luma_trial.sse
12827 + u.sse
12828 + v.sse
12829 + search.lambda
12830 * (skip_bits(skip)
12831 + intra_inter_bits(true)
12832 + best.mode_bits
12833 + mm(motion)
12834 + if skip {
12835 0.0
12836 } else {
12837 luma_trial.bits + u.bits + v.bits
12838 });
12839 if cost < best.cost + search.lambda * mm(motion_won) {
12840 motion_won = motion;
12841 best = Candidate {
12842 cost,
12843 luma: luma_trial,
12844 u,
12845 v,
12846 mode: DC_PRED,
12847 skip,
12848 mode_bits: best.mode_bits,
12849 inter: best.inter,
12850 };
12851 }
12852 }
12853 }
12854 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
12855 // default OFF): the four 16x16 units of `commit_inter_luma` against the
12856 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
12857 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
12858 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
12859 // it, and it is worse again on the deciding native table: film 1080p
12860 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
12861 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
12862 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
12863 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
12864 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
12865 // +28.4/+47.4/-4.0 -- the native table decides.)
12866 //
12867 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
12868 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
12869 // either, and the census names the row: the split units' own set
12870 // `Luma16Inter` is priced within 1.4% of what it is written at in every
12871 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
12872 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
12873 // so a perfect pricer would split even more, and more splitting is what
12874 // measured worse. The four extra txb_skip/eob symbols simply cost more
12875 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
12876 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
12877 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
12878 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
12879 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
12880 // plain translation, which is not the prediction it was priced from.
12881 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
12882 Some(info) => {
12883 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12884 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12885 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12886 };
12887 let second = info.ref1.and_then(|r| {
12888 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
12889 (
12890 info.mv1,
12891 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12892 )
12893 })
12894 });
12895 match info.ref1.is_some() && second.is_none() {
12896 true => {
12897 luma.commit(x, y, BLOCK, &best.luma);
12898 (best.luma.levels.clone(), 0, 0.0, Vec::new())
12899 }
12900 false => commit_inter_luma(
12901 luma,
12902 (x, y),
12903 BLOCK,
12904 info.mv,
12905 own,
12906 search,
12907 &best.luma,
12908 best.skip,
12909 second,
12910 fctx,
12911 ),
12912 }
12913 }
12914 None => {
12915 luma.commit(x, y, BLOCK, &best.luma);
12916 (best.luma.levels.clone(), 0, 0.0, Vec::new())
12917 }
12918 };
12919 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
12920 let [bu, bv] = match (
12921 best.inter.filter(|_| motion_won == 0),
12922 luma_tx_types.first().copied(),
12923 ) {
12924 (Some(info), Some(t)) => {
12925 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12926 Some(&(_, g, _)) => (
12927 (
12928 g.u.as_slice(),
12929 g.width / 2,
12930 chroma[0].true_width,
12931 chroma[0].true_height,
12932 ),
12933 (
12934 g.v.as_slice(),
12935 g.width / 2,
12936 chroma[1].true_width,
12937 chroma[1].true_height,
12938 ),
12939 ),
12940 None => (
12941 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12942 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12943 ),
12944 };
12945 let sec = info.ref1.and_then(|r| {
12946 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
12947 (
12948 info.mv1,
12949 [
12950 (
12951 g.u.as_slice(),
12952 g.width / 2,
12953 chroma[0].true_width,
12954 chroma[0].true_height,
12955 ),
12956 (
12957 g.v.as_slice(),
12958 g.width / 2,
12959 chroma[1].true_width,
12960 chroma[1].true_height,
12961 ),
12962 ],
12963 )
12964 })
12965 });
12966 recode_inter_chroma(
12967 chroma,
12968 (x, y),
12969 BLOCK,
12970 info.mv,
12971 [ou, ov],
12972 sec,
12973 search,
12974 chroma_set,
12975 t,
12976 fctx,
12977 )
12978 .unwrap_or([best.u, best.v])
12979 }
12980 _ => [best.u, best.v],
12981 };
12982 let best = Candidate {
12983 u: bu,
12984 v: bv,
12985 ..best
12986 };
12987 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
12988 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
12989 (
12990 BlockCoeffs {
12991 luma_tx_types,
12992 angle_delta_y: 0,
12993 cfl_alphas: None,
12994 filter_intra: None,
12995 luma: coeffs(&levels, BLOCK),
12996 u: coeffs(&best.u.levels, BLOCK / 2),
12997 v: coeffs(&best.v.levels, BLOCK / 2),
12998 mode: best.mode,
12999 uv_mode: DC_PRED,
13000 skip: best.skip,
13001 inter: best.inter,
13002 motion_mode: motion_won,
13003 eight: None,
13004 dv: None,
13005 palette: None,
13006 palette_uv: None,
13007 tx_depth,
13008 },
13009 best.cost + dcost,
13010 )
13011}
13012
13013/// lane-av1tpl: the strength `k` of the temporal lambda weighting
13014/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
13015/// is what every measurement before this lane was taken on. Swept by
13016/// `EC_AV1_TPL=<k>`.
13017///
13018/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
13019/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
13020/// baseline exactly, which is the control the rest of the table is read
13021/// against:
13022///
13023/// | k | film 1080p | film 2160p | screen |
13024/// |---|---|---|---|
13025/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
13026/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
13027/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
13028/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
13029/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
13030///
13031/// 0.5 is the only arm that is at least flat on every row and down on five of
13032/// the six columns, so it ships as the default. The lookahead pass that feeds
13033/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
13034const TPL_STRENGTH: f64 = 0.5;
13035
13036/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
13037/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
13038/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
13039/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
13040///
13041/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
13042/// nothing to vary the quantizer BY and codes no delta syntax at all.
13043fn deltaq_res_log2() -> Option<u8> {
13044 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
13045 u8::MAX => {}
13046 4 => return None,
13047 r => return Some(r),
13048 }
13049 match crate::envflags::var("EC_AV1_DELTAQ")
13050 .ok()
13051 .as_deref()
13052 .map(str::trim)
13053 {
13054 Some("0") => None,
13055 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
13056 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
13057 }
13058}
13059
13060/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
13061/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
13062/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
13063/// speed presets take, because the streams every other test pins move under
13064/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
13065static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
13066
13067/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
13068#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
13069pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
13070 DELTAQ_OVERRIDE.store(
13071 res_log2.unwrap_or(u8::MAX),
13072 std::sync::atomic::Ordering::Relaxed,
13073 );
13074}
13075
13076/// How much of the derived qindex step is actually taken
13077/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
13078fn deltaq_k() -> f64 {
13079 crate::envflags::var("EC_AV1_DELTAQ_K")
13080 .ok()
13081 .and_then(|v| v.trim().parse::<f64>().ok())
13082 .filter(|k| k.is_finite() && *k >= 0.0)
13083 .unwrap_or(1.0)
13084}
13085
13086/// The largest qindex the map may move a superblock by, either way
13087/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
13088/// deltaq around a quarter of the base qindex).
13089fn deltaq_clamp() -> i32 {
13090 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
13091 .ok()
13092 .and_then(|v| v.trim().parse::<i32>().ok())
13093 .filter(|c| (0..=63).contains(c))
13094 .unwrap_or(16)
13095}
13096
13097/// The qindex a lambda factor `f` asks for, derived rather than fitted.
13098///
13099/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
13100/// square of the quantizer step (`encode_inter_frame`'s own
13101/// `lambda = .. * step * step`), so the step this superblock wants is
13102/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
13103/// step ratio is inverted through the table itself -- the index whose `ac_q`
13104/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
13105/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
13106/// bounds it, and the answer is snapped onto the `res` grid so that every
13107/// superblock's qindex is congruent to `base` and the coded delta is a whole
13108/// number of steps.
13109fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
13110 let base_ac = f64::from(ac_q(8, i32::from(base)));
13111 let target = base_ac * f.max(1e-6).sqrt();
13112 let exact = (1..=255)
13113 .min_by(|&a, &b| {
13114 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
13115 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
13116 })
13117 .expect("the qindex range is not empty")
13118 - i32::from(base);
13119 let want = (exact as f64 * k).round() as i32;
13120 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
13121 // and need not be a whole number of steps, and clamping afterwards would
13122 // hand back a qindex that is not congruent to `base`.
13123 let max_steps = clamp / res;
13124 let steps = (want as f64 / f64::from(res)).round() as i32;
13125 let delta = steps.clamp(-max_steps, max_steps) * res;
13126 (i32::from(base) + delta).clamp(1, 255) as u8
13127}
13128
13129/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
13130/// objective would, from the SAME tpl dependence ratio our own map already
13131/// carries (`EC_AV1_DQ_TPL=1`).
13132///
13133/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
13134/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
13135/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
13136/// same expression at frame scope) by it, and asks
13137/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
13138/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
13139/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
13140/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
13141/// libaom reads `r0`. The offset is clamped to libaom's own
13142/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
13143/// twice the +-16 qindex [`deltaq_for_factor`] allows.
13144///
13145/// Two things differ from [`deltaq_for_factor`] and both are the point of the
13146/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
13147/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
13148/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
13149/// much stronger for the same map. `strength` scales the offset.
13150fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
13151 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
13152 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
13153 let exact = (1..=255)
13154 .min_by(|&a, &b| {
13155 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
13156 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
13157 })
13158 .expect("the qindex range is not empty")
13159 - i32::from(base);
13160 let want = exact as f64 * strength;
13161 // Snapped onto the `res` grid first, so the coded delta is a whole number
13162 // of steps, then bounded by libaom's own `res * 9 - 1`.
13163 let max_steps = (res * 9 - 1) / res;
13164 let steps = (want / f64::from(res)).round() as i32;
13165 let delta = steps.clamp(-max_steps, max_steps) * res;
13166 (i32::from(base) + delta).clamp(1, 255) as u8
13167}
13168
13169/// The frame-level `r0` libaom's objective divides by: the log-mean of
13170/// `1 + r` over the frame's cells, minus 1.
13171fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
13172 if ratio.is_empty() {
13173 return 0.0;
13174 }
13175 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
13176 m.exp() - 1.0
13177}
13178
13179/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
13180/// [`deltaq_for_factor`] derivation.
13181///
13182/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
13183/// the strength (default 1.0 = libaom's own offset when the flag armed it);
13184/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
13185fn dq_tpl_strength(level: DqLevel) -> Option<f64> {
13186 let m = dq_level_k()[level as usize];
13187 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
13188 .ok()
13189 .and_then(|v| v.trim().parse::<f64>().ok())
13190 .filter(|k| k.is_finite() && *k >= 0.0);
13191 let base = match crate::envflags::var("EC_AV1_DQ_TPL")
13192 .ok()
13193 .as_deref()
13194 .map(str::trim)
13195 {
13196 Some("0") => return None,
13197 Some(_) => Some(env_k.unwrap_or(1.0)),
13198 None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))),
13199 };
13200 base.map(|k| k * m).filter(|k| *k > 0.0)
13201}
13202
13203/// lane-arfq: which pyramid level the frame asking for a
13204/// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it
13205/// codes no `delta_q` syntax at all (the whole lever lives in
13206/// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the
13207/// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job.
13208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13209pub(crate) enum DqLevel {
13210 /// The mini-GOP's own hidden `ALTREF`, which every other frame of the
13211 /// group predicts from (directly or through the mid level).
13212 TopArf = 0,
13213 /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it.
13214 MidArf = 1,
13215 /// A shown leaf -- and every frame of the flat, non-pyramid path.
13216 Leaf = 2,
13217}
13218
13219/// The per-level multiplier on the [`dq_tpl_strength`] the preset carries:
13220/// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else
13221/// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes
13222/// no `delta_q` (see [`DqLevel`]).
13223fn dq_level_k() -> [f64; 3] {
13224 dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref())
13225}
13226
13227/// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an
13228/// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry.
13229fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] {
13230 let mut k = crate::speed::DQ_LEVEL_K;
13231 if let Some(spec) = spec {
13232 for (slot, field) in k.iter_mut().zip(spec.split(':')) {
13233 if let Some(v) = field
13234 .trim()
13235 .parse::<f64>()
13236 .ok()
13237 .filter(|v: &f64| v.is_finite() && *v >= 0.0)
13238 {
13239 *slot = v;
13240 }
13241 }
13242 }
13243 k
13244}
13245
13246/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
13247/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
13248/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
13249/// the same tpl map -- and which of the two the frame actually coded.
13250fn dq_census() -> bool {
13251 crate::envflags::var("EC_AV1_DQ_CENSUS")
13252 .ok()
13253 .as_deref()
13254 .map(str::trim)
13255 == Some("1")
13256}
13257
13258/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
13259fn dq_summary(offsets: &[i32]) -> String {
13260 let n = offsets.len().max(1);
13261 let (lo, hi) = offsets
13262 .iter()
13263 .fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
13264 let nz = offsets.iter().filter(|&&o| o != 0).count();
13265 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
13266 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
13267 let mut levels: Vec<i32> = offsets.to_vec();
13268 levels.sort_unstable();
13269 levels.dedup();
13270 format!(
13271 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
13272 offsets.len(),
13273 levels.len()
13274 )
13275}
13276
13277/// How many DISTINCT per-superblock quantizer levels the last inter frame's
13278/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
13279/// (class `gate-blind-to-feature`: every exactness assert below passes on a
13280/// grid that is one flat value, i.e. on no delta_q at all). Process-global
13281/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
13282/// keeps the LARGEST count seen since the last read.
13283static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
13284
13285/// [`DELTAQ_LEVELS`], reset to 0.
13286#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
13287pub(crate) fn take_deltaq_levels() -> usize {
13288 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
13289}
13290
13291/// This superblock's search state: the quantizer it is coded at, and the
13292/// lambda that quantizer implies. RD lambda goes as the square of the step,
13293/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
13294/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
13295/// before lane-deltaq).
13296fn sb_q_search<'m>(
13297 sb_q: &[u8],
13298 sb_cols: usize,
13299 base_q_idx: u8,
13300 (sb_r, sb_c): (usize, usize),
13301 base: Search<'m>,
13302) -> Search<'m> {
13303 let q = sb_q[sb_r * sb_cols + sb_c];
13304 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
13305 Search {
13306 base_q_idx: q,
13307 lambda: base.lambda * ratio * ratio,
13308 ..base
13309 }
13310}
13311
13312fn tpl_strength() -> f64 {
13313 std::env::var("EC_AV1_TPL")
13314 .ok()
13315 .and_then(|v| v.parse::<f64>().ok())
13316 .filter(|k| k.is_finite() && *k >= 0.0)
13317 .unwrap_or(TPL_STRENGTH)
13318}
13319
13320/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
13321/// the frame being coded. 1 turns the weighting off; 2 is the shipped
13322/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
13323/// [`tpl_propagating`], which is the map that can actually use them and is
13324/// the default since lane-av1tpl3, so the default window is 8. Swept by
13325/// `EC_AV1_TPL_D=<d>`.
13326///
13327/// The streaming facade holds `depth - 1` pictures back so it feeds
13328/// `encode_inter_frame` the same window `encode_sequence` does; both read
13329/// THIS function, so the two paths cannot disagree about the window.
13330pub(crate) const TPL_DEPTH: usize = 8;
13331
13332/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
13333/// 0.5 is libaom's own square-root compression of its dependence ratio.
13334const TPL_POWER: f64 = 0.5;
13335
13336/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
13337/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
13338///
13339/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
13340/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
13341/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
13342///
13343/// | k | D | p | film 1080p | film 2160p | screen |
13344/// |---|---|---|---|---|---|
13345/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
13346/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
13347/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
13348/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
13349/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
13350/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
13351/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
13352/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
13353/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
13354/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
13355/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
13356/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
13357///
13358/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
13359/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
13360/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
13361/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
13362/// 0.1..0.4 UP on film 2160p, so it shipped off.
13363///
13364/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
13365/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
13366/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
13367/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
13368/// wherever the window leans on a flat bar, which is exactly where coding is
13369/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
13370/// (libaom's own granularity) puts a busy cell's denominator next to the flat
13371/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
13372/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
13373/// the same native gate (baseline = the shipped one-frame map):
13374///
13375/// | arm | film 1080p | film 2160p | screen |
13376/// |---|---|---|---|
13377/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
13378/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
13379/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
13380/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
13381/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
13382/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
13383/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
13384/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
13385/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
13386/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
13387///
13388/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
13389/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
13390/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
13391/// floor is a real effect on the ratio and never a win once the aggregation
13392/// is in -- the aggregation is the same fix, done where libaom does it.
13393fn tpl_propagating() -> bool {
13394 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
13395}
13396
13397pub(crate) fn tpl_depth() -> usize {
13398 std::env::var("EC_AV1_TPL_D")
13399 .ok()
13400 .and_then(|v| v.parse::<usize>().ok())
13401 .filter(|d| *d >= 1)
13402 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
13403 .max(1)
13404}
13405
13406/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
13407/// process, so the gate can price it against the encode it rides on.
13408static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
13409
13410/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
13411/// the winning displacement and its SAD.
13412///
13413/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
13414/// the left/above winners, first-best tie-break. Built once on the frame's
13415/// own thread and read-only afterwards, so it cannot make a tile's bytes
13416/// depend on the thread count.
13417fn tpl_coarse_pass(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<((i32, i32), u32)> {
13418 let (cells_x, cells_y) = (width / 16, height / 16);
13419 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
13420 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
13421 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
13422 return u32::MAX;
13423 }
13424 let (sx, sy) = (sx as usize, sy as usize);
13425 let mut sum = 0u32;
13426 for r in 0..16 {
13427 let a = &next[(by + r) * width + bx..][..16];
13428 let b = &cur[(sy + r) * width + sx..][..16];
13429 sum += a
13430 .iter()
13431 .zip(b)
13432 .map(|(&p, &q)| u32::from(p.abs_diff(q)))
13433 .sum::<u32>();
13434 }
13435 sum
13436 };
13437 let mut out = Vec::with_capacity(cells_x * cells_y);
13438 let mut above = vec![(0i32, 0i32); cells_x];
13439 for cy in 0..cells_y {
13440 let mut left = (0i32, 0i32);
13441 for cx in 0..cells_x {
13442 let (bx, by) = (cx * 16, cy * 16);
13443 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
13444 for cand in [left, above[cx]] {
13445 if cand != (0, 0) {
13446 let s = sad(bx, by, cand);
13447 if s < best.0 {
13448 best = (s, cand);
13449 }
13450 }
13451 }
13452 for step in [8i32, 4, 2, 1] {
13453 let centre = best.1;
13454 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
13455 let mv = (centre.0 + dx, centre.1 + dy);
13456 if mv.0.abs() > 32 || mv.1.abs() > 32 {
13457 continue;
13458 }
13459 let s = sad(bx, by, mv);
13460 if s < best.0 {
13461 best = (s, mv);
13462 }
13463 }
13464 }
13465 left = best.1;
13466 above[cx] = best.1;
13467 out.push((best.1, best.0));
13468 }
13469 }
13470 out
13471}
13472
13473/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
13474/// transform: here, the mean absolute deviation of the cell from its own DC.
13475/// It is the denominator every propagated cost is read against, so only its
13476/// SHAPE across the frame matters, not its scale.
13477fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
13478 let (cells_x, cells_y) = (width / 16, height / 16);
13479 let mut out = Vec::with_capacity(cells_x * cells_y);
13480 for cy in 0..cells_y {
13481 for cx in 0..cells_x {
13482 let (bx, by) = (cx * 16, cy * 16);
13483 let mut sum = 0u32;
13484 for r in 0..16 {
13485 sum += frame[(by + r) * width + bx..][..16]
13486 .iter()
13487 .map(|&p| u32::from(p))
13488 .sum::<u32>();
13489 }
13490 let dc = ((sum + 128) / 256) as u8;
13491 let mut cost = 0u32;
13492 for r in 0..16 {
13493 cost += frame[(by + r) * width + bx..][..16]
13494 .iter()
13495 .map(|&p| u32::from(p.abs_diff(dc)))
13496 .sum::<u32>();
13497 }
13498 out.push(cost);
13499 }
13500 }
13501 out
13502}
13503
13504/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
13505/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
13506/// splats its own area, at its winning displacement, onto the (at most four)
13507/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
13508fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
13509 let start = std::time::Instant::now();
13510 let (cells_x, cells_y) = (width / 16, height / 16);
13511 let pass = tpl_coarse_pass(cur, next, width, height);
13512 let mut area = vec![0.0f64; cells_x * cells_y];
13513 for cy in 0..cells_y {
13514 for cx in 0..cells_x {
13515 let (mv, _) = pass[cy * cells_x + cx];
13516 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
13517 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
13518 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
13519 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
13520 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
13521 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
13522 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
13523 }
13524 }
13525 }
13526 }
13527 TPL_NANOS.fetch_add(
13528 start.elapsed().as_nanos() as u64,
13529 std::sync::atomic::Ordering::Relaxed,
13530 );
13531 area
13532}
13533
13534/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
13535/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
13536/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
13537/// Decreasing in referenced-ness (a block the next frame leans on is coded
13538/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
13539/// total lambda scale is only redistributed, never moved -- a global move is
13540/// the thing lane-av1lambda already measured inert.
13541fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
13542 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
13543 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
13544 let mut out = Vec::with_capacity(sb_cols * sb_rows);
13545 for sr in 0..sb_rows {
13546 for sc in 0..sb_cols {
13547 let mut sum = 0.0;
13548 for r in 0..4 {
13549 for c in 0..4 {
13550 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
13551 }
13552 }
13553 let w_rel = sum / 16.0 / mean;
13554 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
13555 }
13556 }
13557 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
13558 let mut hist = [0usize; 8];
13559 for w in map {
13560 hist[((w / mean * 2.0) as usize).min(7)] += 1;
13561 }
13562 let (lo, hi) = out
13563 .iter()
13564 .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
13565 eprintln!(
13566 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
13567 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
13568 map.len(),
13569 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
13570 );
13571 }
13572 out
13573}
13574
13575/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
13576/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
13577/// much of the WHOLE lookahead window leans on that cell.
13578///
13579/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
13580/// coarse pass gives a displacement and an inter cost; a cell's own
13581/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
13582/// cell well saves the frames that predict from it -- and it is splatted,
13583/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
13584/// displacement lands on. Walking `f` from the far end of the window back to
13585/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
13586/// area map could not do at all.
13587///
13588/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
13589/// factor over the frame is exactly 1: a cell the window leans on is coded
13590/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
13591/// scale only moves around, never up or down -- a global move is what
13592/// lane-av1lambda already measured inert.
13593/// Returns the per-cell lambda factors AND the per-cell dependence ratio
13594/// `mc_dep / intra` they were derived from -- the second half is what
13595/// [`deltaq_libaom`] needs, since the factor alone has been through a
13596/// mean normalisation the raw ratio cannot be recovered across.
13597fn tpl_lambda_factors(
13598 frames: &[&[u8]],
13599 width: usize,
13600 height: usize,
13601 k: f64,
13602) -> (Vec<f64>, Vec<f64>) {
13603 let start = std::time::Instant::now();
13604 let (cells_x, cells_y) = (width / 16, height / 16);
13605 let cells = cells_x * cells_y;
13606 let levels = frames.len();
13607 let intra: Vec<Vec<u32>> = frames
13608 .iter()
13609 .map(|f| tpl_intra_costs(f, width, height))
13610 .collect();
13611 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
13612 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
13613 .collect();
13614 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
13615 for f in (1..levels).rev() {
13616 for cy in 0..cells_y {
13617 for cx in 0..cells_x {
13618 let ci = cy * cells_x + cx;
13619 let (mv, inter) = passes[f - 1][ci];
13620 let saved = f64::from(intra[f][ci].saturating_sub(inter));
13621 let propagate = saved + mc_dep[f][ci];
13622 if propagate <= 0.0 {
13623 continue;
13624 }
13625 // The 16x16 window of the PREVIOUS frame this cell predicted
13626 // from, spread over the cells it overlaps.
13627 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
13628 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
13629 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
13630 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
13631 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
13632 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
13633 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
13634 }
13635 }
13636 }
13637 }
13638 }
13639 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
13640 // tail (a nearly flat cell the window leans on has a tiny denominator),
13641 // and at p = 1 that tail slams into the clamp. libaom reads its own
13642 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
13643 // sweeps the exponent, 1 being the raw ratio.
13644 let power = std::env::var("EC_AV1_TPL_P")
13645 .ok()
13646 .and_then(|v| v.parse::<f64>().ok())
13647 .filter(|p| p.is_finite() && *p > 0.0)
13648 .unwrap_or(TPL_POWER);
13649 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
13650 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
13651 // `0` to take either back out); `FLOOR` defaults to off.
13652 //
13653 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
13654 // frame's own mean intra cost. A cell of flat content has a near-zero
13655 // MAD, so its ratio explodes exactly where coding is cheap.
13656 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
13657 // and mc_dep are summed over the 64x64 superblock first -- libaom's
13658 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
13659 // per-16x16 numbers), which is also what makes the ratio survive one
13660 // flat cell next to a busy one.
13661 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
13662 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
13663 // harder than the `p` exponent alone can.
13664 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
13665 .ok()
13666 .and_then(|v| v.parse::<f64>().ok())
13667 .filter(|f| f.is_finite() && *f >= 0.0)
13668 .unwrap_or(0.0);
13669 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
13670 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
13671 let intra_mean = intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
13672 let floor = floor_frac * intra_mean;
13673 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
13674 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
13675 // every cell under it. The edge groups are partial and summed as they are.
13676 let ratio: Vec<f64> = if sb_agg {
13677 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
13678 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
13679 for cy in 0..cells_y {
13680 for cx in 0..cells_x {
13681 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
13682 e.0 += mc_dep[0][cy * cells_x + cx];
13683 e.1 += denom(cy * cells_x + cx);
13684 }
13685 }
13686 (0..cells)
13687 .map(|c| {
13688 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
13689 dep / den.max(1.0)
13690 })
13691 .collect()
13692 } else {
13693 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
13694 };
13695 let mut out: Vec<f64> = ratio
13696 .iter()
13697 .map(|&r| {
13698 let r = if log_beta { (1.0 + r).log2() } else { r };
13699 (1.0 + k * r).powf(-power)
13700 })
13701 .collect();
13702 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
13703 for f in &mut out {
13704 *f = (*f / mean).clamp(0.25, 4.0);
13705 }
13706 TPL_NANOS.fetch_add(
13707 start.elapsed().as_nanos() as u64,
13708 std::sync::atomic::Ordering::Relaxed,
13709 );
13710 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
13711 let mut hist = [0usize; 8];
13712 for &f in &out {
13713 hist[((f * 4.0) as usize).min(7)] += 1;
13714 }
13715 let (lo, hi) = out
13716 .iter()
13717 .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
13718 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
13719 eprintln!(
13720 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
13721 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
13722 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
13723 );
13724 }
13725 (out, ratio)
13726}
13727
13728/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
13729/// references name, which slot it refreshes, whether it is shown when it is
13730/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
13731/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
13732/// 0/2 alternation, every frame shown, every reference in the past).
13733///
13734/// The sign bias is carried rather than derived here because only the caller
13735/// knows what order hint each slot holds; it is armed onto the tile writer
13736/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
13737/// the writer scans the same stacks the decoder will.
13738#[derive(Debug, Clone, Copy)]
13739pub(crate) struct PyramidFrame {
13740 /// The slot `LAST_FRAME` (and every reference this encoder does not name
13741 /// apart) reads.
13742 pub last_slot: u8,
13743 /// The single slot `refresh_frame_flags` sets.
13744 pub self_slot: u8,
13745 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
13746 /// pyramid, which is what makes `sign_bias`'s last entry true.
13747 pub altref_slot: u8,
13748 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
13749 /// picture (the leaf chain alternates its refresh between two slots, so
13750 /// the frame before `LAST` is still intact). `None` leaves
13751 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
13752 /// wrote before, and the caller then passes no `last2` picture either.
13753 pub last2_slot: Option<u8>,
13754 /// `show_frame`: false for a hidden frame, output later by a
13755 /// `show_existing_frame` header.
13756 pub show_frame: bool,
13757 /// lane-arfq: which level's `delta_q` strength this frame reads
13758 /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid
13759 /// one share `Level::Arf` and differ only by their q offset.
13760 pub dq_level: DqLevel,
13761 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
13762 pub sign_bias: crate::mvstack::SignBiasTable,
13763}
13764
13765/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
13766/// `temporal_filter` in the small: every 16x16 luma block of `src` is
13767/// motion-compensated from each picture of `window` (the group's own display
13768/// neighbours, nearest first) and averaged in with weight
13769/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
13770/// nothing and one that matches well cancels the grain the block's residual
13771/// would otherwise have to code.
13772///
13773/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
13774/// rides the luma block's own vector (halved), which is what libaom does at
13775/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
13776/// grid tiles it exactly.
13777///
13778/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
13779/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
13780/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
13781/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
13782/// quality the ARF is coded at, so the substitution itself costs little.
13783// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and
13784// `ARF_TF_WIN_FUT` future ones); this takes every picture in it.
13785pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
13786 const SIDE: usize = 16;
13787 let neighbours: Vec<&Picture> = window
13788 .iter()
13789 .filter(|p| p.width == src.width && p.height == src.height)
13790 .collect();
13791 if neighbours.is_empty() || strength <= 0.0 {
13792 return src.clone();
13793 }
13794 let mut out = src.clone();
13795 // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
13796 // `None` when the displaced block leaves the picture.
13797 let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
13798 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
13799 if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
13800 return None;
13801 }
13802 let (sy, sx) = (sy as usize, sx as usize);
13803 let mut acc = 0u64;
13804 for row in 0..SIDE {
13805 let c = &src.y[(by + row) * src.width + bx..][..SIDE];
13806 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
13807 acc += c
13808 .iter()
13809 .zip(p)
13810 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
13811 .sum::<u64>();
13812 }
13813 Some((acc, (sy, sx)))
13814 };
13815 // The log-step diamond `arf_pred_census` priced this with.
13816 let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
13817 let mut best = sad(r, bx, by, (0, 0))?;
13818 let mut centre = (0isize, 0isize);
13819 let mut step = 16isize;
13820 while step >= 1 {
13821 let from = centre;
13822 for (dy, dx) in [
13823 (-1, -1),
13824 (-1, 0),
13825 (-1, 1),
13826 (0, -1),
13827 (0, 1),
13828 (1, -1),
13829 (1, 0),
13830 (1, 1),
13831 ] {
13832 let mv = (from.0 + dy * step, from.1 + dx * step);
13833 if let Some(s) = sad(r, bx, by, mv) {
13834 if s.0 < best.0 {
13835 best = s;
13836 centre = mv;
13837 }
13838 }
13839 }
13840 step /= 2;
13841 }
13842 Some(best.1)
13843 };
13844 let (cw, ch) = (src.width / 2, src.height / 2);
13845 for by in (0..src.height).step_by(SIDE) {
13846 for bx in (0..src.width).step_by(SIDE) {
13847 if by + SIDE > src.height || bx + SIDE > src.width {
13848 continue;
13849 }
13850 let mut y_acc = vec![0f64; SIDE * SIDE];
13851 let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
13852 let mut wsum = 1.0f64;
13853 // Chroma keeps its OWN weight sum: an edge block whose halved
13854 // vector leaves the chroma plane contributes to luma only, and
13855 // dividing chroma by the luma sum would darken it (class
13856 // `metric blind to a plane`, on the encoder side).
13857 let mut cwsum = 1.0f64;
13858 for row in 0..SIDE {
13859 for col in 0..SIDE {
13860 y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
13861 }
13862 }
13863 for row in 0..SIDE / 2 {
13864 for col in 0..SIDE / 2 {
13865 let i = (by / 2 + row) * cw + bx / 2 + col;
13866 c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
13867 c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
13868 }
13869 }
13870 for r in &neighbours {
13871 let Some((sy, sx)) = search(r, bx, by) else {
13872 continue;
13873 };
13874 let mut sse = 0f64;
13875 for row in 0..SIDE {
13876 for col in 0..SIDE {
13877 let d = f64::from(src.y[(by + row) * src.width + bx + col])
13878 - f64::from(r.y[(sy + row) * r.width + sx + col]);
13879 sse += d * d;
13880 }
13881 }
13882 let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
13883 for row in 0..SIDE {
13884 for col in 0..SIDE {
13885 y_acc[row * SIDE + col] +=
13886 w * f64::from(r.y[(sy + row) * r.width + sx + col]);
13887 }
13888 }
13889 // Chroma reads the luma vector halved; a block on the picture
13890 // edge whose halved vector would leave the chroma plane is
13891 // left to luma alone rather than clamped to a different
13892 // displacement than the luma it must stay registered with.
13893 let (cy, cx) = (sy / 2, sx / 2);
13894 if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
13895 for row in 0..SIDE / 2 {
13896 for col in 0..SIDE / 2 {
13897 let i = (cy + row) * cw + cx + col;
13898 c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
13899 c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
13900 }
13901 }
13902 cwsum += w;
13903 }
13904 wsum += w;
13905 }
13906 for row in 0..SIDE {
13907 for col in 0..SIDE {
13908 out.y[(by + row) * src.width + bx + col] =
13909 (y_acc[row * SIDE + col] / wsum).round() as u16;
13910 }
13911 }
13912 for row in 0..SIDE / 2 {
13913 for col in 0..SIDE / 2 {
13914 let i = (by / 2 + row) * cw + bx / 2 + col;
13915 out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
13916 out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
13917 }
13918 }
13919 }
13920 }
13921 out
13922}
13923
13924/// Encodes one picture as an inter frame predicting from `reference`'s
13925/// reconstruction, which the caller decoded (or, for the frame right after
13926/// the key frame, is the key frame's own reconstruction).
13927pub(crate) fn encode_inter_frame(
13928 picture: &Picture,
13929 reference: &Picture,
13930 base_q_idx: u8,
13931 deadzone: f64,
13932 order_hint: u32,
13933 // The order hint each of the seven `ref_frame_idx` entries names, which a
13934 // decoder reads out of its own reference state -- only spec 5.9.22's
13935 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
13936 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
13937 // callers that follow this crate's own flat slot plan.
13938 order_hints: [u32; 7],
13939 render: (usize, usize),
13940 // The tables this frame's writer starts from: what the previous frame
13941 // stored into the slot this one's `primary_ref_frame` names. `None`
13942 // starts from the defaults, which is right only for the frame straight
13943 // after a key frame.
13944 start_cdfs: Option<&crate::cdf_state::Cdfs>,
13945 // The key frame's own (padded) reconstruction, which every frame of the
13946 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
13947 // with `LAST_FRAME` alone, exactly as before.
13948 golden: Option<&Picture>,
13949 // The frame two back, held in the slot this frame is about to refresh
13950 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
13951 // inter frames of a GOP, where the frame two back IS the key frame.
13952 altref: Option<&Picture>,
13953 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
13954 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
13955 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
13956 // take. `None` (every caller but the pyramid leaves) codes the frame
13957 // with the reference set unchanged.
13958 last2: Option<&Picture>,
13959 fctx: &crate::decode::FrameCtx,
13960 // Where this frame sits in the coding-order pyramid; `None` is the flat
13961 // one-shown-frame-per-picture stream this encoder wrote before.
13962 pyramid: Option<PyramidFrame>,
13963 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
13964 // them), padded like this one -- the lookahead window the per-block
13965 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
13966 // EMPTY slice codes the frame at one lambda, as before.
13967 lookahead: &[Picture],
13968) -> Result<Encoded> {
13969 picture.check()?;
13970 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
13971 return Err(Error::unsupported(
13972 "AV1 encode",
13973 "an inter frame is coded only for a picture that is a whole number \
13974 of 64x64 superblocks -- the inter tile writer never splits a \
13975 superblock's partition below that",
13976 ));
13977 }
13978 if reference.width != picture.width || reference.height != picture.height {
13979 return Err(Error::unsupported(
13980 "AV1 encode",
13981 "the reference picture must be the same size as the one being coded",
13982 ));
13983 }
13984
13985 // The single slot this crate's inter frames ever predict from or
13986 // refresh (`inter_frame_headers`'s contract): every frame both reads and
13987 // overwrites slot 0, so the frame just coded is always what the next one
13988 // predicts against.
13989 const LAST_SLOT: u8 = 0;
13990 // Slot 0 and slot 2 alternate so the frame two back survives one more
13991 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
13992 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
13993 // in the very slot it will overwrite.
13994 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
13995 let last_slot = pyramid.map_or(
13996 if order_hint <= 1 {
13997 LAST_SLOT
13998 } else if (order_hint - 1) % 2 == 1 {
13999 0
14000 } else {
14001 2
14002 },
14003 |p| p.last_slot,
14004 );
14005 // `render`, not `picture.width`/`picture.height`: `picture` here is
14006 // already padded to a whole number of superblocks (`encode_sequence`'s
14007 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
14008 // every true-edge clamp downstream) must come from the frame's real,
14009 // unpadded size, same as `key_frame_headers_colour` takes `render` and
14010 // not the padded picture in `encode_key_frame_inner`.
14011 let (seq, mut header) = inter_frame_headers_slots(
14012 render.0,
14013 render.1,
14014 base_q_idx,
14015 order_hint,
14016 last_slot,
14017 self_slot,
14018 match pyramid {
14019 Some(p) => p.altref_slot,
14020 None if altref.is_some() => self_slot,
14021 None => GOLDEN_SLOT,
14022 },
14023 )?;
14024 header.render_width = render.0 as u32;
14025 header.render_height = render.1 as u32;
14026 // lane-refs: this frame's motion-compensation kernel, written into the
14027 // header AND armed on the context every prediction reads, in one place so
14028 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
14029 // tile decodes to different pixels than the encoder scored).
14030 header.interpolation_filter = frame_interp_filter();
14031 fctx.interp_filter.set(mc::InterpFilterKind::from_header(
14032 header.interpolation_filter,
14033 ));
14034 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
14035 // The order hint behind each `ref_frame_idx` entry. The flat path's own
14036 // slot plan (`inter_frame_headers_slots`) is: every reference but
14037 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
14038 // `ALTREF_FRAME`, which reads the frame two back when there is one;
14039 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
14040 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
14041 header.order_hints = order_hints;
14042 // lane-last2: `inter_frame_headers_slots` points every un-named
14043 // reference at `last_slot`; the pyramid's leaf chain retains a second,
14044 // older picture and names it here. The caller's `sign_bias` /
14045 // `order_hints` entry 1 is derived from this same slot, so the stack
14046 // scans and `skipModeAllowed` read what the decoder will.
14047 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
14048 header.ref_frame_idx[1] = slot;
14049 }
14050 header.reference_select = reference_select();
14051 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
14052 // per-reference order-hint distance is read by the block SEARCH, which
14053 // runs long before the writer arms these (the distance-scaled search step
14054 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
14055 // never reached the tool).
14056 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
14057 // lane-hpmv: armed here for the same reason the order hints are -- the
14058 // block SEARCH reads it (its eighth-pel stage) long before the writer.
14059 let hp_mv = header.allow_high_precision_mv;
14060 crate::tile::arm_high_precision_mv(hp_mv);
14061 if let Some(p) = pyramid {
14062 header.show_frame = p.show_frame;
14063 header.showable_frame = !p.show_frame;
14064 header.ref_frame_sign_bias = p.sign_bias;
14065 }
14066 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
14067 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
14068 // block inside this frame codes and searches its own `tx_depth`, the same
14069 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
14070 let tx_select = tx_select() && tx_select_inter();
14071 if tx_select {
14072 header.tx_mode = TxMode::Select;
14073 }
14074
14075 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
14076 // lane-palw: the encoder's own in-process reconstruct reads its palette
14077 // colour-index maps back through `decode::palette_onscreen`, which takes
14078 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
14079 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
14080 // them here so the reconstruct clamps a block cut by the frame edge
14081 // exactly as the writer now does.
14082 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
14083 fctx.seg_mi_dims.set(frame_mi_dims);
14084 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
14085 // here (see `encode_key_frame_inner`).
14086 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
14087 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
14088 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
14089 // This frame's own `allow_screen_content_tools`. It can only be set when
14090 // the SEQUENCE offers the bit at all, which is the key frame's decision
14091 // ([`SEQ_SCREEN`]): a frame header that contradicts
14092 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
14093 // encode.
14094 let screen =
14095 seq_screen() && screen_content(&picture_y8, picture.width, true_width, true_height);
14096 header.allow_screen_content_tools = screen;
14097 // lane-txi, as on the key frame: the header bit the writer's own
14098 // `Cdfs` then reads for every luma `tx_type` symbol.
14099 header.reduced_tx_set = !wide_tx_set(screen);
14100 // lane-intertx, desync (a): the frame context this value is read back
14101 // through ([`decode::reduce_inherited_chroma_tx_type`] inside
14102 // `recode_inter_chroma`, and every inter decode helper the search's own
14103 // trial decode shares) must carry THIS frame's bit, not whatever the
14104 // previous frame's trial decode last left in the shared cell -- a stale
14105 // `true` here narrows the chroma allowance the search reconstructs
14106 // against under the one the header's bit actually allows.
14107 fctx.reduced_tx_set_inter.set(header.reduced_tx_set);
14108 // The search prices coefficients against the tables this frame's writer
14109 // starts from, not against the defaults (lane-av1txbits) -- but only on a
14110 // frame the screen detector said no to (lane-av1price2): armed HERE, after
14111 // `screen` exists, and again on every search/tile worker below.
14112 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
14113 let mut luma = Plane {
14114 source: &picture_y8,
14115 reconstruction: vec![128; picture_y8.len()],
14116 width: picture.width,
14117 height: picture.height,
14118 true_width,
14119 true_height,
14120 tile_x0: 0,
14121 tile_y0: 0,
14122 tile_x1: picture.width,
14123 tile_y1: picture.height,
14124 ctx: CoefCtxMap::default(),
14125 };
14126 let mut chroma = [
14127 Plane {
14128 source: &picture_u8,
14129 reconstruction: vec![128; picture_u8.len()],
14130 width: picture.width / 2,
14131 height: picture.height / 2,
14132 true_width: true_width / 2,
14133 true_height: true_height / 2,
14134 tile_x0: 0,
14135 tile_y0: 0,
14136 tile_x1: picture.width / 2,
14137 tile_y1: picture.height / 2,
14138 ctx: CoefCtxMap::default(),
14139 },
14140 Plane {
14141 source: &picture_v8,
14142 reconstruction: vec![128; picture_v8.len()],
14143 width: picture.width / 2,
14144 height: picture.height / 2,
14145 true_width: true_width / 2,
14146 true_height: true_height / 2,
14147 tile_x0: 0,
14148 tile_y0: 0,
14149 tile_x1: picture.width / 2,
14150 tile_y1: picture.height / 2,
14151 ctx: CoefCtxMap::default(),
14152 },
14153 ];
14154
14155 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
14156 let top_arf = matches!(
14157 pyramid,
14158 Some(p) if p.dq_level == DqLevel::TopArf
14159 );
14160 let arfmode_v = arfmode();
14161 let search = Search {
14162 base_q_idx,
14163 deadzone,
14164 lambda: lambda_scale()
14165 * match pyramid {
14166 Some(p) if !p.show_frame => hidden_lambda_factor(),
14167 _ => 1.0,
14168 }
14169 * step
14170 * step,
14171 modes: &KEY_FRAME_MODES,
14172 top_k: prune_top_k_inter(),
14173 screen,
14174 // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose
14175 // offset is the pyramid's own `arf_q_offset`) reads its leaf offer
14176 // set from [`crate::speed::ARFMODE`]; every other frame -- the mid
14177 // and quarter hidden frames, the leaves, the flat path -- keeps the
14178 // full set.
14179 arf_leaf_intra: !top_arf || arfmode_v & 1 == 0,
14180 arf_leaf8: !top_arf || arfmode_v & 2 == 0,
14181 arf_leaf_compound: !top_arf || arfmode_v & 4 == 0,
14182 };
14183 let mode_bits_table = inter_mode_bits();
14184 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
14185 // this frame the NEXT one predicts from. Off (`None`) without a
14186 // lookahead picture or at strength 0.
14187 let tpl_k = tpl_strength();
14188 let window: Vec<&Picture> = lookahead
14189 .iter()
14190 .take_while(|n| n.width == picture.width && n.height == picture.height)
14191 .collect();
14192 let tpl_sources: Vec<Vec<u8>> = window
14193 .iter()
14194 .map(|n| n.y.iter().map(|&v| v as u8).collect())
14195 .collect();
14196 let tpl_cells_x = picture.width / 16;
14197 // `.1` is the propagating map's raw per-cell dependence ratio, which only
14198 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
14199 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> = (tpl_k > 0.0 && !tpl_sources.is_empty())
14200 .then(|| {
14201 if tpl_propagating() {
14202 let mut frames: Vec<&[u8]> = vec![&picture_y8];
14203 frames.extend(tpl_sources.iter().map(Vec::as_slice));
14204 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
14205 (f, Some(r))
14206 } else {
14207 // The shipped map is one factor per 64x64; it is spread over that
14208 // superblock's own 16 cells so the application site below (which
14209 // averages the four cells of a 32x32 block) reads exactly the
14210 // superblock factor, whichever map fed it.
14211 let map = tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
14212 let cells_y = picture.height / 16;
14213 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
14214 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
14215 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
14216 .collect();
14217 (f, None)
14218 }
14219 });
14220 let (tpl_factors, tpl_ratio) = match tpl_both {
14221 Some((f, r)) => (Some(f), r),
14222 None => (None, None),
14223 };
14224
14225 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
14226 // coding surface's: `blocks` carries one entry per 32x32 block the tile
14227 // writer will actually visit, same count it checks `blocks.len()`
14228 // against, which is fewer than the padded surface's own block count
14229 // whenever the true size is not a 64x64 multiple.
14230 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
14231 let (cols, rows) = (cols as usize, rows as usize);
14232 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
14233 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
14234 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
14235 // only when the map is, and `delta_q_res` follows straight into the frame
14236 // header (`write_delta_q_params`) and into the tile writer's own plan.
14237 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
14238 // measured the per-superblock quantizer as a win on both films and a
14239 // 0.5 loss vs libaom on the desktop capture, so a frame that set
14240 // `allow_screen_content_tools` codes no delta syntax at all and stays
14241 // byte-identical to the pre-lane encoder.
14242 // lane-arfq: the level whose `delta_q` strength this frame reads; the
14243 // flat path (no pyramid) is a leaf.
14244 let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level);
14245 let deltaq_res: Option<i32> = tpl_factors
14246 .as_ref()
14247 .filter(|_| !screen)
14248 .and(deltaq_res_log2().map(|r| 1i32 << r));
14249 // The same 16-cell mean the superblock's own lambda takes, clamped to the
14250 // map the frame actually has -- read over the factors or over the raw
14251 // dependence ratios, whichever mapping is asking.
14252 let sb_mean = |m: &[f64], sb: usize| {
14253 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
14254 (0..16)
14255 .map(|i| {
14256 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
14257 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
14258 })
14259 .sum::<f64>()
14260 / 16.0
14261 };
14262 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
14263 // raw dependence ratio; without it (and always without a ratio map, i.e.
14264 // on the one-frame area map) the shipped derivation stands.
14265 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
14266 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
14267 match (libaom, tpl_ratio.as_deref(), r_frame) {
14268 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
14269 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
14270 }
14271 };
14272 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
14273 (Some(f), Some(res)) => {
14274 let libaom = dq_tpl_strength(dq_level);
14275 let mut g: Vec<u8> = (0..sb_cols * _sb_rows)
14276 .map(|sb| sb_qindex(f, res, sb, libaom))
14277 .collect();
14278 // lane-b128m: under 128 superblocks the delta_q syntax is coded
14279 // ONCE per 128 root (the reader's own unit), so all four 64x64
14280 // cells of a root have to be searched -- and quantized -- at the
14281 // one qindex the root's top-left cell codes.
14282 if sb128_on() {
14283 for sb_r in 0.._sb_rows {
14284 for sb_c in 0..sb_cols {
14285 let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
14286 g[sb_r * sb_cols + sb_c] = q;
14287 }
14288 }
14289 }
14290 Some(g)
14291 }
14292 _ => None,
14293 };
14294 // lane-dq census: both mappings on the SAME superblocks, whether or not
14295 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
14296 // off, and the census then prices the default `res = 4` grid).
14297 if dq_census() {
14298 if let Some(f) = &tpl_factors {
14299 let res = deltaq_res.unwrap_or(4);
14300 let off = |libaom: Option<f64>| -> Vec<i32> {
14301 (0..sb_cols * _sb_rows)
14302 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
14303 .collect()
14304 };
14305 let strength = dq_tpl_strength(dq_level);
14306 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
14307 let coded = match (deltaq_res.is_some(), strength) {
14308 (false, _) => "none".to_string(),
14309 (true, None) => "ours".to_string(),
14310 (true, Some(k)) => format!("libaom k={k}"),
14311 };
14312 eprintln!(
14313 "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
14314 sb_cols * _sb_rows,
14315 r_frame.unwrap_or(f64::NAN),
14316 dq_summary(&ours),
14317 dq_summary(&aom),
14318 );
14319 }
14320 }
14321 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
14322 header.delta.q_present = true;
14323 header.delta.q_res = res.trailing_zeros() as u8;
14324 }
14325 // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
14326 // below, so the root search prices the group the writer really codes.
14327 let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
14328 if let Some(g) = &sb_q {
14329 let mut levels: Vec<u8> = g.clone();
14330 levels.sort_unstable();
14331 levels.dedup();
14332 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
14333 }
14334 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
14335 // This frame's tile grid, as in `encode_key_frame_inner`.
14336 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
14337 let layout = crate::tile::TileLayout::new(
14338 header.mi_cols,
14339 header.mi_rows,
14340 tile_cols_log2,
14341 tile_rows_log2,
14342 );
14343 header.tile_info = tile_info_of(&layout, 1);
14344 let header_tile_info = header.tile_info.clone();
14345 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
14346 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
14347 // once per frame (lane-av1rd2), not once per block, which is a whole
14348 // plane's map per 32x32 block and now per leaf too.
14349 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
14350 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
14351 // availability -- intra edges and the MV stack's scans alike -- already
14352 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
14353 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
14354 // giving each job its own planes and its own `MiGrid` therefore leaves
14355 // every decision, and so every coded bit, exactly where the whole-frame
14356 // loop left it, at any tile count and any thread count.
14357 let (frame_width, frame_height) = (picture.width, picture.height);
14358 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
14359 let [cb, cr] = &mut chroma;
14360 let chroma_out = [
14361 crate::par::Shared::new(&mut cb.reconstruction),
14362 crate::par::Shared::new(&mut cr.reconstruction),
14363 ];
14364 let search_tile = |index: usize,
14365 fctx: &crate::decode::FrameCtx|
14366 -> Result<Vec<(usize, Quadrant)>> {
14367 // Thread-local, and this job may be running on a `search_tiles`
14368 // worker: `ref_distance`'s order-hint distance (the scaled motion
14369 // search step) is read by the SEARCH, so every worker arms it or the
14370 // tile's bits depend on the thread count.
14371 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
14372 crate::tile::arm_high_precision_mv(hp_mv);
14373 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
14374 let rect = layout.rect(index);
14375 let mut luma = fresh_plane(
14376 &picture_y8,
14377 frame_width,
14378 frame_height,
14379 true_width,
14380 true_height,
14381 );
14382 let mut chroma = [
14383 fresh_plane(
14384 &picture_u8,
14385 frame_width / 2,
14386 frame_height / 2,
14387 true_width / 2,
14388 true_height / 2,
14389 ),
14390 fresh_plane(
14391 &picture_v8,
14392 frame_width / 2,
14393 frame_height / 2,
14394 true_width / 2,
14395 true_height / 2,
14396 ),
14397 ];
14398 clip_planes_to_tile(&mut luma, &mut chroma, rect);
14399 let mut grid = MiGrid::new(mi_cols, mi_rows);
14400 grid.set_sign_bias(sign_bias);
14401 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
14402 // built once per tile job (`obmc_prediction`).
14403 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
14404 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
14405 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
14406 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
14407 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
14408 grid.set_tile_bounds(
14409 rect.mi_row0 as usize,
14410 rect.mi_col0 as usize,
14411 rect.mi_row1 as usize,
14412 rect.mi_col1 as usize,
14413 );
14414 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
14415 // lane-b128: under a 128x128 superblock the search walks the roots the
14416 // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
14417 // not plain raster -- a search that visits BL before TR builds every mv
14418 // stack and neighbour context off blocks the writer has not coded yet,
14419 // which is what made the write-time drl clamp fire at all (lane-sb128b).
14420 // At a 64 superblock the two orders are identical and this is the same
14421 // raster loop as before.
14422 let sb128_search = sb128_on();
14423 let root_step = if sb128_search { 2 } else { 1 };
14424 let mut roots: Vec<(usize, usize)> = Vec::new();
14425 {
14426 let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
14427 let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
14428 let mut r = r0;
14429 while r < r1 {
14430 let mut c = c0;
14431 while c < c1 {
14432 roots.push((r, c));
14433 c += root_step;
14434 }
14435 r += root_step;
14436 }
14437 }
14438 for (root_r, root_c) in roots {
14439 // The 64x64 cells of this root, in the writer's own order.
14440 let cells: Vec<(usize, usize)> = if sb128_search {
14441 [(0, 0), (0, 1), (1, 0), (1, 1)]
14442 .into_iter()
14443 .map(|(dr, dc)| (root_r + dr, root_c + dc))
14444 .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
14445 .collect()
14446 } else {
14447 vec![(root_r, root_c)]
14448 };
14449 // What the four cells below really cost, against which the whole
14450 // 128x128 candidate is weighed.
14451 let mark128 = blocks.len();
14452 let mut root_cost = 0.0f64;
14453 // The 128 root's own compound pairs, at its 32x32-mi window (the 64
14454 // root builds the same list one size down, per superblock).
14455 let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14456 if header.reference_select && b128_compound() && !screen && sb128_search {
14457 [
14458 (crate::mvstack::GOLDEN_FRAME, golden),
14459 (crate::mvstack::ALTREF_FRAME, altref),
14460 ]
14461 .into_iter()
14462 .filter_map(|(r, pic)| {
14463 pic.map(|p| {
14464 (
14465 r,
14466 p,
14467 crate::mvstack::find_mv_stack_compound(
14468 &grid,
14469 root_r * 16,
14470 root_c * 16,
14471 32,
14472 32,
14473 (crate::mvstack::LAST_FRAME, r),
14474 mi_cols,
14475 mi_rows,
14476 grid.sign_bias_table(),
14477 &[(0, 0); 7],
14478 None,
14479 ),
14480 )
14481 })
14482 })
14483 .collect()
14484 } else {
14485 Vec::new()
14486 };
14487 let root128 = (sb128_search && b128_root() && cells.len() == 4)
14488 .then(|| {
14489 search_root_128(
14490 &mut luma,
14491 &mut chroma,
14492 &grid,
14493 (root_r, root_c),
14494 (rows, cols),
14495 (header.mi_cols, header.mi_rows),
14496 search,
14497 &tpl_factors,
14498 sb_q.as_ref(),
14499 sb_cols,
14500 tpl_cells_x,
14501 base_q_idx,
14502 dq_res,
14503 reference,
14504 &root_compound,
14505 fctx,
14506 )
14507 })
14508 .flatten();
14509 // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
14510 // are priced; the cheaper one competes with the NONE block and with
14511 // the four superblocks below.
14512 let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
14513 let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
14514 .then(|| {
14515 let mut best: Option<(bool, _)> = None;
14516 for horz in [true, false] {
14517 if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
14518 continue;
14519 }
14520 let Some(found) = search_root_128_rect(
14521 &mut luma,
14522 &mut chroma,
14523 &mut grid,
14524 (root_r, root_c),
14525 (rows, cols),
14526 (header.mi_cols, header.mi_rows),
14527 search,
14528 &tpl_factors,
14529 sb_q.as_ref(),
14530 sb_cols,
14531 tpl_cells_x,
14532 base_q_idx,
14533 dq_res,
14534 reference,
14535 &root_compound,
14536 horz,
14537 fctx,
14538 ) else {
14539 continue;
14540 };
14541 if best
14542 .as_ref()
14543 .is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0)
14544 {
14545 best = Some((horz, found));
14546 }
14547 }
14548 best
14549 })
14550 .flatten();
14551 // lane-ab128: and the same root as one of the four AB shapes -- two
14552 // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
14553 // the cheapest joins the candidate list below.
14554 let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
14555 let root_ab = (sb128_search
14556 && (b128_ab() || forced_ab != 0)
14557 && cells.len() == 4
14558 && forced_rect == 0)
14559 .then(|| {
14560 let mut best: Option<(usize, _)> = None;
14561 for symbol in 4..=7usize {
14562 if forced_ab != 0 && usize::from(forced_ab) != symbol {
14563 continue;
14564 }
14565 let Some(found) = search_root_128_ab(
14566 &mut luma,
14567 &mut chroma,
14568 &mut grid,
14569 (root_r, root_c),
14570 (rows, cols),
14571 (header.mi_cols, header.mi_rows),
14572 search,
14573 &tpl_factors,
14574 sb_q.as_ref(),
14575 sb_cols,
14576 tpl_cells_x,
14577 base_q_idx,
14578 reference,
14579 &root_compound,
14580 symbol,
14581 fctx,
14582 ) else {
14583 continue;
14584 };
14585 if best
14586 .as_ref()
14587 .is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0)
14588 {
14589 best = Some((symbol, found));
14590 }
14591 }
14592 best
14593 })
14594 .flatten();
14595 for (sb_r, sb_c) in cells {
14596 // lane-b64: the whole superblock as ONE 64x64 block, tried before
14597 // its quadrants are (`search_skip_64`) and compared against the
14598 // four of them below. Only a superblock wholly inside the true
14599 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
14600 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
14601 // only that the block's half is inside, and the trial is ranked
14602 // over the inside part alone ([`Plane::block_sse`]).
14603 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
14604 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
14605 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
14606 && x64 + SUPERBLOCK <= luma.true_width
14607 && y64 + SUPERBLOCK <= luma.true_height;
14608 let edge_inside = b64_edge()
14609 && crate::tile::has_half(
14610 sb_c as u32 * crate::tile::SB_MI,
14611 crate::tile::SB_MI,
14612 header.mi_cols,
14613 )
14614 && crate::tile::has_half(
14615 sb_r as u32 * crate::tile::SB_MI,
14616 crate::tile::SB_MI,
14617 header.mi_rows,
14618 );
14619 let sb64_legal = b64_root()
14620 && sb_r * 2 + 1 < rows
14621 && sb_c * 2 + 1 < cols
14622 && (whole_inside || edge_inside);
14623 // One lambda for the whole superblock, the same mean the 32x32
14624 // level takes over its own four tpl cells: the 64-vs-four-32
14625 // comparison below weighs one cost against four, so both sides
14626 // have to be priced at the same lambda.
14627 let sb_search = match &tpl_factors {
14628 // lane-deltaq: with a per-superblock quantizer the lambda
14629 // comes from that quantizer, not from the raw map factor --
14630 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
14631 Some(_) if sb_q.is_some() => sb_q_search(
14632 sb_q.as_ref().expect("armed"),
14633 sb_cols,
14634 base_q_idx,
14635 (sb_r, sb_c),
14636 search,
14637 ),
14638 Some(f) if sb64_legal => {
14639 let mean = (0..16)
14640 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
14641 .sum::<f64>()
14642 / 16.0;
14643 Search {
14644 lambda: search.lambda * mean,
14645 ..search
14646 }
14647 }
14648 _ => search,
14649 };
14650 let mark = blocks.len();
14651 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
14652 let mut sb_cost = 0.0f64;
14653 if sb64_legal {
14654 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
14655 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
14656 let stack =
14657 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
14658 // lane-b64b: the `LAST` + extra-reference pairs at this
14659 // superblock's own 16x16-mi window, the same stacks the tile
14660 // writer's `Whole64` arm rebuilds. Empty unless the frame
14661 // codes `reference_select`, which is what gates the syntax.
14662 // `!screen` for the same reason the residual arm is gated
14663 // there ([`b64_residual`]): a desktop capture's superblocks
14664 // are flat runs the skip arm already codes for nothing, and
14665 // MEASURED, compound at the root cost it +33.4/-23.8 ->
14666 // +33.7/-23.6 while both film rows gained (step 1's table).
14667 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14668 if header.reference_select && b64_compound() && !screen {
14669 [
14670 (crate::mvstack::GOLDEN_FRAME, golden),
14671 (crate::mvstack::ALTREF_FRAME, altref),
14672 ]
14673 .into_iter()
14674 .filter_map(|(r, pic)| {
14675 pic.map(|p| {
14676 (
14677 r,
14678 p,
14679 crate::mvstack::find_mv_stack_compound(
14680 &grid,
14681 mi_row,
14682 mi_col,
14683 16,
14684 16,
14685 (crate::mvstack::LAST_FRAME, r),
14686 mi_cols,
14687 mi_rows,
14688 grid.sign_bias_table(),
14689 &[(0, 0); 7],
14690 None,
14691 ),
14692 )
14693 })
14694 })
14695 .collect()
14696 } else {
14697 Vec::new()
14698 };
14699 if let Some((cost, block)) = search_skip_64(
14700 &mut luma,
14701 &mut chroma,
14702 (x64, y64),
14703 (SUPERBLOCK, SUPERBLOCK),
14704 &sb_search,
14705 b64_residual() && !screen,
14706 reference,
14707 &stack,
14708 &sb_compound,
14709 fctx,
14710 ) {
14711 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
14712 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
14713 let cost = cost
14714 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
14715 sb64 = Some((cost, block, after));
14716 }
14717 }
14718 // A superblock whose 64x64 trial already codes almost nothing per
14719 // pixel is taken outright and its quadrants are never searched --
14720 // the same `split_rd_breakout` shape the 32x32 level uses one
14721 // size up, and where this lever BUYS wall instead of spending it.
14722 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
14723 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, sb_search.lambda)
14724 });
14725 for quadrant in 0..if early64 { 0 } else { 4 } {
14726 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
14727 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
14728 // decision under it (partition, mode, tx, motion) reads
14729 // `search.lambda`, so scaling the one field here scales all
14730 // of them. 32x32 and not the 16x16 the map is built at
14731 // because the whole-vs-split comparison right below weighs
14732 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
14733 // would make those two numbers incomparable.
14734 let search = match &tpl_factors {
14735 // lane-deltaq: the quantizer is a SUPERBLOCK-level
14736 // symbol, so all four quadrants take their superblock's
14737 // own qindex and the lambda it implies. No granularity is
14738 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
14739 // factor per superblock, shared by its sixteen cells.
14740 Some(_) if sb_q.is_some() => sb_q_search(
14741 sb_q.as_ref().expect("armed"),
14742 sb_cols,
14743 base_q_idx,
14744 (sb_r, sb_c),
14745 search,
14746 ),
14747 Some(f) => {
14748 let mean = (0..4)
14749 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
14750 .sum::<f64>()
14751 / 4.0;
14752 Search {
14753 lambda: search.lambda * mean,
14754 ..search
14755 }
14756 }
14757 None => search,
14758 };
14759 // Same filter as the tile writer's: a quadrant whose own mi
14760 // origin is not inside the true frame is never coded.
14761 if r32 >= rows || c32 >= cols {
14762 continue;
14763 }
14764 // spec `decode_partition`'s hasRows/hasCols recomputed at this
14765 // 32x32 block's own half (`crate::tile::has_half`), same as
14766 // the key frame search: the true frame edge can fall inside a
14767 // quadrant a superblock-level check already let through, and
14768 // such a quadrant cannot be left whole -- it must split into
14769 // the 16x16 leaves that are actually inside the true frame
14770 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
14771 // arm).
14772 let (has_cols32, has_rows32) = (
14773 crate::tile::has_half(
14774 c32 as u32 * crate::tile::BLOCK_MI,
14775 crate::tile::BLOCK_MI,
14776 header.mi_cols,
14777 ),
14778 crate::tile::has_half(
14779 r32 as u32 * crate::tile::BLOCK_MI,
14780 crate::tile::BLOCK_MI,
14781 header.mi_rows,
14782 ),
14783 );
14784 if has_cols32 && has_rows32 {
14785 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
14786 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
14787 let stack = find_mv_stack(
14788 &grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows,
14789 );
14790 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
14791 (crate::mvstack::LAST2_FRAME, last2),
14792 (crate::mvstack::GOLDEN_FRAME, golden),
14793 (crate::mvstack::ALTREF_FRAME, altref),
14794 ]
14795 .into_iter()
14796 .filter_map(|(r, pic)| {
14797 pic.map(|p| {
14798 (
14799 r,
14800 p,
14801 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
14802 )
14803 })
14804 })
14805 .collect();
14806 let extra: Vec<(i8, &Picture, &MvStack)> =
14807 extra_stacks.iter().map(|(r, p, st)| (*r, *p, st)).collect();
14808 // The COMPOUND stack of each `LAST` + extra pair, off the
14809 // same grid (and the same armed sign bias) the tile writer
14810 // rebuilds it from. Empty unless this frame codes
14811 // `reference_select`, which is what gates the syntax.
14812 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14813 if header.reference_select {
14814 extra_stacks
14815 .iter()
14816 .map(|&(r, p, _)| {
14817 (
14818 r,
14819 p,
14820 crate::mvstack::find_mv_stack_compound(
14821 &grid,
14822 mi_row,
14823 mi_col,
14824 8,
14825 8,
14826 (crate::mvstack::LAST_FRAME, r),
14827 mi_cols,
14828 mi_rows,
14829 grid.sign_bias_table(),
14830 &[(0, 0); 7],
14831 None,
14832 ),
14833 )
14834 })
14835 .collect()
14836 } else {
14837 Vec::new()
14838 };
14839
14840 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
14841 let (block, mut cost_whole) = search_inter_block(
14842 &mut luma,
14843 &mut chroma,
14844 (x, y),
14845 &search,
14846 &mode_bits_table,
14847 reference,
14848 &stack,
14849 &extra,
14850 &compound,
14851 &grid,
14852 (mi_row, mi_col),
14853 (mi_rows, mi_cols),
14854 fctx,
14855 );
14856 cost_whole += search.lambda * partition_bits(BLOCK, false);
14857 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
14858
14859 // What four 16x16 leaves cost instead (spec
14860 // PARTITION_SPLIT at BLOCK_32X32, which
14861 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
14862 // already writes for a straddling quadrant). Each leaf is
14863 // searched against the reconstruction -- and the `mi`
14864 // grid -- the ones before it left, exactly as the writer
14865 // and the decoder will read them.
14866 //
14867 // A block the whole-32 search left skipped (no residual
14868 // at all) is not offered the split: libaom prunes the
14869 // same way at cpu-used 6, and it is where the wall would
14870 // otherwise go on static content.
14871 let leaf_positions: Vec<(usize, usize)> =
14872 (0..4).map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)).collect();
14873 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
14874 crate::tile::has_half(
14875 sc as u32 * crate::tile::SUB_MI,
14876 crate::tile::SUB_MI,
14877 header.mi_cols,
14878 ) && crate::tile::has_half(
14879 sr as u32 * crate::tile::SUB_MI,
14880 crate::tile::SUB_MI,
14881 header.mi_rows,
14882 )
14883 });
14884 // The breakout above: a 32x32 block that codes almost
14885 // nothing is not offered the split at all.
14886 let breakout = split_breakout_coeffs();
14887 let split = (!block.skip
14888 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
14889 && (breakout == 0 || block.luma.len() > 4 * breakout)
14890 && leaves_legal
14891 && split_inter_blocks())
14892 .then(|| {
14893 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
14894 let mut cost = search.lambda * partition_bits(BLOCK, true);
14895 let mut leaves = Vec::with_capacity(4);
14896 for &(sr, sc) in &leaf_positions {
14897 let (mi_row, mi_col) = (sr * 4, sc * 4);
14898 let (lx, ly) = (sc * SUB, sr * SUB);
14899 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
14900 let stack = find_mv_stack(
14901 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
14902 );
14903 let cstacks = leaf_compound_stacks(
14904 &grid,
14905 mi_row,
14906 mi_col,
14907 4,
14908 4,
14909 mi_cols,
14910 mi_rows,
14911 header.reference_select,
14912 golden,
14913 altref,
14914 );
14915 let (leaf, leaf_cost) = code_square_inter(
14916 &mut luma,
14917 &mut chroma,
14918 (lx, ly),
14919 SUB,
14920 &search,
14921 &mode_bits_table,
14922 reference,
14923 &stack,
14924 &cstacks,
14925 &grid,
14926 (mi_row, mi_col),
14927 (mi_rows, mi_cols),
14928 &obmc_refs,
14929 fctx,
14930 );
14931 let leaf_cost =
14932 leaf_cost + search.lambda * partition_bits(SUB, false);
14933 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
14934
14935 // And what four 8x8 leaves cost instead --
14936 // the same tree one step further down, which
14937 // the writer codes as a real PARTITION_SPLIT
14938 // at BLOCK_16X16 (lane-av1rd2). Same
14939 // skipped-block prune as the level above.
14940 let eight = (!leaf.skip
14941 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
14942 && (breakout == 0 || leaf.luma.len() > breakout)
14943 && split_inter_8()
14944 // lane-arfmode: arm 2 makes 16x16 the top
14945 // ARF's leaf floor -- the RD-optional 8x8
14946 // comparison is not offered. Counted only
14947 // when every other prune let it through,
14948 // so the counter means "refused", not
14949 // "never considered". The spec-forced 8x8s
14950 // at a straddling 16x16 (the
14951 // `sub_positions` path below) are a
14952 // different site and stay.
14953 && (search.arf_leaf8 || arfmode_hit_and_no()))
14954 .then(|| {
14955 restore(&mut luma, &mut chroma, (lx, ly), SUB, &leaf_base);
14956 let mut cost8 = search.lambda
14957 * (partition_bits(SUB, true)
14958 + 4.0 * partition_bits(8, false));
14959 let mut eight = Vec::with_capacity(4);
14960 for i in 0..4 {
14961 let (mr, mc) = (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
14962 let stack8 = find_mv_stack(
14963 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
14964 );
14965 let cstacks8: Vec<(
14966 i8,
14967 &Picture,
14968 crate::mvstack::CompoundMvStack,
14969 )> = if header.reference_select && leaf_compound() {
14970 [
14971 (crate::mvstack::GOLDEN_FRAME, golden),
14972 (crate::mvstack::ALTREF_FRAME, altref),
14973 ]
14974 .into_iter()
14975 .filter_map(|(r, pic)| {
14976 pic.map(|p| {
14977 (
14978 r,
14979 p,
14980 crate::mvstack::find_mv_stack_compound(
14981 &grid,
14982 mr,
14983 mc,
14984 2,
14985 2,
14986 (crate::mvstack::LAST_FRAME, r),
14987 mi_cols,
14988 mi_rows,
14989 grid.sign_bias_table(),
14990 &[(0, 0); 7],
14991 None,
14992 ),
14993 )
14994 })
14995 })
14996 .collect()
14997 } else {
14998 Vec::new()
14999 };
15000 let (leaf8, cost) = code_square_inter(
15001 &mut luma,
15002 &mut chroma,
15003 (lx + (i % 2) * 8, ly + (i / 2) * 8),
15004 8,
15005 &search,
15006 &mode_bits_table,
15007 reference,
15008 &stack8,
15009 &cstacks8,
15010 &grid,
15011 (mr, mc),
15012 (mi_rows, mi_cols),
15013 &obmc_refs,
15014 fctx,
15015 );
15016 cost8 += cost;
15017 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
15018 eight.push(leaf8);
15019 }
15020 (eight, cost8)
15021 });
15022 match eight {
15023 Some((eight, cost8)) if cost8 < leaf_cost => {
15024 partition_hit(3);
15025 cost += cost8;
15026 leaves.push(BlockCoeffs {
15027 eight: Some(eight),
15028 ..BlockCoeffs::default()
15029 });
15030 continue;
15031 }
15032 Some(_) => {
15033 restore(&mut luma, &mut chroma, (lx, ly), SUB, &after_leaf)
15034 }
15035 None => {}
15036 }
15037 partition_hit(2);
15038 cost += leaf_cost;
15039 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
15040 leaves.push(leaf);
15041 }
15042 (leaves, cost)
15043 });
15044 if let Some((leaves, cost)) = split {
15045 if cost < cost_whole {
15046 // The leaves' own `mi` cells are already in the
15047 // grid, and their reconstruction is what the
15048 // planes hold.
15049 partition_hit(1);
15050 sb_cost += cost;
15051 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
15052 continue;
15053 }
15054 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
15055 }
15056 partition_hit(0);
15057 sb_cost += cost_whole;
15058 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
15059 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
15060 } else {
15061 // The sub-positions actually inside the true frame, same
15062 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
15063 let sub_positions: Vec<(usize, usize)> = (0..4)
15064 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
15065 .filter(|&(sr, sc)| {
15066 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
15067 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
15068 })
15069 .collect();
15070 // Each leaf searches intra against its own `NEARESTMV`
15071 // candidate (`code_square_inter`), same real-inter choice
15072 // `search_inter_block` makes for a whole 32x32 block, at
15073 // this leaf's own 4x4-mi mv-stack window -- unless the
15074 // leaf's own half itself straddles the true edge, which
15075 // it codes as two (or one, at a true corner) 8x8 leaves
15076 // (`crate::tile::write_leaf8`'s inter counterpart),
15077 // mirroring the key frame search's straddling-16x16
15078 // handling above (lane-av1inter8).
15079 let mut leaves = Vec::with_capacity(sub_positions.len());
15080 for (sr, sc) in sub_positions {
15081 let (has_cols16, has_rows16) = (
15082 crate::tile::has_half(
15083 sc as u32 * crate::tile::SUB_MI,
15084 crate::tile::SUB_MI,
15085 header.mi_cols,
15086 ),
15087 crate::tile::has_half(
15088 sr as u32 * crate::tile::SUB_MI,
15089 crate::tile::SUB_MI,
15090 header.mi_rows,
15091 ),
15092 );
15093 if has_cols16 && has_rows16 {
15094 let (x, y) = (sc * SUB, sr * SUB);
15095 let (mi_row, mi_col) = (sr * 4, sc * 4);
15096 let stack = find_mv_stack(
15097 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
15098 );
15099 let cstacks = leaf_compound_stacks(
15100 &grid,
15101 mi_row,
15102 mi_col,
15103 4,
15104 4,
15105 mi_cols,
15106 mi_rows,
15107 header.reference_select,
15108 golden,
15109 altref,
15110 );
15111 let (block, _) = code_square_inter(
15112 &mut luma,
15113 &mut chroma,
15114 (x, y),
15115 SUB,
15116 &search,
15117 &mode_bits_table,
15118 reference,
15119 &stack,
15120 &cstacks,
15121 &grid,
15122 (mi_row, mi_col),
15123 (mi_rows, mi_cols),
15124 &obmc_refs,
15125 fctx,
15126 );
15127 // One publication point for every coded leaf
15128 // (`record_mi`): this site used to spell the vote
15129 // out with `ref_frame` pinned to LAST and `mv1`
15130 // to (0,0), which is the encoder-grid-drift class
15131 // -- correct only for as long as a leaf can never
15132 // be compound.
15133 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
15134 leaves.push(block);
15135 } else {
15136 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
15137 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
15138 let mut eight = Vec::with_capacity(2);
15139 for i in 0..4 {
15140 let leaf_x = x_sub + (i % 2) * 8;
15141 let leaf_y = y_sub + (i / 2) * 8;
15142 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
15143 continue;
15144 }
15145 let (mi_row, mi_col) =
15146 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
15147 let stack = find_mv_stack(
15148 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
15149 );
15150 let cstacks = leaf_compound_stacks(
15151 &grid,
15152 mi_row,
15153 mi_col,
15154 2,
15155 2,
15156 mi_cols,
15157 mi_rows,
15158 header.reference_select,
15159 golden,
15160 altref,
15161 );
15162 let (leaf, _) = code_square_inter(
15163 &mut luma,
15164 &mut chroma,
15165 (leaf_x, leaf_y),
15166 8,
15167 &search,
15168 &mode_bits_table,
15169 reference,
15170 &stack,
15171 &cstacks,
15172 &grid,
15173 (mi_row, mi_col),
15174 (mi_rows, mi_cols),
15175 &obmc_refs,
15176 fctx,
15177 );
15178 // Same publication point as the 16x16
15179 // straddling leaf above (`record_mi`).
15180 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
15181 eight.push(leaf);
15182 }
15183 leaves.push(BlockCoeffs {
15184 eight: Some(eight),
15185 ..BlockCoeffs::default()
15186 });
15187 }
15188 }
15189 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
15190 }
15191 }
15192 // The 64x64 root against what its four quadrants really cost.
15193 if let Some((cost64, block, after)) = sb64
15194 && (early64
15195 || cost64
15196 < sb_cost
15197 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
15198 {
15199 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15200 if block.inter.is_some_and(|i| i.ref1.is_some()) {
15201 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15202 }
15203 if !whole_inside {
15204 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15205 }
15206 blocks.truncate(mark);
15207 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
15208 // Overwrites every 16x16 mi cell the quadrant searches
15209 // published under this superblock, so the next block's stack
15210 // is built off the block that was really coded.
15211 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
15212 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
15213 for q in 1..4 {
15214 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
15215 blocks.push((r32 * cols + c32, Quadrant::Covered));
15216 }
15217 root_cost += cost64;
15218 } else {
15219 root_cost += sb_cost;
15220 }
15221 }
15222 // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
15223 // `partition_w128` symbol) against what its four superblocks really
15224 // cost, the same weighing the 64 root does one size down. Both sides
15225 // carry their own partition symbol, so the comparison is complete.
15226 // The root candidates, each tagged with the PARTITION symbol its
15227 // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
15228 // shapes (lane-ab128).
15229 let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
15230 if let Some((c, l, b, a)) = root128 {
15231 cands.push((c, l, 0, vec![b], a));
15232 }
15233 if let Some((horz, (c, l, halves, a))) = root_rect {
15234 cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
15235 }
15236 if let Some((symbol, (c, l, pieces, a))) = root_ab {
15237 cands.push((c, l, symbol, pieces.to_vec(), a));
15238 }
15239 // The witness knobs drop every other arm outright: on synthetic
15240 // content the whole block always wins its own comparison.
15241 if forced_rect != 0 {
15242 cands.retain(|c| c.2 == 1 || c.2 == 2);
15243 }
15244 if forced_ab != 0 {
15245 cands.retain(|c| c.2 == usize::from(forced_ab));
15246 }
15247 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
15248 // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
15249 // superblock arm codes the delta_q group too -- the Whole64 writer
15250 // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
15251 // with `!sb128_armed()`) and every smaller shape below it pass
15252 // `is_whole_sb = false` under a 128 grid, so the arm's first
15253 // (root-origin) superblock codes the group even when skipped. Only the skipped 128
15254 // NONE root escapes it, so the split side is charged here at the same
15255 // root lambda the candidates are priced with.
15256 let split_dq =
15257 delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
15258 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
15259 && (cost128
15260 < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
15261 // The witness knobs take the root whatever it costs, so the
15262 // forced block really reaches the writer.
15263 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
15264 || forced_rect != 0
15265 || forced_ab != 0)
15266 {
15267 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
15268 blocks.truncate(mark128);
15269 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
15270 let at = (root_r * 2) * cols + root_c * 2;
15271 match shape {
15272 0 => {
15273 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15274 let block = halves.into_iter().next().expect("the NONE arm's block");
15275 record_mi(
15276 &mut grid,
15277 root_r * 16,
15278 root_c * 16,
15279 32,
15280 block.inter,
15281 block.skip,
15282 );
15283 blocks.push((at, Quadrant::Whole128(block)));
15284 }
15285 // lane-ab128: three pieces, published at their own footprints
15286 // in the writer's own order ([`ab128_pieces`]).
15287 symbol @ 4..=7 => {
15288 B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15289 for (((mr, mc), (w, h)), piece) in
15290 ab128_pieces(symbol, (root_r * 16, root_c * 16))
15291 .iter()
15292 .zip(&halves)
15293 {
15294 record_mi_rect(
15295 &mut grid,
15296 *mr,
15297 *mc,
15298 (w / 4, h / 4),
15299 piece.inter,
15300 piece.skip,
15301 );
15302 }
15303 blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
15304 }
15305 symbol => {
15306 let horz = symbol == 1;
15307 if horz {
15308 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15309 } else {
15310 B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15311 }
15312 let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
15313 for (i, half) in halves.iter().enumerate() {
15314 let (mr, mc) = if horz {
15315 (root_r * 16 + i * 16, root_c * 16)
15316 } else {
15317 (root_r * 16, root_c * 16 + i * 16)
15318 };
15319 record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
15320 }
15321 blocks.push((at, Quadrant::Rect128(horz, halves)));
15322 }
15323 }
15324 for q in 1..16 {
15325 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
15326 blocks.push((r32 * cols + c32, Quadrant::Covered));
15327 }
15328 }
15329 }
15330 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
15331 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
15332 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
15333 for (&out, tile) in chroma_out.iter().zip(&chroma) {
15334 copy_rect(
15335 out,
15336 &tile.reconstruction,
15337 frame_width / 2,
15338 x0 / 2,
15339 y0 / 2,
15340 x1.div_ceil(2),
15341 y1.div_ceil(2),
15342 );
15343 }
15344 Ok(blocks)
15345 };
15346 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
15347 .into_iter()
15348 .flatten()
15349 {
15350 blocks[at] = quadrant;
15351 }
15352
15353 // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
15354 // superblock roots the search left whole, so a flat BD result is
15355 // attributable (class `gate-blind-to-feature`). A key frame codes none:
15356 // only the inter writer has a 128x128 block.
15357 if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
15358 let whole = blocks
15359 .iter()
15360 .filter(|q| matches!(q, Quadrant::Whole128(_)))
15361 .count();
15362 let roots = blocks
15363 .iter()
15364 .filter(|q| !matches!(q, Quadrant::Covered))
15365 .count();
15366 // lane-b128r: of those roots, how many code a REAL residual rather
15367 // than the skip-only block lane-b128 shipped -- the fire count this
15368 // arm's own gate row is read against.
15369 let residual = blocks
15370 .iter()
15371 .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
15372 .count();
15373 // lane-b128r: and how many named a second reference (the compound
15374 // arm at the 128 root).
15375 let compound = blocks
15376 .iter()
15377 .filter(
15378 |q| matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some())),
15379 )
15380 .count();
15381 // lane-b128hv: and how many roots took a rect cut instead, per shape
15382 // -- the HORZ/VERT fire count the gate rows are read against.
15383 let horz = blocks
15384 .iter()
15385 .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
15386 .count();
15387 let vert = blocks
15388 .iter()
15389 .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
15390 .count();
15391 let rect_compound = blocks
15392 .iter()
15393 .filter(|q| {
15394 matches!(q, Quadrant::Rect128(_, hs)
15395 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
15396 })
15397 .count();
15398 // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
15399 // .. _VERT_B order -- the per-shape fire count its gate rows are read
15400 // against.
15401 let ab: [usize; 4] = std::array::from_fn(|i| {
15402 blocks
15403 .iter()
15404 .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
15405 .count()
15406 });
15407 eprintln!(
15408 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
15409 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
15410 compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
15411 {roots} coded blocks ({:.1}% of the frame's area at 128)",
15412 ab[0],
15413 ab[1],
15414 ab[2],
15415 ab[3],
15416 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
15417 / blocks.len().max(1) as f64,
15418 );
15419 }
15420 let modes = blocks
15421 .iter()
15422 .flat_map(Quadrant::blocks)
15423 .map(|b| b.mode)
15424 .collect::<Vec<_>>();
15425 let inter_block_share = blocks
15426 .iter()
15427 .flat_map(Quadrant::blocks)
15428 .filter(|b| b.inter.is_some())
15429 .count() as f64
15430 / modes.len() as f64;
15431 for block in blocks.iter().flat_map(Quadrant::blocks) {
15432 if let Some(info) = block.inter {
15433 let r = (info.ref_frame as usize).min(7);
15434 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15435 }
15436 }
15437 #[cfg(test)]
15438 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
15439 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
15440 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
15441 // next frame's writer starts from them -- exactly what
15442 // `crate::stream::stored_cdfs_for` hands the decoder.
15443 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
15444 let mut cdfs = start_cdfs
15445 .cloned()
15446 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
15447 // lane-txi: set per frame, never inherited from the snapshot the
15448 // previous frame stored -- the content gate can flip the bit between
15449 // frames (class `per-tile-state-not-reset`).
15450 cdfs.reduced_tx_set = header.reduced_tx_set;
15451 let start_cdfs = CdfSnapshot(cdfs);
15452 let reference_select_bit = header.reference_select;
15453 let switchable_motion_mode = header.is_motion_mode_switchable;
15454 let warped_motion = header.allow_warped_motion;
15455 let order_hint_bits = seq.order_hint_bits;
15456 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
15457 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
15458 // What this frame stores is the LARGEST tile's end-of-tile tables --
15459 // its own header's `context_update_tile_id` (spec 7.20), which
15460 // `tile_info_of` set to exactly that tile.
15461 let store_tile = layout.largest_tile();
15462 let end_cdfs = std::cell::RefCell::new(None);
15463 // As in `encode_key_frame_inner`: every tile starts from this frame's
15464 // own tables, so no tile depends on any other.
15465 let code_tiles = |bits: u8,
15466 sb_cols: usize,
15467 cdef_grid: &[u8],
15468 units: &[Option<crate::restoration::WienerInfo>]|
15469 -> Result<Vec<Vec<u8>>> {
15470 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
15471 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
15472 crate::tile::arm_delta_q(
15473 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
15474 sb_cols,
15475 sb_q.clone().unwrap_or_default(),
15476 base_q_idx,
15477 );
15478 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
15479 crate::tile::arm_sb128(sb128_on());
15480 crate::tile::arm_sign_bias(sign_bias);
15481 // Thread-locals: every tile job arms its own worker.
15482 crate::tile::arm_reference_select(reference_select_bit);
15483 crate::tile::arm_motion_mode(switchable_motion_mode);
15484 crate::tile::arm_warped_motion(warped_motion);
15485 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
15486 crate::tile::arm_high_precision_mv(hp_mv);
15487 crate::tile::arm_screen(screen);
15488 crate::tile::arm_frame_mi_dims(frame_mi_dims);
15489 crate::tile::arm_filter_intra(filter_intra_on());
15490 let mut cdfs = start_cdfs.0.clone();
15491 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
15492 // Each tile's own MV grid: a candidate scan never reaches past
15493 // the tile's bounds, so a grid holding only this tile's own
15494 // blocks reads exactly as the decoder's frame-wide one does
15495 // under `MiGrid::set_tile_bounds`.
15496 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
15497 mv_grid.set_sign_bias(sign_bias);
15498 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
15499 mi_cols,
15500 mi_rows,
15501 base_q_idx,
15502 &blocks,
15503 tx_select,
15504 &mut cdfs,
15505 layout.rect(index),
15506 &mut mv_grid,
15507 )?;
15508 Ok((bytes, Some(cdfs)))
15509 })?;
15510 if let Some(cdfs) = stored {
15511 *end_cdfs.borrow_mut() = Some(cdfs);
15512 }
15513 Ok(out)
15514 };
15515 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
15516 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
15517 // this tile against the same single-slot reference this encoder predicted
15518 // from, under each candidate level.
15519 // The reference a DECODER holds is this frame's cropped size, not the
15520 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
15521 // reference whose height is not the header's own `frame_height` (spec
15522 // 7.9's compatible-size rule), and the chained-decode round trips prove
15523 // the two predict identically.
15524 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
15525 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
15526 reference.clone()
15527 } else {
15528 Picture {
15529 width: fw,
15530 height: fh,
15531 y: crop_plane(&reference.y, reference.width, fw, fh),
15532 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
15533 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
15534 }
15535 };
15536 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
15537 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
15538 // blocks may name GOLDEN needs that plane too, cropped the same way.
15539 let trial_golden = golden.map(|g| {
15540 if (g.width, g.height) == (fw, fh) {
15541 g.clone()
15542 } else {
15543 Picture {
15544 width: fw,
15545 height: fh,
15546 y: crop_plane(&g.y, g.width, fw, fh),
15547 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
15548 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
15549 }
15550 }
15551 });
15552 let trial_altref = altref.map(|a| {
15553 if (a.width, a.height) == (fw, fh) {
15554 a.clone()
15555 } else {
15556 Picture {
15557 width: fw,
15558 height: fh,
15559 y: crop_plane(&a.y, a.width, fw, fh),
15560 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
15561 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
15562 }
15563 }
15564 });
15565 let trial_last2 = last2.map(|l| {
15566 if (l.width, l.height) == (fw, fh) {
15567 l.clone()
15568 } else {
15569 Picture {
15570 width: fw,
15571 height: fh,
15572 y: crop_plane(&l.y, l.width, fw, fh),
15573 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
15574 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
15575 }
15576 }
15577 });
15578 let mut refs: [Option<&Picture>; 8] = [None; 8];
15579 refs[1] = Some(&trial_ref);
15580 refs[2] = trial_last2.as_ref();
15581 refs[4] = trial_golden.as_ref();
15582 refs[7] = trial_altref.as_ref();
15583 let refpix = crate::decode::RefPix::ready(refs);
15584 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
15585 // sum the block search believed it was minimising. Against the
15586 // post-filter per-frame PSNR the gate prints, this separates a trial
15587 // whose reconstruction is a lie from a filter stage that undoes the win.
15588 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
15589 let sse: u64 = luma
15590 .reconstruction
15591 .chunks(luma.width)
15592 .take(luma.true_height)
15593 .zip(picture_y8.chunks(luma.width))
15594 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
15595 .map(|(&r, &s)| {
15596 let d = i64::from(r) - i64::from(s);
15597 (d * d) as u64
15598 })
15599 .sum();
15600 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
15601 }
15602 let post = |luma: &Plane<'_>, tag: &str| {
15603 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
15604 return;
15605 }
15606 let sse: u64 = luma
15607 .reconstruction
15608 .chunks(luma.width)
15609 .take(luma.true_height)
15610 .zip(picture_y8.chunks(luma.width))
15611 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
15612 .map(|(&r, &s)| {
15613 let d = i64::from(r) - i64::from(s);
15614 (d * d) as u64
15615 })
15616 .sum();
15617 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
15618 };
15619 pick_and_apply_filters(
15620 &mut header,
15621 &mut luma,
15622 &mut chroma,
15623 [&picture_y8, &picture_u8, &picture_v8],
15624 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
15625 // this frame's own `tx_select`, so the search runs under inter
15626 // `TxMode::Select` too (it used to skip and leave every inter frame
15627 // unfiltered once Select became the default).
15628 true,
15629 &mut tiles,
15630 search.lambda,
15631 fctx,
15632 &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows),
15633 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
15634 // are what the NEXT frame writes from, so the winning re-code
15635 // publishes its own into `end_cdfs` -- the first write's are stale
15636 // the moment a second tile is coded.
15637 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
15638 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
15639 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
15640 crate::decode::decode_inter_frame_tiles_lr(
15641 &payloads,
15642 &header_tile_info,
15643 h.mi_cols,
15644 h.mi_rows,
15645 base_q_idx,
15646 h.frame_width,
15647 h.frame_height,
15648 &refpix,
15649 cdef,
15650 lf,
15651 h.allow_high_precision_mv,
15652 h.force_integer_mv,
15653 Some(fctx.interp_filter.get()),
15654 seq.enable_dual_filter,
15655 h.reference_select,
15656 // lane-txi: this frame's own bit, not the hardcoded `true`
15657 // the wrapper used to pass.
15658 h.reduced_tx_set,
15659 tx_select,
15660 lr,
15661 // The trial decode re-reads the tile the writer just wrote,
15662 // so it starts from the same tables the writer did (this
15663 // frame's `start_cdfs`), not from the defaults.
15664 Some(start_cdfs.0.clone()),
15665 sign_bias,
15666 h.allow_screen_content_tools,
15667 switchable_motion_mode,
15668 h.allow_warped_motion,
15669 seq.enable_filter_intra,
15670 // lane-deltaq: this frame's own delta_q/delta_lf params, so
15671 // the trial decode reads the per-superblock `delta_qindex`
15672 // syntax the writer just wrote.
15673 h.delta.clone(),
15674 fctx,
15675 )
15676 },
15677 )?;
15678 post(&luma, "EC_POSTFILTER");
15679 let mut cdfs = end_cdfs
15680 .into_inner()
15681 .unwrap_or_else(|| start_cdfs.0.clone());
15682 cdfs.reset_counts();
15683 let next_cdfs = CdfSnapshot(cdfs);
15684 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
15685 header.tile_info.tile_size_bytes = tile_size_bytes;
15686 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
15687 let mut stream = temporal_delimiter();
15688 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
15689
15690 let [u, v] = chroma;
15691 Ok(Encoded {
15692 stream,
15693 modes,
15694 inter_block_share,
15695 reconstruction: Picture {
15696 width: luma.width,
15697 height: luma.height,
15698 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15699 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15700 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15701 },
15702 tile,
15703 mi_cols: header.mi_cols,
15704 mi_rows: header.mi_rows,
15705 base_q_idx,
15706 tx_select,
15707 switchable_motion_mode,
15708 screen,
15709 reduced_tx_set: header.reduced_tx_set,
15710 start_cdfs: Box::new(start_cdfs),
15711 next_cdfs: Box::new(next_cdfs),
15712 loop_filter: header.loop_filter,
15713 cdef: header.cdef,
15714 loop_restoration: header.loop_restoration,
15715 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
15716 // intra frames only).
15717 allow_intrabc: false,
15718 delta: header.delta.clone(),
15719 })
15720}
15721
15722/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
15723/// frame's temporal unit followed by one inter frame's temporal unit per
15724/// remaining picture, all sharing the key frame's sequence header -- and
15725/// each frame's own [`Encoded`], in coding order.
15726#[derive(Clone, Debug)]
15727pub struct EncodedSequence {
15728 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
15729 /// sequence header and the key frame) followed by each later frame's
15730 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
15731 /// the sequence header the key frame carried).
15732 pub stream: Vec<u8>,
15733 /// One entry per picture, in DISPLAY order — the order a decoder outputs
15734 /// them and the order `pictures` came in. Without a pyramid that is also
15735 /// the coding order; with one the two differ, and `coding_order` is the
15736 /// map between them.
15737 pub frames: Vec<Encoded>,
15738 /// The index into `frames` of each coded frame, in CODING order — what a
15739 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
15740 /// `0..frames.len()` on the flat path.
15741 pub coding_order: Vec<usize>,
15742}
15743
15744/// Encodes a sequence of pictures as a key frame followed by one inter frame
15745/// per remaining picture, each predicting from the previous frame's own
15746/// decoded reconstruction — never from the source, which is what a decoder
15747/// cannot see. Every picture must be the same even size (any even width and
15748/// height — each is padded to a whole number of 64x64 superblocks
15749/// internally, which is what lets an inter frame's reference always match
15750/// the frame being coded against it), and `pictures` must be non-empty.
15751///
15752/// # Errors
15753/// Returns an error when `pictures` is empty, when any picture besides the
15754/// first is not the same size as the first, or under the same conditions
15755/// [`encode_key_frame`] and the inter frame path do.
15756pub(crate) fn encode_sequence_with_ctx(
15757 pictures: &[Picture],
15758 base_q_idx: u8,
15759 deadzone: f64,
15760 fctx: &crate::decode::FrameCtx,
15761) -> Result<EncodedSequence> {
15762 let Some((first, rest)) = pictures.split_first() else {
15763 return Err(Error::unsupported(
15764 "AV1 encode",
15765 "a sequence needs at least one picture",
15766 ));
15767 };
15768 first.check_even()?;
15769 let render = (first.width, first.height);
15770 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
15771 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
15772 // the leaves that predict backward off it, and a `show_existing_frame`
15773 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
15774 // an A/B. Screen content stays flat (the content gate in
15775 // `Av1Encoder::encode_frames`, whose detector this asks first so the
15776 // whole sequence path is decided in one place), and so does a run that
15777 // asks for a quantizer rounding offset the facade does not carry: the
15778 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
15779 // the ablations' -- must keep the flat path rather than be silently
15780 // ignored.
15781 //
15782 // The reordering itself is NOT reimplemented here: it is the facade's
15783 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
15784 // called with this sequence's shape, so the two paths cannot drift.
15785 let pyramid = crate::encoder::Pyramid::from_env()
15786 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
15787 .filter(|_| !picture_is_screen(first));
15788 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
15789 if let Some(pyramid) = pyramid {
15790 for picture in rest {
15791 picture.check_even()?;
15792 if (picture.width, picture.height) != render {
15793 return Err(Error::unsupported(
15794 "AV1 encode",
15795 "every picture in a sequence must be the same size as the first",
15796 ));
15797 }
15798 }
15799 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
15800 pictures,
15801 base_q_idx,
15802 pyramid,
15803 armed_tiles(),
15804 );
15805 }
15806 // The key frame and every inter frame after it are coded at the same
15807 // padded size, so the reference each inter frame predicts from -- the
15808 // previous frame's own uncropped reconstruction, at the size a decoder's
15809 // reference buffer actually holds -- always matches the frame being
15810 // coded against it.
15811 let key = encode_key_frame_inner(
15812 &first.padded_to(SUPERBLOCK),
15813 base_q_idx,
15814 deadzone,
15815 &KEY_FRAME_MODES,
15816 split_blocks(),
15817 render,
15818 unspecified_color_config(),
15819 fctx,
15820 )?;
15821 let mut stream = key.stream.clone();
15822 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
15823 // key frame refreshes every slot, each inter frame only slot 0), which is
15824 // what `GOLDEN_FRAME` names.
15825 let golden = key.reconstruction.clone();
15826 // The frame two back, once there is one that is not the key frame
15827 // itself (which `GOLDEN_FRAME` already names).
15828 let mut prev2: Option<Picture> = None;
15829 let mut carried = key.next_cdfs.clone();
15830 let mut reference = key.reconstruction.clone();
15831 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
15832 for (i, picture) in rest.iter().enumerate() {
15833 picture.check_even()?;
15834 // lane-av1tpl2: the lookahead window the per-block lambda weighting
15835 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
15836 // sources at this frame's coded (padded) size. The tail of the
15837 // sequence gets a shorter window, and the last frame none at all.
15838 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
15839 .iter()
15840 .take(tpl_depth() - 1)
15841 .map(|n| n.padded_to(SUPERBLOCK))
15842 .collect();
15843 if (picture.width, picture.height) != render {
15844 return Err(Error::unsupported(
15845 "AV1 encode",
15846 "every picture in a sequence must be the same size as the first",
15847 ));
15848 }
15849 let order_hint = (i + 1) as u32;
15850 let inter = encode_inter_frame(
15851 &picture.padded_to(SUPERBLOCK),
15852 &reference,
15853 base_q_idx,
15854 deadzone,
15855 order_hint,
15856 flat_order_hints(order_hint, 0, prev2.is_some()),
15857 render,
15858 Some(&carried.0),
15859 Some(&golden),
15860 prev2.as_ref(),
15861 None,
15862 fctx,
15863 None,
15864 &lookahead,
15865 )?;
15866 stream.extend_from_slice(&inter.stream);
15867 carried = inter.next_cdfs.clone();
15868 prev2 = Some(std::mem::replace(
15869 &mut reference,
15870 inter.reconstruction.clone(),
15871 ));
15872 frames.push(crop_encoded(&inter, render.0, render.1));
15873 }
15874 Ok(EncodedSequence {
15875 stream,
15876 coding_order: (0..frames.len()).collect(),
15877 frames,
15878 })
15879}
15880
15881#[cfg(test)]
15882mod tests {
15883
15884 /// Every (site, frame type, block side) the census can be called with
15885 /// lands in its own ten-counter bucket, inside the array (class
15886 /// `enumerate-table-domain`: an off-by-one here would silently add two
15887 /// sites' trials together).
15888 #[test]
15889 fn the_split_census_buckets_are_distinct_and_in_bounds() {
15890 let mut seen = std::collections::BTreeSet::new();
15891 for site in 0..2 {
15892 for key in [true, false] {
15893 for side in [8usize, 16, 32, 64] {
15894 let base = super::split_census_base(site, key, side);
15895 assert!(
15896 base + 10 <= super::SPLIT_CENSUS.len(),
15897 "{site} {key} {side}"
15898 );
15899 assert!(seen.insert(base), "{site} {key} {side} collides");
15900 }
15901 }
15902 }
15903 assert_eq!(seen.len(), 16);
15904 }
15905
15906 /// An [`crate::mvstack::MvStack`] with every context at zero and no
15907 /// neighbours, for the pricer tests below to fill the one band each of
15908 /// them is about.
15909 /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
15910 /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
15911 /// against the same stack -- an offer the writer clamps prices the
15912 /// residual against a predictor the decoder never derives, which is the
15913 /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
15914 /// side, so the stream stays legal; here the pricer's own offer set is
15915 /// enumerated, class `enumerate-table-domain`).
15916 ///
15917 /// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt
15918 /// r2, 2026-09-29). It replaces the clip gate
15919 /// `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`,
15920 /// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a
15921 /// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable
15922 /// while the invariant above holds, so no recipe could ever satisfy it.
15923 /// Deletion loses no coverage on either half:
15924 /// * the clamp half -- this test IS the coverage, and it is strictly
15925 /// stronger than any clip gate: it enumerates the pricer's whole offer
15926 /// set against the writer's rule for every stack size 0..=4, and larger
15927 /// stacks add entries the pricers never offer (`best_new_mv_syntax`
15928 /// breaks at `entries.len() <= idx` for `idx > 0`, so indices 3/4 are
15929 /// unreachable at ANY stack size), which is why 0..=4 bounds the
15930 /// domain rather than sampling it;
15931 /// * the pixel half -- the deleted gate's own decode-vs-encoder-
15932 /// reconstruction compare on a 1280x768 sb128 sequence is already made
15933 /// four times over, by `a_128_superblock_clip_whose_root_search_codes_
15934 /// 128x128_blocks_decodes_exact`,
15935 /// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`,
15936 /// `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact`
15937 /// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
15938 /// (same geometry, same `force_sb128(true)`, same own-reconstruction AND
15939 /// ffmpeg compare).
15940 /// MEASURED before deleting (153 clip x size x frame-count x q combinations,
15941 /// `enc_probe`): `tile::drl_clamp_hits()` = 0 on every one. MUTATION PROOF
15942 /// the clip was never the variable: widening `best_new_mv_syntax`'s offer
15943 /// set to `0..5` fires the counter immediately (9/2/2/1 on
15944 /// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8,
15945 /// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp`
15946 /// and `DRL_CLAMP_HITS` are KEPT as the tripwire for the owning fix
15947 /// (`deferred(unblock: the DRL owner widens the pricer past the writer's
15948 /// `start + 2` ceiling, or retires the counter)`) -- this test will go red
15949 /// the moment either happens, which is the signal to re-open the cell.
15950 ///
15951 /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
15952 #[test]
15953 fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
15954 for n in 0..=4usize {
15955 let mut stack = bare_stack();
15956 for i in 0..n {
15957 stack.entries.push(crate::mvstack::StackEntry {
15958 mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
15959 weight: 1,
15960 });
15961 stack.drl_ctx.push(0);
15962 }
15963 stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
15964 stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
15965 stack.pred_mv = stack.nearest_mv;
15966 // Aim the vector at each entry in turn, so every index the offer
15967 // set holds is the one that wins at least once.
15968 for target in 0..n.max(1) {
15969 let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
15970 let (_, idx) =
15971 best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable");
15972 let idx = usize::from(idx);
15973 assert_eq!(
15974 crate::tile::signalled_drl_idx(n, 0, idx),
15975 idx,
15976 "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
15977 );
15978 }
15979 // The NEARMV arm's own offer set (`search_inter_block`,
15980 // `search_skip_64`): indices 1 and 2, offered only when the stack
15981 // really holds that entry.
15982 for idx in 1..=2usize {
15983 if stack.entries.get(idx).is_some() {
15984 assert_eq!(
15985 crate::tile::signalled_drl_idx(n, 1, idx),
15986 idx,
15987 "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
15988 );
15989 }
15990 }
15991 }
15992 }
15993
15994 fn bare_stack() -> crate::mvstack::MvStack {
15995 crate::mvstack::MvStack {
15996 entries: Default::default(),
15997 nearest_mv: (0, 0),
15998 near_mv: (0, 0),
15999 pred_mv: (0, 0),
16000 new_mv_ctx: 0,
16001 ref_mv_ctx: 0,
16002 zero_mv_ctx: 0,
16003 drl_ctx: Default::default(),
16004 above_refs: (None, None),
16005 left_refs: (None, None),
16006 above_nbr: None,
16007 left_nbr: None,
16008 above_skip: false,
16009 left_skip: false,
16010 }
16011 }
16012
16013 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
16014 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
16015 /// own neighbour-derived context. Red before lane-ctx, where the pricer
16016 /// spent four constants at CDF row 0 that assumed the pair was
16017 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
16018 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
16019 #[test]
16020 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
16021 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
16022 use crate::encode::symbol_bits as b;
16023 use crate::mvstack::{
16024 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
16025 LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
16026 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
16027 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
16028 };
16029 // (pair, unidirectional?, the tree's symbols as (table, p index,
16030 // context selector, value)) -- transcribed from the writer.
16031 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
16032 type Sym = (char, usize, usize, usize);
16033 let cases: [((i8, i8), bool, &[Sym]); 7] = [
16034 (
16035 (LAST_FRAME, LAST2_FRAME),
16036 true,
16037 &[('u', 0, 1, 0), ('u', 1, 7, 0)],
16038 ),
16039 (
16040 (LAST_FRAME, LAST3_FRAME),
16041 true,
16042 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
16043 ),
16044 (
16045 (LAST_FRAME, GOLDEN_FRAME),
16046 true,
16047 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
16048 ),
16049 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
16050 (
16051 (LAST_FRAME, ALTREF_FRAME),
16052 false,
16053 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
16054 ),
16055 (
16056 (LAST_FRAME, BWDREF_FRAME),
16057 false,
16058 &[
16059 ('c', 0, 3, 0),
16060 ('c', 1, 4, 0),
16061 ('b', 0, 2, 0),
16062 ('b', 1, 6, 0),
16063 ],
16064 ),
16065 (
16066 (LAST_FRAME, ALTREF2_FRAME),
16067 false,
16068 &[
16069 ('c', 0, 3, 0),
16070 ('c', 1, 4, 0),
16071 ('b', 0, 2, 0),
16072 ('b', 1, 6, 1),
16073 ],
16074 ),
16075 ];
16076 let nbr = |ref0, ref1: Option<i8>| {
16077 Some(NeighbourRef {
16078 is_inter: true,
16079 ref0,
16080 ref1,
16081 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
16082 })
16083 };
16084 // No neighbours (every context zero), then a mixed pair that puts the
16085 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
16086 for (above_nbr, left_nbr, above_refs, left_refs) in [
16087 (None, None, (None, None), (None, None)),
16088 (
16089 nbr(LAST_FRAME, None),
16090 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
16091 (Some(LAST_FRAME), None),
16092 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
16093 ),
16094 ] {
16095 let stack = crate::mvstack::MvStack {
16096 above_nbr,
16097 left_nbr,
16098 above_refs,
16099 left_refs,
16100 ..bare_stack()
16101 };
16102 let (a, a1) = above_refs;
16103 let (l, l1) = left_refs;
16104 let ctx_of = |sel: usize| match sel {
16105 1 => single_ref_p1_ctx(a, a1, l, l1),
16106 2 => single_ref_p2_ctx(a, a1, l, l1),
16107 3 => single_ref_p3_ctx(a, a1, l, l1),
16108 4 => single_ref_p4_ctx(a, a1, l, l1),
16109 5 => single_ref_p5_ctx(a, a1, l, l1),
16110 6 => single_ref_p6_ctx(a, a1, l, l1),
16111 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
16112 };
16113 for (pair, unidir, symbols) in cases {
16114 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
16115 + b(
16116 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
16117 usize::from(!unidir),
16118 );
16119 for &(table, p, sel, v) in symbols {
16120 let row = ctx_of(sel);
16121 want += match table {
16122 'u' => b(&UNI_COMP_REF[row][p], v),
16123 'c' => b(&COMP_REF[row][p], v),
16124 _ => b(&COMP_BWDREF[row][p], v),
16125 };
16126 }
16127 let got = super::compound_ref_bits(pair, &stack);
16128 assert!(
16129 (got - want).abs() < 1e-9,
16130 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
16131 priced {got} bits, writer codes {want}"
16132 );
16133 }
16134 }
16135 }
16136
16137 /// The `skip` and `is_inter` symbols are priced at the SAME context
16138 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
16139 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
16140 /// on every neighbour configuration whose context is not zero (class
16141 /// pricer-context-zero).
16142 #[test]
16143 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
16144 use crate::cdf::{INTRA_INTER, SKIP};
16145 use crate::encode::symbol_bits as b;
16146 use crate::mvstack::NeighbourRef;
16147 let nbr = |is_inter| NeighbourRef {
16148 is_inter,
16149 ref0: if is_inter {
16150 crate::mvstack::LAST_FRAME
16151 } else {
16152 0
16153 },
16154 ref1: None,
16155 uni: false,
16156 };
16157 for (above, left, above_skip, left_skip) in [
16158 (None, None, false, false),
16159 (Some(nbr(true)), Some(nbr(true)), true, false),
16160 (Some(nbr(false)), Some(nbr(false)), true, true),
16161 (Some(nbr(false)), None, false, true),
16162 (None, Some(nbr(true)), true, true),
16163 ] {
16164 let stack = crate::mvstack::MvStack {
16165 above_nbr: above,
16166 left_nbr: left,
16167 above_skip,
16168 left_skip,
16169 ..bare_stack()
16170 };
16171 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
16172 let ii_ctx = crate::tile::intra_inter_ctx(
16173 above.is_some(),
16174 left.is_some(),
16175 above.is_some_and(|n| n.is_inter),
16176 left.is_some_and(|n| n.is_inter),
16177 );
16178 for v in [false, true] {
16179 let (got, want) = (
16180 super::skip_bits_at(&stack, v),
16181 b(&SKIP[skip_ctx], usize::from(v)),
16182 );
16183 assert!(
16184 (got - want).abs() < 1e-9,
16185 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
16186 );
16187 let (got, want) = (
16188 super::intra_inter_bits_at(&stack, v),
16189 b(&INTRA_INTER[ii_ctx], usize::from(v)),
16190 );
16191 assert!(
16192 (got - want).abs() < 1e-9,
16193 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
16194 );
16195 }
16196 }
16197 }
16198
16199 /// [`super::single_ref_bits`] pays exactly what tile.rs'
16200 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
16201 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
16202 /// the context that symbol's own `single_ref_p*_ctx` derives from the
16203 /// block's above/left neighbours. Red before lane-pricer, where every
16204 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
16205 #[test]
16206 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
16207 use crate::cdf::SINGLE_REF as SR;
16208 use crate::encode::symbol_bits as b;
16209 use crate::mvstack::{
16210 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
16211 LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
16212 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
16213 };
16214 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
16215 above_refs,
16216 left_refs,
16217 above_nbr,
16218 left_nbr,
16219 ..bare_stack()
16220 };
16221 let nbr = |ref0, ref1| {
16222 Some(crate::mvstack::NeighbourRef {
16223 is_inter: true,
16224 ref0,
16225 ref1,
16226 uni: false,
16227 })
16228 };
16229 // (reference, the symbols `write_single_ref` emits as (p index, value))
16230 let cases: [(i8, &[(usize, usize)]); 7] = [
16231 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
16232 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
16233 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
16234 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
16235 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
16236 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
16237 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
16238 ];
16239 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
16240 // that puts every p* context on a different row -- the second with a
16241 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
16242 // off row 0.
16243 for (above_refs, left_refs, above_nbr, left_nbr) in [
16244 ((None, None), (None, None), None, None),
16245 (
16246 (Some(LAST_FRAME), None),
16247 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
16248 nbr(LAST_FRAME, None),
16249 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
16250 ),
16251 ] {
16252 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
16253 let (a, a1) = above_refs;
16254 let (l, l1) = left_refs;
16255 let ctx_of = |p: usize| match p {
16256 0 => single_ref_p1_ctx(a, a1, l, l1),
16257 1 => single_ref_p2_ctx(a, a1, l, l1),
16258 2 => single_ref_p3_ctx(a, a1, l, l1),
16259 3 => single_ref_p4_ctx(a, a1, l, l1),
16260 4 => single_ref_p5_ctx(a, a1, l, l1),
16261 _ => single_ref_p6_ctx(a, a1, l, l1),
16262 };
16263 for (ref_frame, symbols) in cases {
16264 // Plus the `comp_mode = 0` symbol the writer codes ahead of
16265 // the reference syntax on a `reference_select` frame.
16266 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
16267 if super::reference_select() {
16268 want += b(
16269 &crate::cdf::COMP_MODE
16270 [crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)],
16271 0,
16272 );
16273 }
16274 let got = super::single_ref_bits(ref_frame, &stack);
16275 assert!(
16276 (got - want).abs() < 1e-9,
16277 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
16278 priced {got} bits, writer codes {want}"
16279 );
16280 }
16281 }
16282 }
16283
16284 /// lane-av1tpl2's propagated map, on the two properties every decision
16285 /// under it rests on: a frame the whole lookahead window repeats exactly
16286 /// (uniform texture) leans on every cell alike, so every factor is 1 and
16287 /// the weighting is a no-op; and where the window really does save bits
16288 /// by predicting -- the textured half of a frame whose other half is
16289 /// flat -- the factor FALLS below 1, i.e. that half is coded more
16290 /// distortion-averse than the half nothing gains from.
16291 /// The distortion metric itself (lane-sse): a block the true frame edge
16292 /// cuts through is scored over its INSIDE part only, so a difference that
16293 /// lives entirely in the padding costs nothing and a block wholly past
16294 /// the edge scores zero. Before this, the search ranked modes,
16295 /// transforms and partition trees on samples the display crop throws
16296 /// away -- which lane-b64b had fixed for the 64x64 root alone.
16297 #[test]
16298 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
16299 // A 40x40 true frame on a 64x64 padded coding surface.
16300 let source = vec![10u8; 64 * 64];
16301 let plane = fresh_plane(&source, 64, 64, 40, 40);
16302 let mut reconstruction = vec![10u8; 64 * 64];
16303 // Off by 190 at (50, 50) -- past the true edge in both axes.
16304 reconstruction[50 * 64 + 50] = 200;
16305 assert_eq!(
16306 plane.block_sse(0, 0, 64, &reconstruction),
16307 0.0,
16308 "padding was scored"
16309 );
16310 // Off by 10 at (39, 39) -- the last sample the decoder shows.
16311 reconstruction[39 * 64 + 39] = 20;
16312 assert_eq!(
16313 plane.block_sse(0, 0, 64, &reconstruction),
16314 100.0,
16315 "inside was not scored"
16316 );
16317 // A 16x16 block whose every sample is padding.
16318 let block = vec![200u8; 16 * 16];
16319 assert_eq!(
16320 plane.block_sse(48, 0, 16, &block),
16321 0.0,
16322 "a block past the edge scored"
16323 );
16324 // A 16x16 block the edge cuts: 8 of its columns are inside.
16325 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
16326 }
16327
16328 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
16329 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
16330 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
16331 #[test]
16332 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
16333 let (base, res) = (162u8, 4i32);
16334 let rf = 2.0;
16335 // A superblock the window leans on more than the frame average is
16336 // coded FINER (lower qindex); a slack one coarser; the average one
16337 // exactly at the base.
16338 assert!(
16339 super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base,
16340 "leaned-on SB must go finer"
16341 );
16342 assert!(
16343 super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base,
16344 "idle SB must go coarser"
16345 );
16346 assert_eq!(
16347 super::deltaq_libaom(base, rf, rf, 1.0, res),
16348 base,
16349 "the average SB moves 0"
16350 );
16351 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
16352 let max = ((res * 9 - 1) / res) * res;
16353 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
16354 for k in [0.5f64, 1.0, 1.5] {
16355 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
16356 let d = q - i32::from(base);
16357 assert_eq!(
16358 d % res,
16359 0,
16360 "r={r} k={k}: offset {d} is not a whole {res}-step"
16361 );
16362 assert!(
16363 d.abs() <= max,
16364 "r={r} k={k}: offset {d} past libaom's +-{max}"
16365 );
16366 }
16367 }
16368 // The clamp is REACHED from both ends, so the bound is a real bound
16369 // and not a formula that never gets there.
16370 assert_eq!(
16371 i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base),
16372 -max
16373 );
16374 assert_eq!(
16375 i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base),
16376 max
16377 );
16378 // A stronger `k` never moves less than a weaker one.
16379 let d = |k: f64| {
16380 (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs()
16381 };
16382 assert!(
16383 d(0.5) <= d(1.0) && d(1.0) <= d(1.5),
16384 "strength must be monotone: {} {} {}",
16385 d(0.5),
16386 d(1.0),
16387 d(1.5)
16388 );
16389 // The frame reference is libaom's log-mean: flat in, the same value out.
16390 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
16391 }
16392
16393 /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
16394 /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
16395 /// shipped default, and the multiplier reaches the strength.
16396 #[test]
16397 fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
16398 let d = crate::speed::DQ_LEVEL_K;
16399 assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
16400 assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
16401 // Short and broken fields fall back per SLOT, not per spec.
16402 assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
16403 assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
16404 assert_eq!(super::DqLevel::TopArf as usize, 0);
16405 assert_eq!(super::DqLevel::MidArf as usize, 1);
16406 assert_eq!(super::DqLevel::Leaf as usize, 2);
16407 }
16408
16409 #[test]
16410 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
16411 // Four 64x64 superblocks across: the shipped map forms its ratio per
16412 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
16413 // only ever produce one ratio -- and one ratio, mean-normalised, is
16414 // the flat map, whatever the content underneath it.
16415 let (w, h) = (256usize, 64usize);
16416 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
16417 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
16418 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
16419 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
16420 for (i, &v) in f.iter().enumerate() {
16421 assert!(
16422 (v - 1.0).abs() < 1e-6,
16423 "cell {i} factor {v}, a flat map must move no lambda"
16424 );
16425 }
16426
16427 // Left half textured, right half constant: the window saves bits
16428 // predicting the left half and nothing at all on the right.
16429 let split: Vec<u8> = (0..w * h)
16430 .map(|i| {
16431 if i % w < w / 2 {
16432 ((i * 37) % 251) as u8
16433 } else {
16434 128
16435 }
16436 })
16437 .collect();
16438 let frames: Vec<&[u8]> = vec![&split, &split, &split];
16439 let cells_x = w / 16;
16440 for k in [0.25f64, 0.5, 1.0, 2.0] {
16441 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
16442 for r in 0..h / 16 {
16443 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
16444 assert!(
16445 lean < 1.0,
16446 "k={k} row {r}: leaned-on cell factor {lean} must be < 1"
16447 );
16448 assert!(
16449 idle > 1.0,
16450 "k={k} row {r}: idle cell factor {idle} must be > 1"
16451 );
16452 }
16453 }
16454 }
16455
16456 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
16457 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
16458 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
16459 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
16460 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
16461 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
16462 /// only a quarter of the 16x8 table and read the wrong byte for every
16463 /// block row but the first (silently wrong above-right/below-left
16464 /// availability -- wrong pixels, no error).
16465 #[test]
16466 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
16467 for (bw, bh) in [
16468 (16usize, 8usize),
16469 (8, 16),
16470 (32, 16),
16471 (16, 32),
16472 (64, 32),
16473 (32, 64),
16474 ] {
16475 let (bw_log2, bh_log2) = (
16476 (bw / 4).trailing_zeros() as usize,
16477 (bh / 4).trailing_zeros() as usize,
16478 );
16479 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
16480 for (name, table) in [
16481 ("has_tr", rect_reach_tables(bw, bh).0),
16482 ("has_bl", rect_reach_tables(bw, bh).1),
16483 ] {
16484 assert_eq!(
16485 table.len() * 8,
16486 rows * cols,
16487 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
16488 );
16489 let mut seen = vec![0u32; table.len() * 8];
16490 for blk_row in 0..rows {
16491 for blk_col in 0..cols {
16492 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
16493 assert!(
16494 idx < seen.len(),
16495 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
16496 );
16497 seen[idx] += 1;
16498 }
16499 }
16500 assert!(
16501 seen.iter().all(|&n| n == 1),
16502 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
16503 (row stride is not {cols})"
16504 );
16505 }
16506 }
16507 }
16508 use super::*;
16509 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
16510 use crate::probe::run_with_stdin;
16511 use std::process::{Command, Stdio};
16512
16513 /// Every rectangular shape this decoder codes, at every position a block
16514 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
16515 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
16516 /// (`reconintra.c`) answer, whose bodies are ported below.
16517 ///
16518 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
16519 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
16520 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
16521 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
16522 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
16523 /// oracle's own arrays, so a re-routed or truncated table fails here even
16524 /// where the two rows happen to agree.
16525 ///
16526 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
16527 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
16528 /// callers handle by predicting each transform unit as its own block.
16529 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
16530 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
16531 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
16532 /// (the horizontal shapes, which those partitions never produce).
16533 #[test]
16534 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
16535 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
16536 // it pins the 64 reach explicitly instead of following the process's
16537 // own superblock knob (`for_encoder`), which made it red under
16538 // `EC_AV1_SB128=1` for no defect of the code under test.
16539 let fctx = &crate::decode::FrameCtx::new();
16540 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
16541 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
16542 (4, 8, 64, 9280, 64, 550),
16543 (8, 4, 64, 3712, 64, 9630),
16544 (8, 16, 16, 2352, 16, 134),
16545 (16, 8, 16, 960, 16, 2400),
16546 (16, 32, 4, 620, 4, 32),
16547 (32, 16, 4, 32, 4, 184),
16548 (32, 64, 1, 127, 1, 0),
16549 (64, 32, 1, 19, 1, 34),
16550 (4, 16, 32, 5472, 32, 14),
16551 (16, 4, 32, 960, 32, 6464),
16552 (8, 32, 8, 1400, 8, 2),
16553 (32, 8, 8, 32, 8, 1136),
16554 (16, 64, 2, 382, 2, 0),
16555 (64, 16, 2, 4, 2, 84),
16556 ];
16557 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
16558 /// a block whose transform covers it whole (`row_off == col_off == 0`,
16559 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
16560 /// superblock (`sb_mi_size == 16`).
16561 fn libaom_reach(
16562 bw: usize,
16563 bh: usize,
16564 x: usize,
16565 y: usize,
16566 width: usize,
16567 height: usize,
16568 _fctx: &crate::decode::FrameCtx,
16569 ) -> (bool, bool) {
16570 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
16571 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
16572 let sb_mi_size = 16usize;
16573 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
16574 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
16575 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
16576 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
16577 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
16578 // has_top_right: top_available && right_available, then row_off == 0.
16579 let top_right = if y == 0 || x + bw >= width {
16580 false
16581 } else if blk_row_in_sb == 0 {
16582 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
16583 // `bw_unit < bw_unit`, false for a whole-block transform.)
16584 true
16585 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
16586 false
16587 } else {
16588 bit(tr_table)
16589 };
16590 // has_bottom_left: bottom_available && left_available, col_off == 0.
16591 let bottom_left = if x == 0 || y + bh >= height {
16592 false
16593 } else if blk_col_in_sb == 0 {
16594 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
16595 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
16596 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
16597 false
16598 } else {
16599 bit(bl_table)
16600 };
16601 (top_right, bottom_left)
16602 }
16603 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
16604 let (tr, bl) = rect_reach_tables(bw, bh);
16605 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
16606 assert_eq!(
16607 (tr.len(), sum(tr), bl.len(), sum(bl)),
16608 (tr_len, tr_sum, bl_len, bl_sum),
16609 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
16610 );
16611 // Two superblocks across and down, so the superblock-relative
16612 // position (and not the frame position) is what decides.
16613 for sb_y in [0usize, 64] {
16614 for sb_x in [0usize, 64] {
16615 for y in (sb_y..sb_y + 64).step_by(bh) {
16616 for x in (sb_x..sb_x + 64).step_by(bw) {
16617 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
16618 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
16619 assert_eq!(
16620 (got.above_right, got.below_left),
16621 want,
16622 "{bw}x{bh} at ({x}, {y})"
16623 );
16624 }
16625 }
16626 }
16627 }
16628 }
16629 }
16630
16631 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
16632 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
16633 /// aomenc gate decodes its stream through ffmpeg and is meaningless
16634 /// without it -- turns it into a hard failure. Without this the require
16635 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
16636 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
16637 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
16638 fn have_ffmpeg() -> bool {
16639 let present = Command::new("ffmpeg")
16640 .arg("-version")
16641 .stdout(Stdio::null())
16642 .stderr(Stdio::null())
16643 .status()
16644 .is_ok_and(|s| s.success());
16645 assert!(
16646 present
16647 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
16648 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
16649 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
16650 );
16651 present
16652 }
16653
16654 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
16655 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
16656 fn have_encoder(encoder: &str) -> bool {
16657 Command::new("ffmpeg")
16658 .args(["-hide_banner", "-encoders"])
16659 .stderr(Stdio::null())
16660 .output()
16661 .is_ok_and(|o| {
16662 String::from_utf8_lossy(&o.stdout)
16663 .lines()
16664 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
16665 })
16666 }
16667
16668 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
16669 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
16670 let out = run_with_stdin(
16671 Command::new("ffmpeg").args([
16672 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
16673 ]),
16674 stream,
16675 );
16676 assert!(
16677 out.status.success(),
16678 "ffmpeg refused the stream: {}",
16679 String::from_utf8_lossy(&out.stderr)
16680 );
16681 let (luma, chroma) = (width * height, width * height / 4);
16682 assert_eq!(
16683 out.stdout.len(),
16684 luma + 2 * chroma,
16685 "expected one 4:2:0 frame"
16686 );
16687 Picture {
16688 width,
16689 height,
16690 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
16691 u: out.stdout[luma..luma + chroma]
16692 .iter()
16693 .map(|&v| u16::from(v))
16694 .collect(),
16695 v: out.stdout[luma + chroma..]
16696 .iter()
16697 .map(|&v| u16::from(v))
16698 .collect(),
16699 }
16700 }
16701
16702 /// A picture with something of everything in it: a gradient, an edge, a
16703 /// ripple and a block of flat colour, none of them aligned to the block
16704 /// grid.
16705 /// The in-loop filters actually FIRE and the stream still decodes to
16706 /// exactly what the encoder kept as its reconstruction
16707 /// (gate-blind-to-feature: a filter search that always answered "off"
16708 /// would leave every other test just as green, and the BD gate that
16709 /// would notice is `#[ignore]`d).
16710 ///
16711 /// Run:
16712 /// cargo test -p ec-av1 --release --lib -- \
16713 /// encode::tests::the_filter_search_picks_real_filters
16714 #[test]
16715 fn the_filter_search_picks_real_filters() {
16716 let _knobs = crate::speed::knob_read();
16717 let fctx = &crate::decode::FrameCtx::for_encoder();
16718 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
16719 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
16720 let fired = encoded
16721 .frames
16722 .iter()
16723 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
16724 .count();
16725 assert!(
16726 fired > 0,
16727 "no frame of this sequence chose any in-loop filtering: {:?}",
16728 encoded
16729 .frames
16730 .iter()
16731 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
16732 .collect::<Vec<_>>()
16733 );
16734 // The reconstruction the encoder predicts from is the FILTERED one,
16735 // and it is what a decoder of the stream produces -- byte for byte,
16736 // frame for frame.
16737 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
16738 assert_eq!(decoded.len(), encoded.frames.len());
16739 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
16740 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
16741 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
16742 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
16743 }
16744 }
16745
16746 fn test_card(width: usize, height: usize) -> Picture {
16747 let mut picture = Picture::grey(width, height);
16748 for y in 0..height {
16749 for x in 0..width {
16750 let gradient = x as f64 * 200.0 / width as f64;
16751 let ripple = 30.0
16752 * (x as f64 * std::f64::consts::PI / 23.0).sin()
16753 * (y as f64 * std::f64::consts::PI / 37.0).cos();
16754 let edge = if x > width * 3 / 7 && y > height / 3 {
16755 40.0
16756 } else {
16757 0.0
16758 };
16759 picture.y[y * width + x] =
16760 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
16761 }
16762 }
16763 for y in 0..height / 2 {
16764 for x in 0..width / 2 {
16765 let i = y * width / 2 + x;
16766 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
16767 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
16768 }
16769 }
16770 picture
16771 }
16772
16773 fn psnr(a: &[u16], b: &[u16]) -> f64 {
16774 let squared: f64 = a
16775 .iter()
16776 .zip(b)
16777 .map(|(&x, &y)| {
16778 let d = f64::from(x) - f64::from(y);
16779 d * d
16780 })
16781 .sum();
16782 if squared == 0.0 {
16783 return f64::INFINITY;
16784 }
16785 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
16786 }
16787
16788 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
16789 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
16790 /// frame's new root fires on most superblocks -- and what BOTH decoders
16791 /// produce is the encoder's own reconstruction, sample for sample.
16792 ///
16793 /// The fire count is the `gate-blind-to-feature` guard: without it every
16794 /// assert below passes on a stream that codes no whole superblock at all.
16795 #[test]
16796 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
16797 let _knobs = crate::speed::knob_read();
16798 let fctx = &crate::decode::FrameCtx::for_encoder();
16799 // 4 x 3 superblocks, all of them wholly inside the frame.
16800 let (width, height) = (256usize, 192usize);
16801 let mut picture = Picture::grey(width, height);
16802 for y in 0..height {
16803 for x in 0..width {
16804 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
16805 }
16806 }
16807 for y in 0..height / 2 {
16808 for x in 0..width / 2 {
16809 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
16810 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
16811 }
16812 }
16813 let _ = take_i64_root_hits();
16814 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
16815 let [roots, _offered, _edge] = take_i64_root_hits();
16816 // The counters are process-global, so another test encoding in
16817 // parallel can only ADD to them -- the per-FRAME fact is the mode
16818 // list, which carries one entry per coded block and so exactly 12
16819 // when every superblock was coded as one 64x64 intra block.
16820 assert_eq!(
16821 encoded.modes.len(),
16822 12,
16823 "not every superblock was coded as one 64x64 intra block"
16824 );
16825 assert!(
16826 roots >= 8,
16827 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
16828 );
16829 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
16830
16831 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16832 assert_eq!(ours.len(), 1, "our decoder's frames");
16833 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
16834 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
16835 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
16836
16837 if !have_ffmpeg() {
16838 eprintln!("SKIP the ffmpeg half: no ffmpeg");
16839 return;
16840 }
16841 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16842 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
16843 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
16844 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
16845 }
16846
16847 /// The claim the whole encoder rests on: what a decoder produces is what
16848 /// the encoder said it would, sample for sample, on every plane.
16849 ///
16850 /// Prediction reads the reconstruction, so a single sample of drift
16851 /// anywhere would spread into every block below and to the right of it —
16852 /// which is why this is an equality and not a tolerance.
16853 #[test]
16854 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
16855 let _knobs = crate::speed::knob_read();
16856 let fctx = &crate::decode::FrameCtx::for_encoder();
16857 if !have_ffmpeg() {
16858 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
16859 return;
16860 }
16861 for &(width, height) in &[
16862 (64usize, 64usize),
16863 (96, 64),
16864 (160, 96),
16865 (32, 48),
16866 (248, 152),
16867 ] {
16868 let picture = test_card(width, height);
16869 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16870 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16871 assert_eq!(
16872 decoded.y, encoded.reconstruction.y,
16873 "{width}x{height}: luma"
16874 );
16875 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
16876 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
16877 }
16878 // One q index from each of the four coefficient-CDF contexts
16879 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
16880 let (width, height) = (64usize, 64usize);
16881 let picture = test_card(width, height);
16882 let _ = take_tx_depth_hits();
16883 for &q in &[15u8, 45, 100, 200] {
16884 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16885 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16886 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
16887 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
16888 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
16889 }
16890 // lane-av1tx: the exactness above is only a claim about SPLIT
16891 // transforms if some block actually split one (`gate-blind-to-feature`
16892 // -- with `tx_depth` stuck at 0 every assert here passes on the
16893 // pre-lane stream). The test card's edges split at these four
16894 // quantizers; the counter is per-process (another test encoding in
16895 // parallel can only ADD to it, so this can be masked, never falsely
16896 // failed), so it is read once for the whole q ladder.
16897 let depths = take_tx_depth_hits();
16898 assert!(
16899 depths[1] + depths[2] > 0,
16900 "no block split its transform: depths {depths:?}"
16901 );
16902 }
16903
16904 /// A synthetic screen-content picture -- a few flat colours in a grid of
16905 /// boxes with hard edges and text-like bars, the shape a desktop capture
16906 /// has -- so the palette path is exercised on content it is for.
16907 #[cfg(test)]
16908 fn screen_card(width: usize, height: usize) -> Picture {
16909 const INK: [u16; 4] = [16, 90, 180, 235];
16910 let mut picture = Picture::grey(width, height);
16911 for y in 0..height {
16912 for x in 0..width {
16913 let cell = (x / 24 + y / 24) % 2;
16914 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
16915 picture.y[y * width + x] = INK[cell * 2 + bar];
16916 }
16917 }
16918 // Four chroma colours, not two: a two-colour chroma block only ever
16919 // codes a `PaletteSizeUV` of 2, which leaves
16920 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
16921 // deltas and the neighbour cache flags, exercised only when
16922 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
16923 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
16924 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
16925 for y in 0..height / 2 {
16926 for x in 0..width / 2 {
16927 let cell = (x / 12 + 2 * (y / 12)) % 4;
16928 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
16929 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
16930 }
16931 }
16932 picture
16933 }
16934
16935 /// The lane's own end-to-end check: on screen content the detector fires,
16936 /// blocks really take a palette (fire count, class
16937 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
16938 /// symbol this lane writes -- reconstructs exactly what the encoder did.
16939 /// The film-shaped `test_card` must NOT trip the detector, which is what
16940 /// keeps every non-screen stream byte-identical.
16941 #[test]
16942 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
16943 let _knobs = crate::speed::knob_read();
16944 let fctx = &crate::decode::FrameCtx::for_encoder();
16945 let (width, height) = (192usize, 96usize);
16946 let _ = crate::tile::take_palette_hits();
16947 let picture = screen_card(width, height);
16948 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16949 assert!(
16950 encoded.screen,
16951 "the detector did not fire on screen content -- no palette syntax was coded at all"
16952 );
16953 let hits = crate::tile::take_palette_hits();
16954 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
16955 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
16956 // The chroma half is a claim about the plane-1 syntax only if some
16957 // block really took a chroma palette (`gate-blind-to-feature`): every
16958 // exactness assert below passes on a stream that codes
16959 // `palette_uv_mode == 0` everywhere.
16960 let uv_hits = crate::tile::take_palette_uv_hits();
16961 assert!(
16962 uv_hits[0] > 0,
16963 "no block took a chroma palette: {uv_hits:?}"
16964 );
16965 let uv_cached = crate::tile::take_palette_uv_cache_hits();
16966 eprintln!(
16967 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
16968 uv_hits[0],
16969 &uv_hits[2..]
16970 );
16971 assert!(
16972 uv_cached > 0,
16973 "no chroma base colour came out of the neighbour cache -- \
16974 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
16975 );
16976 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
16977 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
16978 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
16979 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
16980 if !have_ffmpeg() {
16981 eprintln!("SKIP the ffmpeg half: no ffmpeg");
16982 return;
16983 }
16984 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16985 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
16986 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
16987 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
16988 // A whole GOP: the inter frames' own intra blocks carry the palette
16989 // syntax too (the three intra arms of the inter writers), which only
16990 // ffmpeg reading the frames back can prove.
16991 let moved: Vec<Picture> = (0..4)
16992 .map(|f| {
16993 let base = screen_card(width, height);
16994 let mut out = Picture::grey(width, height);
16995 for y in 0..height {
16996 for x in 0..width {
16997 let sx = (x + f * 7) % width;
16998 out.y[y * width + x] = base.y[y * width + sx];
16999 }
17000 }
17001 for y in 0..height / 2 {
17002 for x in 0..width / 2 {
17003 let sx = (x + f * 3) % (width / 2);
17004 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
17005 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
17006 }
17007 }
17008 out
17009 })
17010 .collect();
17011 let _ = crate::tile::take_palette_hits();
17012 let _ = crate::tile::take_palette_uv_hits();
17013 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
17014 let gop_hits = crate::tile::take_palette_hits();
17015 let gop_uv_hits = crate::tile::take_palette_uv_hits();
17016 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
17017 eprintln!(
17018 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
17019 {} chroma palette blocks",
17020 inter_screen, gop_hits[0], gop_uv_hits[0]
17021 );
17022 assert!(
17023 gop_uv_hits[0] > 0,
17024 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
17025 );
17026 assert!(
17027 inter_screen > 0,
17028 "no inter frame set allow_screen_content_tools"
17029 );
17030 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
17031 assert_eq!(
17032 gop_decoded.len(),
17033 gop.frames.len(),
17034 "our decoder: GOP frame count"
17035 );
17036 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
17037 assert_eq!(
17038 ours.y, frame.reconstruction.y,
17039 "our decoder: GOP frame {i} luma"
17040 );
17041 }
17042 if have_ffmpeg() {
17043 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
17044 assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count");
17045 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
17046 assert_eq!(
17047 theirs.y, frame.reconstruction.y,
17048 "ffmpeg: GOP frame {i} luma"
17049 );
17050 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
17051 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
17052 }
17053 }
17054
17055 // The other half of the keep rule: film-shaped content leaves the
17056 // detector (and so the whole sequence header) alone.
17057 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
17058 assert!(
17059 !film.screen,
17060 "the detector fired on the film-shaped test card"
17061 );
17062 }
17063
17064 /// The lane's keep-rule measurement: the gate's own screen capture, one
17065 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
17066 /// Setting the bit forces deblocking, CDEF and loop restoration off for
17067 /// that frame, so the table is exactly the filter loss against the bytes
17068 /// the copied blocks save.
17069 #[test]
17070 #[ignore = "needs the real-library manifest and ffmpeg"]
17071 fn probe_intrabc_key_frame() {
17072 let _knobs = crate::speed::knob_write();
17073 let fctx = &crate::decode::FrameCtx::for_encoder();
17074 // lane-av1clipprobe: the manifest is a real-library file, so it
17075 // resolves through the crate's one fixture root (EC_FIXTURES first)
17076 // and its absence is reported by the one probe instead of an inline
17077 // SKIP that named no path. A file that IS there but unreadable is not
17078 // an absence, so it is a hard error rather than a second silent skip.
17079 let Some(manifest_path) =
17080 crate::library_fixture::require("real-library-manifest.tsv", "probe_intrabc_key_frame")
17081 else {
17082 return;
17083 };
17084 let manifest = std::fs::read_to_string(&manifest_path).unwrap_or_else(|e| {
17085 panic!(
17086 "probe_intrabc_key_frame: {} is present but unreadable ({e})",
17087 manifest_path.display()
17088 )
17089 });
17090 let Some(clip) = manifest
17091 .lines()
17092 .skip(1)
17093 .filter_map(|l| l.split('\t').next())
17094 .find(|p| {
17095 p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
17096 })
17097 else {
17098 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
17099 return;
17100 };
17101 let (width, height) = (1280usize, 768usize);
17102 let picture = clip_frame(clip, "0", width, height);
17103 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
17104 for q in [5u8, 20, 35, 45] {
17105 for on in [false, true] {
17106 force_intrabc(Some(on));
17107 let _ = crate::tile::take_intrabc_hits();
17108 let _ = take_intrabc_search();
17109 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
17110 let hits = crate::tile::take_intrabc_hits();
17111 let search = take_intrabc_search();
17112 eprintln!(
17113 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
17114 if encoded.allow_intrabc { "on" } else { "off" },
17115 encoded.stream.len(),
17116 psnr_all(&encoded.reconstruction, &picture),
17117 hits[0],
17118 &hits[1..],
17119 search[0],
17120 search[1],
17121 search[2],
17122 );
17123 }
17124 }
17125 force_intrabc(None);
17126 }
17127
17128 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
17129 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
17130 /// take a block vector (fire count + DV histogram, class
17131 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
17132 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
17133 /// exactly what the encoder did.
17134 #[test]
17135 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
17136 let _knobs = crate::speed::knob_write();
17137 let fctx = &crate::decode::FrameCtx::for_encoder();
17138 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
17139 // superblocks of 64) and tall enough for a source superblock row
17140 // above the blocks that copy from it.
17141 let (width, height) = (512usize, 256usize);
17142 let picture = screen_card(width, height);
17143 let _ = crate::tile::take_intrabc_hits();
17144 // The default is OFF (it measured worse on the real screen capture --
17145 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
17146 // the arm on for its own encode and puts it back straight after.
17147 force_intrabc(Some(true));
17148 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17149 force_intrabc(None);
17150 assert!(
17151 encoded.allow_intrabc,
17152 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
17153 intrabc_source_share() * 100.0
17154 );
17155 let hits = crate::tile::take_intrabc_hits();
17156 eprintln!(
17157 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
17158 hits[0],
17159 &hits[1..],
17160 intrabc_source_share() * 100.0
17161 );
17162 let search = take_intrabc_search();
17163 eprintln!(
17164 "intrabc searches {} found-valid {} won-RD {}",
17165 search[0], search[1], search[2]
17166 );
17167 assert!(
17168 hits[0] > 0,
17169 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
17170 );
17171 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
17172 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
17173 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
17174 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
17175 if !have_ffmpeg() {
17176 eprintln!("SKIP the ffmpeg half: no ffmpeg");
17177 return;
17178 }
17179 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17180 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
17181 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
17182 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
17183 }
17184
17185 /// The minimal repro that isolated the inter-residual desync: a key frame
17186 /// followed by one inter frame whose single superblock carries one
17187 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
17188 /// coefficient, its three sibling blocks all `skip: true`. Before the
17189 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
17190 /// found when processing input") even though every symbol either block
17191 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
17192 /// same coefficient syntax decodes clean on every intra key-frame gate).
17193 #[test]
17194 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
17195 let _knobs = crate::speed::knob_write();
17196 let fctx = &crate::decode::FrameCtx::for_encoder();
17197 if !have_ffmpeg() {
17198 eprintln!(
17199 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
17200 );
17201 return;
17202 }
17203 let (width, height) = (64usize, 64usize);
17204 let picture = Picture::grey(width, height);
17205 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17206
17207 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
17208 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
17209
17210 let residual_block = BlockCoeffs {
17211 luma_tx_types: Vec::new(),
17212 angle_delta_y: 0,
17213 cfl_alphas: None,
17214 filter_intra: None,
17215 luma: vec![Coeff {
17216 row: 0,
17217 col: 0,
17218 level: 4,
17219 }],
17220 u: Vec::new(),
17221 v: Vec::new(),
17222 mode: 0,
17223 uv_mode: 0,
17224 skip: false,
17225 eight: None,
17226 dv: None,
17227 palette: None,
17228 palette_uv: None,
17229 tx_depth: 0,
17230 inter: Some(InterInfo {
17231 ref1: None,
17232 mv1: (0, 0),
17233 ref_frame: crate::mvstack::LAST_FRAME,
17234 mode: InterMode::NearestMv,
17235 mv: (0, 0),
17236 ref_mv_idx: 0,
17237 }),
17238 motion_mode: 0,
17239 };
17240 let skipped_block = BlockCoeffs {
17241 skip: true,
17242 inter: Some(InterInfo {
17243 ref1: None,
17244 mv1: (0, 0),
17245 ref_frame: crate::mvstack::LAST_FRAME,
17246 mode: InterMode::NearestMv,
17247 mv: (0, 0),
17248 ref_mv_idx: 0,
17249 }),
17250 ..BlockCoeffs::default()
17251 };
17252 let blocks = vec![
17253 Quadrant::Whole(residual_block),
17254 Quadrant::Whole(skipped_block.clone()),
17255 Quadrant::Whole(skipped_block.clone()),
17256 Quadrant::Whole(skipped_block),
17257 ];
17258 // lane-av1obmc: the header this tile is decoded under carries
17259 // `is_motion_mode_switchable`, so the writer must be armed with it
17260 // too or the decoder reads a `motion_mode` symbol nobody wrote.
17261 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
17262 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
17263 let tile = crate::tile::sb_coeff_inter_frame_tile(
17264 inter_header.mi_cols,
17265 inter_header.mi_rows,
17266 100,
17267 &blocks,
17268 )
17269 .unwrap();
17270
17271 // `key.stream` is already a temporal delimiter, the sequence header
17272 // and the key frame's own OBU (`encode_key_frame` built it from the
17273 // same `key_frame_headers(width, height, 100)` this test calls), so
17274 // the inter frame's OBU is appended straight onto it rather than
17275 // re-deriving the key frame's tile bytes.
17276 let mut stream = key.stream.clone();
17277 stream.extend_from_slice(&temporal_delimiter());
17278 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
17279
17280 ffmpeg_decode_sequence(&stream, width, height, 2);
17281 }
17282
17283 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
17284 /// frame size an AV1 decoder allocates, not necessarily the render size
17285 /// (see [`a_frame_round_trips_at_its_own_size`]).
17286 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
17287 // Distinct per call, not per process: the test binary runs callers on
17288 // parallel threads, and a shared name lets one test's cleanup delete
17289 // the stream another test's ffprobe is still reading.
17290 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
17291 let path = std::env::temp_dir().join(format!(
17292 "ec-av1-probe-{}-{}.obu",
17293 std::process::id(),
17294 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
17295 ));
17296 let _ = std::fs::remove_file(&path);
17297 std::fs::write(&path, stream).expect("writing the probe stream");
17298 let out = Command::new("ffprobe")
17299 .args([
17300 "-v",
17301 "error",
17302 "-f",
17303 "obu",
17304 "-select_streams",
17305 "v:0",
17306 "-show_entries",
17307 "stream=width,height",
17308 "-of",
17309 "csv=p=0",
17310 ])
17311 .arg(&path)
17312 .output()
17313 .expect("ffprobe failed to run");
17314 let _ = std::fs::remove_file(&path);
17315 assert!(
17316 out.status.success(),
17317 "ffprobe refused the stream: {}",
17318 String::from_utf8_lossy(&out.stderr)
17319 );
17320 let text = String::from_utf8_lossy(&out.stdout);
17321 let mut fields = text.trim().split(',');
17322 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
17323 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
17324 (width, height)
17325 }
17326
17327 /// lane-av1cap: the final filter replay against the capture decode it
17328 /// replaced, at the block-padded and straddling sizes the whole-frame
17329 /// tests cover -- `set_verify_final_replay` makes
17330 /// [`pick_and_apply_filters`] run both on every frame and assert, per
17331 /// frame, that the spliced picture and the two filter stages the
17332 /// restoration search reads are bit-identical over the frame's own crop.
17333 #[test]
17334 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
17335 let _knobs = crate::speed::knob_write();
17336 let fctx = &crate::decode::FrameCtx::for_encoder();
17337 crate::decode::set_verify_final_replay(true);
17338 for &(width, height) in &[
17339 (64usize, 56usize),
17340 (216, 96),
17341 (192, 120),
17342 (640, 352),
17343 (1280, 720),
17344 ] {
17345 eprintln!("--- {width}x{height}");
17346 let picture = test_card(width, height);
17347 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17348 }
17349 crate::decode::set_verify_final_replay(false);
17350 }
17351
17352 /// A key frame at an arbitrary even size round-trips through ffmpeg over
17353 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
17354 /// picture's own size, and what ffmpeg decodes over that same top-left
17355 /// region equals it sample for sample.
17356 ///
17357 /// This does not check that `ffprobe` reports the picture's own size,
17358 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
17359 /// (block-padded) frame size, the same one libaom itself would code for
17360 /// a non-block-aligned picture. `render_width`/`render_height` (which
17361 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
17362 /// decoder is required to crop pixels by, and ffmpeg's does not --
17363 /// checked empirically against ffprobe here and against a real libaom
17364 /// encode separately. So the coded size, not the render size, is what
17365 /// `ffprobe` is asserted to report below.
17366 #[test]
17367 fn a_frame_round_trips_at_its_own_size() {
17368 let _knobs = crate::speed::knob_read();
17369 let fctx = &crate::decode::FrameCtx::for_encoder();
17370 if !have_ffmpeg() {
17371 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
17372 return;
17373 }
17374 // 854x480 is covered separately by
17375 // `an_854x480_picture_round_trips_through_its_padding`, which its own
17376 // doc comment explains was worth keeping as its own test.
17377 for &(width, height) in &[
17378 (1920usize, 1080usize),
17379 (640, 352),
17380 (1280, 720),
17381 (64, 56),
17382 (854, 480),
17383 (216, 96),
17384 (192, 120),
17385 ] {
17386 let picture = test_card(width, height);
17387 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17388 assert_eq!(
17389 (encoded.reconstruction.width, encoded.reconstruction.height),
17390 (width, height),
17391 "{width}x{height}: reconstruction is cropped to the picture's own size"
17392 );
17393 assert_eq!(
17394 ffprobe_size(&encoded.stream),
17395 (width as u32, height as u32),
17396 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
17397 );
17398 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17399 assert_eq!(
17400 decoded.y, encoded.reconstruction.y,
17401 "{width}x{height}: luma"
17402 );
17403 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
17404 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
17405 }
17406 }
17407
17408 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
17409 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
17410 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
17411 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
17412 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
17413 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
17414 /// col`) -- different bits of an 8-byte table, one true, one false. The
17415 /// stride libaom indexes by is fixed at its compile-time maximum
17416 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
17417 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
17418 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
17419 /// row/col position within the (correctly 64-relative) superblock stayed
17420 /// right, only the table's own row stride was wrong. Fixed in
17421 /// `Reach::table_stride`; not an arithmetic-coder desync (an
17422 /// EC_RNG-per-symbol trace against the same debug decoder found the
17423 /// bitstream byte-for-byte identical to libaom's across all 51188
17424 /// symbols of this frame before this bug was found).
17425 ///
17426 /// Since the frame header started writing the true (unpadded) display
17427 /// size into `frame_width`/`frame_height` rather than the padded coded
17428 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
17429 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
17430 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
17431 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
17432 /// the header's own size before output).
17433 #[test]
17434 fn an_854x480_picture_round_trips_through_its_padding() {
17435 let _knobs = crate::speed::knob_read();
17436 let fctx = &crate::decode::FrameCtx::for_encoder();
17437 if !have_ffmpeg() {
17438 return;
17439 }
17440 let (width, height) = (854usize, 480usize);
17441 let picture = test_card(width, height);
17442 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17443 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17444 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
17445 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
17446 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
17447 }
17448
17449 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
17450 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
17451 /// superblock, both partition tables:
17452 ///
17453 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
17454 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
17455 /// wiring the TU sites onto it changes no existing stream;
17456 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
17457 /// NULL in libaom because that lookup never happens, and reading a
17458 /// 4x4 row out of the three-row vert tables is what crashed a real
17459 /// `--enable-tx-size-search=1` stream (r2);
17460 /// 3. and it must be the BLOCK's vert answer where the two tables
17461 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
17462 /// row 1, column 0 reads its above-right samples from the 8x8 to its
17463 /// upper right, which a vertical AB partition codes AFTER it
17464 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
17465 #[test]
17466 fn of_tu_follows_the_block_row_including_under_vert_ab() {
17467 let fctx = &crate::decode::FrameCtx::for_encoder();
17468 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
17469 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
17470 // above-right answer is the BLOCK's, which is the whole reason a unit
17471 // asks the block instead of looking itself up (the
17472 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
17473 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
17474 assert_eq!(
17475 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
17476 plain.above_right,
17477 "ordinary table: the top-right TX4 unit takes the block's row"
17478 );
17479 let guard = Reach::vert_ab_partition();
17480 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
17481 assert_eq!(
17482 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
17483 vert.above_right,
17484 "vert AB: the unit follows the vert row the block just picked"
17485 );
17486 assert_ne!(
17487 plain.above_right, vert.above_right,
17488 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
17489 );
17490 drop(guard);
17491 }
17492
17493 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
17494 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
17495 /// reconintra.c`), for every 16x16 and 32x32 block position across three
17496 /// superblocks square -- interior and every superblock edge (top row,
17497 /// left column, right column, bottom row) both sizes reach. Written to
17498 /// catch the class the `table_stride` bug was: an index stride silently
17499 /// wrong for one block size while looking plausible for the other.
17500 #[test]
17501 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
17502 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
17503 // it pins the 64 reach explicitly instead of following the process's
17504 // own superblock knob (`for_encoder`), which made it red under
17505 // `EC_AV1_SB128=1` for no defect of the code under test.
17506 let fctx = &crate::decode::FrameCtx::new();
17507 // Transcribed from has_top_right/has_bottom_left's row_off==0,
17508 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
17509 // 128px reference grid) pinned as libaom pins it, independent of the
17510 // 64px superblock this crate actually codes.
17511 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
17512 if y == 0 || x + side >= width {
17513 return false;
17514 }
17515 let (row, col, per_side) = (
17516 (y % SUPERBLOCK) / side,
17517 (x % SUPERBLOCK) / side,
17518 SUPERBLOCK / side,
17519 );
17520 if row == 0 {
17521 return true;
17522 }
17523 if col + 1 == per_side {
17524 return false;
17525 }
17526 let stride = 128 / side;
17527 let index = row * stride + col;
17528 let table = if side == BLOCK {
17529 [95u8, 87].to_vec()
17530 } else {
17531 vec![255, 85, 119, 85, 127, 85, 119, 85]
17532 };
17533 (table[index / 8] >> (index % 8)) & 1 != 0
17534 }
17535
17536 fn libaom_bottom_left(
17537 side: usize,
17538 x: usize,
17539 y: usize,
17540 height: usize,
17541 _fctx: &crate::decode::FrameCtx,
17542 ) -> bool {
17543 if x == 0 || y + side >= height {
17544 return false;
17545 }
17546 let (row, col, per_side) = (
17547 (y % SUPERBLOCK) / side,
17548 (x % SUPERBLOCK) / side,
17549 SUPERBLOCK / side,
17550 );
17551 if col == 0 {
17552 return row * side + side < SUPERBLOCK;
17553 }
17554 if row + 1 == per_side {
17555 return false;
17556 }
17557 let stride = 128 / side;
17558 let index = row * stride + col;
17559 let table = if side == BLOCK {
17560 [4u8, 4].to_vec()
17561 } else {
17562 vec![84, 16, 84, 0, 84, 16, 84, 0]
17563 };
17564 (table[index / 8] >> (index % 8)) & 1 != 0
17565 }
17566
17567 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
17568 for side in [16usize, BLOCK] {
17569 for y in (0..height).step_by(side) {
17570 for x in (0..width).step_by(side) {
17571 let reach = Reach::of(side, x, y, width, height, fctx);
17572 assert_eq!(
17573 reach.above_right,
17574 libaom_top_right(side, x, y, width, height),
17575 "side={side} x={x} y={y}: above_right"
17576 );
17577 assert_eq!(
17578 reach.below_left,
17579 libaom_bottom_left(side, x, y, height, fctx),
17580 "side={side} x={x} y={y}: below_left"
17581 );
17582 }
17583 }
17584 }
17585 }
17586
17587 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
17588 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
17589 /// column inside the superblock) may read the below-left samples the
17590 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
17591 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
17592 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
17593 /// stream that partitions that small first hits the still-refused
17594 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
17595 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
17596 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
17597 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
17598 /// pixels -- lane-palette2 r12: the square multi-TU path used the
17599 /// standalone-block tables instead of this rule and granted a 16x16
17600 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
17601 #[test]
17602 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
17603 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
17604 // *_count_unit = tx size / 4.
17605 fn libaom_tr(
17606 bw: usize,
17607 bh: usize,
17608 col_off: usize,
17609 row_off: usize,
17610 tx: usize,
17611 blk: bool,
17612 ) -> bool {
17613 let (plane_bw_unit, count) = (bw / 4, tx / 4);
17614 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
17615 let _ = bh;
17616 if row_off_u > 0 {
17617 col_off_u + count < plane_bw_unit
17618 } else if col_off_u + count < plane_bw_unit {
17619 true
17620 } else {
17621 blk
17622 }
17623 }
17624 fn libaom_bl(
17625 bw: usize,
17626 bh: usize,
17627 col_off: usize,
17628 row_off: usize,
17629 tx: usize,
17630 blk: bool,
17631 ) -> bool {
17632 let (plane_bh_unit, count) = (bh / 4, tx / 4);
17633 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
17634 let _ = bw;
17635 if col_off_u > 0 {
17636 false
17637 } else if row_off_u + count < plane_bh_unit {
17638 true
17639 } else {
17640 blk
17641 }
17642 }
17643 for &(bw, bh) in &[
17644 (8, 8),
17645 (16, 16),
17646 (32, 32),
17647 (64, 64),
17648 (16, 8),
17649 (8, 16),
17650 (32, 16),
17651 (16, 32),
17652 (64, 32),
17653 (32, 64),
17654 ] {
17655 for &tx in &[4usize, 8, 16, 32] {
17656 if tx > bw.min(bh) {
17657 continue;
17658 }
17659 for row_off in (0..bh).step_by(tx) {
17660 for col_off in (0..bw).step_by(tx) {
17661 for &blk in &[
17662 Reach {
17663 above_right: false,
17664 below_left: false,
17665 },
17666 Reach {
17667 above_right: true,
17668 below_left: true,
17669 },
17670 ] {
17671 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
17672 assert_eq!(
17673 got.above_right,
17674 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
17675 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
17676 );
17677 assert_eq!(
17678 got.below_left,
17679 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
17680 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
17681 );
17682 }
17683 }
17684 }
17685 }
17686 }
17687 }
17688
17689 #[test]
17690 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
17691 let fctx = &crate::decode::FrameCtx::for_encoder();
17692 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
17693 // Interior superblock, so neither the frame edge nor the col == 0 /
17694 // last-row early returns answer instead of the table.
17695 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
17696 let mut flipped = 0;
17697 for row in 0..8 {
17698 for col in 1..8 {
17699 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
17700 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
17701 let vert = {
17702 let _guard = Reach::vert_ab_partition();
17703 Reach::of(8, x, y, width, height, fctx).below_left
17704 };
17705 // The TR square of a VERT_A/_B sits at an even row, odd
17706 // column; every other slot must be untouched by the guard.
17707 if row % 2 == 0 && col % 2 == 1 {
17708 assert!(!raster, "raster below_left at row={row} col={col}");
17709 assert!(vert, "vert below_left at row={row} col={col}");
17710 flipped += 1;
17711 } else {
17712 assert_eq!(raster, vert, "guard moved row={row} col={col}");
17713 }
17714 }
17715 }
17716 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
17717 // The guard is scoped: it must not leak past its own block.
17718 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
17719 }
17720
17721 /// An odd width or height is refused by name, not by however the padder
17722 /// or the block coder would happen to fail on it.
17723 #[test]
17724 fn odd_dimensions_are_refused() {
17725 let _knobs = crate::speed::knob_read();
17726 let fctx = &crate::decode::FrameCtx::for_encoder();
17727 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
17728 let picture = Picture::grey(width, height);
17729 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
17730 .expect_err(&format!("{width}x{height} is odd and must be refused"));
17731 assert!(
17732 err.to_string().contains("even"),
17733 "{width}x{height}: error was {err}"
17734 );
17735 }
17736 }
17737
17738 /// A sequence at a size that is not a multiple of the block grid decodes
17739 /// to the right frame count and the right size for every frame,
17740 /// including the inter frames whose reference is the previous frame's
17741 /// own (padded) reconstruction.
17742 #[test]
17743 fn sequence_round_trips_at_a_non_multiple_size() {
17744 let _knobs = crate::speed::knob_read();
17745 let fctx = &crate::decode::FrameCtx::for_encoder();
17746 if !have_ffmpeg() {
17747 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
17748 return;
17749 }
17750 let (width, height) = (160usize, 96usize);
17751 let pictures: Vec<Picture> = (0..3)
17752 .map(|i| panned_test_card(width, height, i * 3))
17753 .collect();
17754 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17755 assert_eq!(encoded.frames.len(), 3);
17756 for (i, frame) in encoded.frames.iter().enumerate() {
17757 assert_eq!(
17758 (frame.reconstruction.width, frame.reconstruction.height),
17759 (width, height),
17760 "frame {i}: reconstruction size"
17761 );
17762 }
17763 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
17764 // true (display) size a sequence's frames share, not the padded one.
17765 assert_eq!(
17766 ffprobe_size(&encoded.stream),
17767 (width as u32, height as u32),
17768 "sequence: ffprobe reports the true (display) size"
17769 );
17770 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
17771 assert_eq!(decoded.len(), 3, "decoded frame count");
17772 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17773 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17774 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17775 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17776 }
17777 }
17778
17779 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
17780 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
17781 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
17782 /// `pos + side_mi / 2 < bound` boundary), which is the case
17783 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
17784 /// refusing. A key frame alone already covered this size; this proves the
17785 /// inter tile writer's parity with it across a real multi-frame export.
17786 #[test]
17787 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
17788 let _knobs = crate::speed::knob_read();
17789 let fctx = &crate::decode::FrameCtx::for_encoder();
17790 if !have_ffmpeg() {
17791 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
17792 return;
17793 }
17794 let (width, height) = (1280usize, 720usize);
17795 let pictures: Vec<Picture> = (0..3)
17796 .map(|i| panned_test_card(width, height, i * 3))
17797 .collect();
17798 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17799 assert_eq!(encoded.frames.len(), 3);
17800 for (i, frame) in encoded.frames.iter().enumerate() {
17801 assert_eq!(
17802 (frame.reconstruction.width, frame.reconstruction.height),
17803 (width, height),
17804 "frame {i}: reconstruction size"
17805 );
17806 }
17807 assert_eq!(
17808 ffprobe_size(&encoded.stream),
17809 (width as u32, height as u32),
17810 "ffprobe reports the true (display) 1280x720 size"
17811 );
17812 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
17813 assert_eq!(decoded.len(), 3, "decoded frame count");
17814 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17815 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17816 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17817 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17818 }
17819 }
17820
17821 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
17822 /// leaf's own half (`has_half` at the SUB level) itself straddles the
17823 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
17824 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
17825 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
17826 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
17827 /// straddling-16x16 branch), so an inter frame no longer refuses this
17828 /// size either. This only proves the encoder does not error out -- see
17829 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
17830 /// decoder-clean proof (a 3-frame sequence, so the inter path is
17831 /// actually exercised).
17832 #[test]
17833 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
17834 let _knobs = crate::speed::knob_read();
17835 let fctx = &crate::decode::FrameCtx::for_encoder();
17836 let (width, height) = (640usize, 360usize);
17837 let picture = Picture::grey(width, height);
17838 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
17839 .expect("key frame now codes the mod-32==8 straddle");
17840
17841 // `encode_sequence`'s second frame is the inter path: same size, now
17842 // wired the same way.
17843 let pictures = vec![picture.clone(), picture];
17844 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
17845 .expect("inter frame now codes the mod-32==8 straddle too");
17846 }
17847
17848 /// The r15 fix at production size: three 640x360 key frames (inter is
17849 /// still refused at this size, per the test above, so this stands in for
17850 /// the charter's "3-frame sequence" using three independent key frames of
17851 /// shifted content), each proven decoder-clean through ffmpeg rather than
17852 /// only encoder-clean.
17853 #[test]
17854 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
17855 let _knobs = crate::speed::knob_read();
17856 let fctx = &crate::decode::FrameCtx::for_encoder();
17857 if !have_ffmpeg() {
17858 eprintln!(
17859 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
17860 no ffmpeg"
17861 );
17862 return;
17863 }
17864 let (width, height) = (640usize, 360usize);
17865 for shift in [0i64, 7, 19] {
17866 let picture = panned_test_card(width, height, shift);
17867 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17868 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17869 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
17870 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
17871 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
17872 }
17873 }
17874
17875 /// The 640x360 straddle class, but through the inter path an actual
17876 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
17877 /// proves the leaf-8 inter stream this round wires up is not just
17878 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
17879 #[test]
17880 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
17881 let _knobs = crate::speed::knob_read();
17882 let fctx = &crate::decode::FrameCtx::for_encoder();
17883 if !have_ffmpeg() {
17884 eprintln!(
17885 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
17886 );
17887 return;
17888 }
17889 let (width, height) = (640usize, 360usize);
17890 let pictures: Vec<Picture> = (0..4)
17891 .map(|i| panned_test_card(width, height, i * 3))
17892 .collect();
17893 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17894 assert_eq!(encoded.frames.len(), 4);
17895 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
17896 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
17897 }
17898 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
17899 assert_eq!(decoded.len(), 4, "decoded frame count");
17900 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17901 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17902 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17903 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17904 }
17905 }
17906
17907 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
17908 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
17909 let out = Command::new("ffmpeg")
17910 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
17911 .args(["-vf", &format!("scale={width}:{height}")])
17912 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
17913 .output()
17914 .expect("ffmpeg failed to run");
17915 assert!(
17916 out.status.success(),
17917 "ffmpeg: {}",
17918 String::from_utf8_lossy(&out.stderr)
17919 );
17920 let (luma, chroma) = (width * height, width * height / 4);
17921 assert_eq!(
17922 out.stdout.len(),
17923 luma + 2 * chroma,
17924 "expected one 4:2:0 frame"
17925 );
17926 Picture {
17927 width,
17928 height,
17929 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
17930 u: out.stdout[luma..luma + chroma]
17931 .iter()
17932 .map(|&v| u16::from(v))
17933 .collect(),
17934 v: out.stdout[luma + chroma..]
17935 .iter()
17936 .map(|&v| u16::from(v))
17937 .collect(),
17938 }
17939 }
17940
17941 /// Prints what the mode search saves over DC prediction alone, for the
17942 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
17943 /// weight the search puts on rate can be swept.
17944 #[test]
17945 #[ignore = "a sweep, not a gate"]
17946 fn probe_lambda() {
17947 let _knobs = crate::speed::knob_read();
17948 let fctx = &crate::decode::FrameCtx::for_encoder();
17949 let mut pictures = vec![
17950 ("test card".to_string(), test_card(160, 96)),
17951 ("stripes".to_string(), stripes(160, 96, true)),
17952 ];
17953 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
17954 for entry in clips.split(':').filter(|e| !e.is_empty()) {
17955 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
17956 let name = path.rsplit('/').next().unwrap_or(path).to_string();
17957 pictures.push((name, clip_frame(path, skip, 640, 352)));
17958 }
17959 }
17960 for (name, picture) in pictures {
17961 let dc = ladder(&picture, &[DC_PRED], fctx);
17962 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
17963 println!(
17964 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
17965 bd_rate(&dc, &searched) * 100.0,
17966 10f64.powf(searched[1].1),
17967 searched[1].0,
17968 10f64.powf(dc[1].1),
17969 dc[1].0,
17970 );
17971 }
17972 }
17973
17974 /// Prints the whole mode-search ladder, so two builds of the search can be
17975 /// compared against each other rather than each against its own baseline.
17976 #[test]
17977 #[ignore = "a sweep, not a gate"]
17978 fn probe_ladder() {
17979 let _knobs = crate::speed::knob_read();
17980 let fctx = &crate::decode::FrameCtx::for_encoder();
17981 for (name, picture) in sweep_pictures() {
17982 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
17983 let points = all
17984 .iter()
17985 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
17986 .collect::<Vec<_>>()
17987 .join(" ");
17988 println!("ladder {name}: {points}");
17989 }
17990 }
17991
17992 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
17993 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
17994 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
17995 #[test]
17996 // ROBUST-RED on this tree, and the red is in the MEASURE, not the codec:
17997 // the `stripes` picture codes LOSSLESSLY at q110/90/70, so both ladders
17998 // come back as three identical `(inf, 1.8260748027008264)` points and
17999 // `bd_rate` has an empty trapezoid to integrate, which panics with
18000 // "the two ladders have to overlap in PSNR". Row 1 (`test card`) still
18001 // prints its number before the panic. Point `EC_AV1_CLIPS` at a real lossy
18002 // clip, or read only row 1.
18003 #[ignore = "a sweep, not a gate; PANICS on its own lossless synthetic rows (stripes is lossless at q110/90/70, so bd_rate has no PSNR overlap) -- point EC_AV1_CLIPS at a lossy clip"]
18004 fn probe_split() {
18005 let _knobs = crate::speed::knob_read();
18006 let fctx = &crate::decode::FrameCtx::for_encoder();
18007 for (name, picture) in sweep_pictures() {
18008 let ladder = |split: bool| {
18009 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
18010 .iter()
18011 .map(|&q| {
18012 let encoded = encode_key_frame_inner(
18013 &picture,
18014 q,
18015 0.5,
18016 &KEY_FRAME_MODES,
18017 split,
18018 (picture.width, picture.height),
18019 unspecified_color_config(),
18020 fctx,
18021 )
18022 .unwrap();
18023 (
18024 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
18025 (encoded.stream.len() as f64).log10(),
18026 )
18027 })
18028 .collect();
18029 points.sort_by(|a, b| a.0.total_cmp(&b.0));
18030 points
18031 };
18032 let (whole, split) = (ladder(false), ladder(true));
18033 let blocks = encode_key_frame_inner(
18034 &picture,
18035 90,
18036 0.5,
18037 &KEY_FRAME_MODES,
18038 true,
18039 (picture.width, picture.height),
18040 unspecified_color_config(),
18041 fctx,
18042 )
18043 .unwrap()
18044 .modes
18045 .len();
18046 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
18047 println!(
18048 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
18049 bd_rate(&whole, &split) * 100.0
18050 );
18051 }
18052 }
18053
18054 /// A striped picture, running one way or the other. The stripes are what
18055 /// separates a vertical predictor from a horizontal one: a mode search
18056 /// reading a transposed edge would pick the wrong one of the pair, which no
18057 /// symmetric picture would show.
18058 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
18059 let mut picture = Picture::grey(width, height);
18060 for y in 0..height {
18061 for x in 0..width {
18062 let along = if vertical { x } else { y };
18063 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
18064 }
18065 }
18066 picture
18067 }
18068
18069 /// Where two planes first disagree, and by how much: a mismatch reported as
18070 /// a position says which block and which sample of it went wrong, which a
18071 /// pair of thousand-sample arrays does not. A length difference counts as a
18072 /// disagreement: `zip` stops at the shorter plane, so a short one would
18073 /// otherwise compare exact over the prefix the two share.
18074 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
18075 if let Some(i) = ours.iter().zip(theirs).position(|(a, b)| a != b) {
18076 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
18077 return Some(format!(
18078 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
18079 i % width,
18080 i / width,
18081 ours[i],
18082 theirs[i]
18083 ));
18084 }
18085 if ours.len() != theirs.len() {
18086 return Some(format!(
18087 "no sample in the shared prefix differs, but ours is {} samples and theirs is {}",
18088 ours.len(),
18089 theirs.len()
18090 ));
18091 }
18092 None
18093 }
18094
18095 /// Every mode the encoder offers has to predict what the decoder predicts,
18096 /// not just the ones a particular picture happens to choose: each is forced
18097 /// over a whole picture and the reconstruction gated against ffmpeg.
18098 #[test]
18099 fn every_mode_decodes_to_what_the_encoder_predicted() {
18100 let _knobs = crate::speed::knob_write();
18101 let fctx = &crate::decode::FrameCtx::for_encoder();
18102 if !have_ffmpeg() {
18103 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
18104 return;
18105 }
18106 // A mode ablation measures the MODE search: a filter-intra block is
18107 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
18108 // "the encoder coded something else" check for a reason that is not
18109 // about the mode search at all.
18110 force_filter_intra(Some(false));
18111 // 128 wide is a whole number of superblocks and 160 is not: the last
18112 // superblock of a 160-wide row is half a one, whose blocks have no
18113 // above-right samples inside the frame at all.
18114 for (width, height) in [(128, 96), (160, 96)] {
18115 let picture = test_card(width, height);
18116 for mode in KEY_FRAME_MODES {
18117 let encoded =
18118 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx)
18119 .unwrap();
18120 let decoded = ffmpeg_decode(&encoded.stream, width, height);
18121 for (plane, ours, theirs, stride) in [
18122 ("luma", &encoded.reconstruction.y, &decoded.y, width),
18123 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
18124 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
18125 ] {
18126 assert!(
18127 first_difference(ours, theirs, stride).is_none(),
18128 "{width}x{height} mode {mode}, {plane}: {}",
18129 first_difference(ours, theirs, stride).unwrap()
18130 );
18131 }
18132 assert!(
18133 encoded.modes.iter().all(|&m| m == mode),
18134 "mode {mode}: the encoder coded something else"
18135 );
18136 }
18137 }
18138 }
18139
18140 /// The search has to follow the picture: vertical stripes are cheapest
18141 /// predicted from the row above, horizontal ones from the column to the
18142 /// left. Reading the edges the other way round would swap the two answers
18143 /// while leaving every fidelity gate intact.
18144 #[test]
18145 fn the_search_picks_the_direction_the_picture_runs() {
18146 let _knobs = crate::speed::knob_write();
18147 let fctx = &crate::decode::FrameCtx::for_encoder();
18148 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
18149 // a filter-intra block is coded `DC_PRED` whatever mode the arm
18150 // offers, and these stripes are SCREEN content, where the filter arm
18151 // now searches its own transform depth (lane-fitu) and wins outright
18152 // -- which says nothing about the mode search this gate measures.
18153 force_filter_intra(Some(false));
18154 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
18155 let picture = stripes(128, 96, vertical);
18156 // Only the pair, because on stripes a third mode predicts exactly
18157 // what the right one of the pair does -- PAETH reads the corner and
18158 // the left column, which a striped picture makes equal -- and the
18159 // tie then goes to whichever is cheaper to name, which is not what
18160 // this gate is about.
18161 let encoded =
18162 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx)
18163 .unwrap();
18164 // The first block of the picture has neither neighbour, so it
18165 // cannot tell the modes apart; every other one can.
18166 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
18167 assert!(
18168 picked * 2 > encoded.modes.len() - 1,
18169 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
18170 encoded.modes.len() - 1,
18171 encoded.modes
18172 );
18173 }
18174 }
18175
18176 /// What the search is for: the same picture, at the same quantizer, coded
18177 /// smaller and more faithfully than DC alone can manage.
18178 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
18179 /// between the two rate-distortion curves in log-rate against PSNR, as a
18180 /// fraction of the reference's rate. Negative means the second curve costs
18181 /// less for the same picture.
18182 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
18183 let low = reference[0].0.max(other[0].0);
18184 let high = reference[reference.len() - 1]
18185 .0
18186 .min(other[other.len() - 1].0);
18187 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
18188 // the non-directional one on the synthetic diagonals -- every point
18189 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
18190 // to integrate over any more. A curve that dominates that way has
18191 // saved everything the measure can express (the
18192 // `instrument-at-bound` class: the answer is at the instrument's own
18193 // edge, not undefined), so name it rather than panicking; anything
18194 // less clean than strict dominance still is.
18195 if high <= low {
18196 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
18197 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
18198 let dominates =
18199 other[0].0 > reference[reference.len() - 1].0 && other_hi_rate <= ref_lo_rate;
18200 assert!(
18201 dominates,
18202 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
18203 );
18204 return -1.0;
18205 }
18206 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
18207 let i = curve
18208 .windows(2)
18209 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
18210 .unwrap_or(0);
18211 let (x0, y0) = curve[i];
18212 let (x1, y1) = curve[i + 1];
18213 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
18214 };
18215 let steps = 64;
18216 let mut area = 0.0;
18217 for step in 0..steps {
18218 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
18219 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
18220 }
18221 10f64.powf(area / f64::from(steps)) - 1.0
18222 }
18223
18224 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
18225 /// fidelity.
18226 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
18227 // A mode ablation measures the MODE search: the palette would code
18228 // these synthetic two-colour pictures losslessly under every arm and
18229 // leave nothing to compare (see [`force_screen`]).
18230 force_screen(Some(false));
18231 // Same reason, for the filter-intra candidate: it wins blocks under
18232 // BOTH arms of a mode ablation and so cancels the difference the
18233 // ablation measures (class `gate-recipe-confound`).
18234 force_filter_intra(Some(false));
18235 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
18236 .iter()
18237 .map(|&q| {
18238 let encoded =
18239 encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
18240 (
18241 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
18242 (encoded.stream.len() as f64).log10(),
18243 )
18244 })
18245 .collect();
18246 points.sort_by(|a, b| a.0.total_cmp(&b.0));
18247 points
18248 }
18249
18250 /// What the search is for: the same pictures cost less to code at the same
18251 /// fidelity than DC prediction alone can manage. A picture that runs one
18252 /// way saves far more than a busy one, which is the shape a working
18253 /// directional pair has.
18254 #[test]
18255 fn the_search_beats_dc_alone() {
18256 let _knobs = crate::speed::knob_read();
18257 let fctx = &crate::decode::FrameCtx::for_encoder();
18258 for (name, picture, want) in [
18259 ("test card", test_card(160, 96), -0.05),
18260 ("stripes", stripes(160, 96, true), -0.40),
18261 ] {
18262 let saved = bd_rate(
18263 &ladder(&picture, &[DC_PRED], fctx),
18264 &ladder(&picture, &NON_DIRECTIONAL, fctx),
18265 );
18266 assert!(
18267 saved < want,
18268 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
18269 saved * 100.0,
18270 -want * 100.0
18271 );
18272 }
18273 }
18274
18275 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
18276 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
18277 fn sweep_pictures() -> Vec<(String, Picture)> {
18278 let mut pictures = vec![
18279 ("test card".to_string(), test_card(160, 96)),
18280 ("stripes".to_string(), stripes(160, 96, true)),
18281 ("diagonal".to_string(), diagonal(160, 96, true)),
18282 ];
18283 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
18284 for entry in clips.split(':').filter(|e| !e.is_empty()) {
18285 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
18286 let name = path.rsplit('/').next().unwrap_or(path).to_string();
18287 pictures.push((name, clip_frame(path, skip, 640, 352)));
18288 }
18289 }
18290 pictures
18291 }
18292
18293 /// What the six directional modes are worth, per picture, at whatever
18294 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
18295 /// no further, and how often the search picks one.
18296 #[test]
18297 #[ignore = "a sweep, not a gate"]
18298 fn probe_directional() {
18299 let _knobs = crate::speed::knob_write();
18300 let fctx = &crate::decode::FrameCtx::for_encoder();
18301 for (name, picture) in sweep_pictures() {
18302 let dc = ladder(&picture, &[DC_PRED], fctx);
18303 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
18304 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
18305 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
18306 let directional = encoded
18307 .modes
18308 .iter()
18309 .filter(|&&m| (3..=8).contains(&m))
18310 .count();
18311 // A picture whose ladders sit at different fidelities altogether
18312 // has no BD-rate to report -- see the flat-sample-window class.
18313 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
18314 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
18315 };
18316 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
18317 if overlap(a, b) {
18318 format!("{:+.2}%", bd_rate(a, b) * 100.0)
18319 } else {
18320 "no overlap".to_string()
18321 }
18322 };
18323 println!(
18324 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
18325 against(&flat, &all),
18326 against(&dc, &all),
18327 encoded.modes.len(),
18328 );
18329 }
18330 }
18331
18332 /// A picture whose stripes run along a diagonal, one way or the other.
18333 /// This is to the directional modes what [`stripes`] is to the vertical and
18334 /// horizontal pair: a predictor that walked the edge in the wrong direction
18335 /// would answer the two pictures the same way round.
18336 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
18337 let mut picture = Picture::grey(width, height);
18338 for y in 0..height {
18339 for x in 0..width {
18340 let along = if down_right { x + height - y } else { x + y };
18341 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
18342 }
18343 }
18344 picture
18345 }
18346
18347 /// The mode picked by the most blocks of a picture, ignoring the first
18348 /// block, which has no neighbours to tell the modes apart with.
18349 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
18350 // A mode ablation measures the MODE search: the palette would code
18351 // these synthetic two-colour pictures losslessly under every arm and
18352 // leave nothing to compare (see [`force_screen`]).
18353 force_screen(Some(false));
18354 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
18355 let blocks = &encoded.modes[1..];
18356 let mut counts = [0usize; 13];
18357 for &mode in blocks {
18358 counts[usize::from(mode)] += 1;
18359 }
18360 let (mode, count) = counts
18361 .iter()
18362 .enumerate()
18363 .max_by_key(|&(_, count)| *count)
18364 .expect("thirteen modes");
18365 (mode as u8, *count, blocks.len())
18366 }
18367
18368 /// The search has to follow a diagonal the way it runs: stripes down and to
18369 /// the right are cheapest predicted at 135 degrees, stripes down and to the
18370 /// left at 45. A walk that stepped the wrong way along the edge, or read
18371 /// the above row where it should read the left column, would swap these.
18372 #[test]
18373 fn the_search_picks_the_diagonal_the_picture_runs() {
18374 let _knobs = crate::speed::knob_write();
18375 let fctx = &crate::decode::FrameCtx::for_encoder();
18376 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
18377 let picture = diagonal(160, 96, down_right);
18378 let (mode, count, blocks) = favourite_mode(&picture, fctx);
18379 assert_eq!(
18380 mode, want,
18381 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
18382 );
18383 }
18384 }
18385
18386 /// What the directional modes are for: a picture that runs along a diagonal
18387 /// costs far less to code with them than the seven that read only their own
18388 /// edges can manage, and a picture that runs no particular way costs no
18389 /// more. The second half is the one that bites: a mode set the search
18390 /// cannot price is a mode set that loses rate on content that does not want
18391 /// it, which is what costing the mode symbol is for.
18392 #[test]
18393 fn the_diagonals_beat_the_modes_that_read_no_further() {
18394 let _knobs = crate::speed::knob_read();
18395 let fctx = &crate::decode::FrameCtx::for_encoder();
18396 for (name, picture, want) in [
18397 ("down-right", diagonal(160, 96, true), -0.20),
18398 ("down-left", diagonal(160, 96, false), -0.20),
18399 ("test card", test_card(160, 96), 0.01),
18400 ] {
18401 let saved = bd_rate(
18402 &ladder(&picture, &NON_DIRECTIONAL, fctx),
18403 &ladder(&picture, &KEY_FRAME_MODES, fctx),
18404 );
18405 assert!(
18406 saved < want,
18407 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
18408 saved * 100.0,
18409 -want * 100.0
18410 );
18411 }
18412 }
18413
18414 /// A mode the encoder cannot predict must be refused rather than coded as
18415 /// something else, and a search with nothing to choose from likewise.
18416 #[test]
18417 fn a_mode_the_encoder_cannot_predict_is_refused() {
18418 let _knobs = crate::speed::knob_read();
18419 let fctx = &crate::decode::FrameCtx::for_encoder();
18420 let picture = test_card(64, 64);
18421 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
18422 .unwrap_err()
18423 .to_string();
18424 assert!(
18425 message.contains("intra mode 13"),
18426 "the refusal must name the mode, got {message}"
18427 );
18428 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
18429 }
18430
18431 /// The picture that comes back is the picture that went in, to within the
18432 /// quantizer. A prediction that read the wrong neighbours, or a block
18433 /// written into the wrong place, would still decode to what the encoder
18434 /// reconstructed — it is this gate that says the reconstruction is of the
18435 /// right picture.
18436 #[test]
18437 fn the_encoded_picture_is_the_one_that_went_in() {
18438 let _knobs = crate::speed::knob_read();
18439 let fctx = &crate::decode::FrameCtx::for_encoder();
18440 let picture = test_card(160, 96);
18441 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18442 let luma = psnr(&encoded.reconstruction.y, &picture.y);
18443 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
18444 for (plane, (got, want)) in [
18445 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
18446 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
18447 ]
18448 .iter()
18449 .enumerate()
18450 {
18451 let chroma = psnr(got, want);
18452 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
18453 }
18454 }
18455
18456 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
18457 /// does the opposite. Both are monotone, which is what a rate-distortion
18458 /// loop above this will assume.
18459 #[test]
18460 fn fidelity_and_rate_move_with_the_quantizer() {
18461 let _knobs = crate::speed::knob_read();
18462 let fctx = &crate::decode::FrameCtx::for_encoder();
18463 let picture = test_card(128, 128);
18464 let mut previous: Option<(usize, f64)> = None;
18465 for &q in &[70u8, 90, 110] {
18466 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18467 let quality = psnr(&encoded.reconstruction.y, &picture.y);
18468 if let Some((bytes, better)) = previous {
18469 assert!(
18470 encoded.stream.len() < bytes,
18471 "q {q}: {} bytes",
18472 encoded.stream.len()
18473 );
18474 assert!(quality < better, "q {q}: PSNR {quality}");
18475 }
18476 previous = Some((encoded.stream.len(), quality));
18477 }
18478
18479 // The deadzone half of this claim lives in
18480 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
18481 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
18482 // every zeroing, the deadzone no longer moves a coded stream
18483 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
18484 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
18485 // job, not a quantiser defect.
18486
18487 // Bytes must not jump up across a q-context boundary: a wrong CDF
18488 // table for the far side would show up as a rate discontinuity here,
18489 // even though a coarser quantizer always codes no more than a finer
18490 // one on the same picture.
18491 //
18492 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
18493 // chroma searches its own mode, a coarser quantizer can pick a
18494 // *different* uv_mode on a block whose modes now cost nearly the
18495 // same, and the search prices that symbol against the static default
18496 // CDF while the writer codes it against an adapted one -- 311 -> 319
18497 // bytes at q 120->121 on this picture. The table this gate is really
18498 // watching would move the rate by far more than the mode churn does.
18499 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
18500 // same block can also change transform DEPTH between two neighbouring
18501 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
18502 // symbol is priced off the static CDF row 0 for the same reason the
18503 // uv_mode one is.
18504 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
18505 // path is pricing through the adapting CDF state (what
18506 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
18507 // drift of), after which the exact bound comes back.
18508 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
18509 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx)
18510 .unwrap()
18511 .stream
18512 .len();
18513 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx)
18514 .unwrap()
18515 .stream
18516 .len();
18517 assert!(
18518 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
18519 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
18520 );
18521 }
18522 }
18523
18524 /// A flat picture is a flat stream: every block predicts its neighbours'
18525 /// average, which is the picture's own value, and codes nothing.
18526 #[test]
18527 fn a_flat_picture_costs_almost_nothing() {
18528 let _knobs = crate::speed::knob_read();
18529 let fctx = &crate::decode::FrameCtx::for_encoder();
18530 let mut picture = Picture::grey(128, 128);
18531 picture.y.fill(97);
18532 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18533 // The first block has no neighbour and predicts 128, so it carries a
18534 // DC; every block after it predicts 97 and carries nothing.
18535 assert!(
18536 encoded.stream.len() < 100,
18537 "{} bytes for a flat picture",
18538 encoded.stream.len()
18539 );
18540 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
18541 assert_eq!(s, 97, "sample {i} of a flat picture");
18542 }
18543 }
18544
18545 /// The sizes the encoder refuses, refused for a reason rather than by
18546 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
18547 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
18548 /// lands past the halfway point of whichever block it falls in, so
18549 /// `PARTITION_NONE` or a single gathered split flag still says everything
18550 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
18551 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
18552 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
18553 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
18554 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
18555 /// refusal here claimed otherwise and was wrong; see
18556 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
18557 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
18558 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
18559 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
18560 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
18561 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
18562 /// still refused is a malformed picture.
18563 #[test]
18564 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
18565 let _knobs = crate::speed::knob_read();
18566 let fctx = &crate::decode::FrameCtx::for_encoder();
18567 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
18568 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
18569 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
18570 .expect("36 luma columns still round up to an even MiCols");
18571
18572 let mut short = Picture::grey(64, 64);
18573 short.u.truncate(10);
18574 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
18575 }
18576
18577 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
18578 /// column half only (`has_half` false on cols, true on rows) -- exactly
18579 /// the single-axis straddle lane-av1-rect r7 wires through
18580 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
18581 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
18582 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
18583 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
18584 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
18585 /// `partition_context_lookup` entry this writer ever produces (no 4x4
18586 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
18587 /// leaf regardless of neighbour state -- our writer already agreed with
18588 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
18589 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
18590 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
18591 /// it does not regress the gate. r11 tell-for-tell traced two further,
18592 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
18593 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
18594 /// leaves, when the second leaf's true above (or left) neighbour is the
18595 /// first leaf itself -- fixed by threading the first leaf's mode into the
18596 /// second leaf's context, mi-precise, like `record_mi` already does for
18597 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
18598 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
18599 /// `reduced_tx_set` is false), but this crate's key frames set
18600 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
18601 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
18602 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
18603 /// symbol bits to desync everything after it. Fixed with a new
18604 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
18605 /// eset/size slot). Both fixes are provably correct against libaom
18606 /// source and each closed part of the gap (leaf0's `eob` went from a
18607 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
18608 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
18609 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
18610 /// (do not reuse r11's committed logs, which predate its own fixes) and
18611 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
18612 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
18613 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
18614 /// every other `write_block` caller at 16x16 and up already passes
18615 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
18616 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
18617 /// different amount of arithmetic range and derailed everything after
18618 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
18619 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
18620 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
18621 /// never updating those coarse arrays itself -- so a *second* straddling
18622 /// 16x16 quadrant stacked above or left of the first (never covered by
18623 /// r11's same-call `prev_leaf` override, which only threads state
18624 /// between the two leaves of one shared quadrant) read whatever stale
18625 /// mode sat in that slot before either leaf ran. Fixed by writing the
18626 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
18627 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
18628 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
18629 /// offset of a single unit; fixing (3)+(4) together still leaves a
18630 /// residual divergence one leaf further in -- the decoder now reads
18631 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
18632 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
18633 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
18634 /// desyncs the stream by exactly the width of one earlier symbol -- not
18635 /// yet isolated to a single named symbol. r15 found the last bug: the
18636 /// header fix from r14 explained the rng skew fully, and the remaining
18637 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
18638 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
18639 /// loop, once per leaf, so the first leaf's write clobbered the true
18640 /// external neighbour mode the second leaf of the *same* straddling
18641 /// quadrant still needed for its non-adjacency axis (a column-straddle
18642 /// case: two leaves share one `outer_at` column index, so leaf 1's
18643 /// write to `left_mode[r]` overwrote the real western neighbour before
18644 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
18645 /// doing it once, after the whole leaf loop, from the last (bottom/
18646 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
18647 #[test]
18648 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
18649 let _knobs = crate::speed::knob_read();
18650 let fctx = &crate::decode::FrameCtx::for_encoder();
18651 if !have_ffmpeg() {
18652 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
18653 return;
18654 }
18655 let (width, height) = (40usize, 32usize);
18656 let picture = test_card(width, height);
18657 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18658 assert_eq!(
18659 (encoded.reconstruction.width, encoded.reconstruction.height),
18660 (width, height)
18661 );
18662 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
18663 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
18664 }
18665 let decoded = ffmpeg_decode(&encoded.stream, width, height);
18666 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
18667 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
18668 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
18669 }
18670
18671 /// A frame of real video, rather than a picture built to be easy.
18672 ///
18673 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
18674 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
18675 /// encoder's reconstruction has to survive the same equality gate as the
18676 /// synthetic pictures — real video reaches contexts a test card does not.
18677 #[test]
18678 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
18679 let _knobs = crate::speed::knob_read();
18680 let fctx = &crate::decode::FrameCtx::for_encoder();
18681 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
18682 eprintln!(
18683 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
18684 set EC_AV1_CLIP to a clip"
18685 );
18686 return;
18687 };
18688 if !have_ffmpeg() {
18689 eprintln!(
18690 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
18691 );
18692 return;
18693 }
18694 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
18695 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
18696 // test quick while still spanning many superblocks.
18697 let (width, height) = (640usize, 352usize);
18698 let picture = clip_frame(&clip, &skip, width, height);
18699
18700 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18701 let decoded = ffmpeg_decode(&encoded.stream, width, height);
18702 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
18703 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
18704 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
18705 eprintln!(
18706 "{} bytes, luma PSNR {:.2} dB",
18707 encoded.stream.len(),
18708 psnr(&decoded.y, &picture.y)
18709 );
18710 }
18711
18712 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
18713 /// sequence of these is a translation a motion search can actually find
18714 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
18715 /// inter frame's rate against the key frame's is measuring the same
18716 /// picture moving, not two different pictures.
18717 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
18718 let mut picture = Picture::grey(width, height);
18719 for y in 0..height {
18720 for x in 0..width {
18721 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
18722 let gradient = sx * 200.0 / width as f64;
18723 let ripple = 30.0
18724 * (sx * std::f64::consts::PI / 23.0).sin()
18725 * (y as f64 * std::f64::consts::PI / 37.0).cos();
18726 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
18727 40.0
18728 } else {
18729 0.0
18730 };
18731 picture.y[y * width + x] =
18732 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
18733 }
18734 }
18735 for y in 0..height / 2 {
18736 for x in 0..width / 2 {
18737 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
18738 let i = y * width / 2 + x;
18739 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
18740 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
18741 }
18742 }
18743 picture
18744 }
18745
18746 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
18747 fn ffmpeg_decode_sequence(
18748 stream: &[u8],
18749 width: usize,
18750 height: usize,
18751 frames: usize,
18752 ) -> Vec<Picture> {
18753 let out = run_with_stdin(
18754 Command::new("ffmpeg").args([
18755 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
18756 ]),
18757 stream,
18758 );
18759 assert!(
18760 out.status.success(),
18761 "ffmpeg refused the stream: {}",
18762 String::from_utf8_lossy(&out.stderr)
18763 );
18764 let (luma, chroma) = (width * height, width * height / 4);
18765 let frame_bytes = luma + 2 * chroma;
18766 assert_eq!(
18767 out.stdout.len(),
18768 frame_bytes * frames,
18769 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
18770 String::from_utf8_lossy(&out.stderr)
18771 );
18772 (0..frames)
18773 .map(|i| {
18774 let base = i * frame_bytes;
18775 Picture {
18776 width,
18777 height,
18778 y: out.stdout[base..base + luma]
18779 .iter()
18780 .map(|&v| u16::from(v))
18781 .collect(),
18782 u: out.stdout[base + luma..base + luma + chroma]
18783 .iter()
18784 .map(|&v| u16::from(v))
18785 .collect(),
18786 v: out.stdout[base + luma + chroma..base + frame_bytes]
18787 .iter()
18788 .map(|&v| u16::from(v))
18789 .collect(),
18790 }
18791 })
18792 .collect()
18793 }
18794
18795 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
18796 /// makes for a key frame, extended down the reference chain: each inter
18797 /// frame's reconstruction predicts from the previous frame's own decoded
18798 /// reconstruction, so a single sample of drift anywhere would propagate
18799 /// into every frame after it -- which is why every frame is checked, not
18800 /// just the last one, and why this is an equality and not a tolerance.
18801 #[test]
18802 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
18803 let _knobs = crate::speed::knob_read();
18804 let fctx = &crate::decode::FrameCtx::for_encoder();
18805 if !have_ffmpeg() {
18806 eprintln!(
18807 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
18808 );
18809 return;
18810 }
18811 let (width, height) = (128usize, 64usize);
18812 let pictures: Vec<Picture> = (0..5)
18813 .map(|i| panned_test_card(width, height, i * 3))
18814 .collect();
18815 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18816 assert_eq!(encoded.frames.len(), 5);
18817
18818 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
18819 assert_eq!(
18820 encoded.frames.len(),
18821 decoded.len(),
18822 "frame count: ours vs ffmpeg"
18823 );
18824 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18825 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
18826 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
18827 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
18828 }
18829
18830 eprintln!("frame bytes luma PSNR (dB) inter share");
18831 for (i, frame) in encoded.frames.iter().enumerate() {
18832 eprintln!(
18833 "{i:5} {:5} {:14.2} {:11.2}",
18834 frame.stream.len(),
18835 psnr(&frame.reconstruction.y, &pictures[i].y),
18836 frame.inter_block_share
18837 );
18838 }
18839 }
18840
18841 /// The same sequence through OUR OWN decoder, sample-exact against the
18842 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
18843 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
18844 /// divergence point at all, while our decoder can be traced symbol by
18845 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
18846 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
18847 /// names the first differing frame, plane and position.
18848 /// lane-sb128b: the writer used to price a `NEWMV` residual against
18849 /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
18850 /// write-time stack could not carry, while the drl symbols signalled the
18851 /// clamped index -- so the decoder derived a DIFFERENT motion vector with
18852 /// the entropy stream still in sync, and the drift only surfaced frames
18853 /// later as a drl desync (on film B, as the encoder's own trial decode
18854 /// refusing a reference slot).
18855 ///
18856 /// The clamp needs a stack that shrinks between search and write, which
18857 /// is what a 128x128 superblock's visit order does; the counter is the
18858 /// point (class `gate-blind-to-feature`): a green round trip on a clip
18859 /// that never clamps proves nothing.
18860 ///
18861 /// `#[ignore]`: [`force_sb128`] moves a process-global.
18862 ///
18863 /// The drl-clamp cell this gate's counter used to gate is no longer gated
18864 /// here: it is covered by
18865 /// [`every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`],
18866 /// which enumerates the pricer's offer set against the writer's rule (see
18867 /// its doc). The clamp needs a stack that shrinks between search and
18868 /// write, which is what a 128x128 superblock's visit order would do -- but
18869 /// the pricer never offers an index this tree's `write_drl_idx` cannot
18870 /// signal, so no clip can provoke it (lane-av1recipehunt: 153 attempts, 0;
18871 /// widening the pricer to `0..5` fires the counter immediately, reverting
18872 /// silences it). `drl_clamp_hits` is kept as the tripwire for that fix.
18873
18874 /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
18875 /// and one motion vector where the four 64x64 roots below spend four of
18876 /// each (cen3's L1). The counter is the gate on the fixture (class
18877 /// `gate-blind-to-feature`): a green round trip on a clip that never
18878 /// codes a 128x128 block proves nothing. RED before the search existed
18879 /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
18880 /// root by construction).
18881 ///
18882 /// Both readers: our own decoder sample-exact against the encoder's
18883 /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
18884 /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
18885 ///
18886 /// `#[ignore]`: [`force_sb128`] moves a process-global.
18887 ///
18888 /// cargo test -p ec-av1 --release --lib -- --ignored \
18889 /// a_128_superblock_clip_whose_root_search --nocapture
18890 #[test]
18891 #[ignore = "sets the process-global superblock size: run it alone"]
18892 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
18893 let _knobs = crate::speed::knob_write();
18894 if !have_ffmpeg() {
18895 eprintln!("SKIP: no ffmpeg");
18896 return;
18897 }
18898 force_sb128(true);
18899 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
18900 std::fs::create_dir_all(&dir).unwrap();
18901 let clip = dir.join("smpte-1280x768.y4m");
18902 // A slow horizontal pan over a still pattern: whole 128x128 regions
18903 // share one motion vector, which is exactly what a 128 root can code
18904 // as one block and four 64 roots cannot.
18905 let ok = Command::new("ffmpeg")
18906 .args(["-v", "error", "-y", "-f", "lavfi"])
18907 .args(["-i", "smptebars=size=1600x768:rate=24"])
18908 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
18909 .args(["-pix_fmt", "yuv420p"])
18910 .arg(&clip)
18911 .status()
18912 .expect("ffmpeg failed to run")
18913 .success();
18914 assert!(ok, "ffmpeg could not write the synthetic clip");
18915 let (width, height) = (1280usize, 768usize);
18916 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
18917 let _ = take_b128_none_hits();
18918 let _ = crate::tile::take_sb128_none_hits();
18919 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
18920 let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
18921 eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
18922 assert!(
18923 coded > 0,
18924 "no 128x128 block was coded on this clip, so it cannot witness the root search",
18925 );
18926 assert_eq!(
18927 won, coded,
18928 "every 128x128 root the search took must be coded as one"
18929 );
18930 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18931 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18932 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18933 let recon = &frame.reconstruction;
18934 for (plane, got, want) in [
18935 ("luma", &dec.y, &recon.y),
18936 ("U", &dec.u, &recon.u),
18937 ("V", &dec.v, &recon.v),
18938 ] {
18939 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18940 assert_eq!(
18941 differ,
18942 0,
18943 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18944 own reconstruction",
18945 got.len()
18946 );
18947 assert_eq!(
18948 got.len(),
18949 want.len(),
18950 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
18951 got.len(),
18952 want.len()
18953 );
18954 }
18955 }
18956 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18957 assert_eq!(
18958 encoded.frames.len(),
18959 ff.len(),
18960 "frame count: ours vs ffmpeg"
18961 );
18962 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18963 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
18964 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
18965 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
18966 }
18967 }
18968
18969 /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
18970 /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
18971 /// same pan the skip-only witness above uses, with the arm FORCED
18972 /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
18973 /// about once per frame, which witnesses the shape but not every context
18974 /// it reads, and forcing codes all 420 roots of the clip through it. RED
18975 /// before this lane by construction (`write_inter_block_128` refused
18976 /// every non-skip 128 block, so no such block existed to decode), and RED
18977 /// again on the first draft of the writer, whose neighbour band recorded
18978 /// `skip = true` for a block that carries a residual -- the next root's
18979 /// `skip` symbol then took CDF row 1 where the reader takes row 0.
18980 ///
18981 /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces
18982 /// the skip arm's cost unconditionally (that is what makes the writer see
18983 /// the residual), and the cost model moved under it since lane-b128r --
18984 /// lane-rectdq made every non-skipped root pay its delta_q group and the
18985 /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root
18986 /// lost its partition at ALL 420 roots and the writer coded none. q=60
18987 /// puts 52 written blocks back on this clip; the `coded > 0` assert below
18988 /// is the guard that catches the next such drift.
18989 ///
18990 /// cargo test -p ec-av1 --release --lib -- --ignored \
18991 /// a_128_root_block_with_a_real_residual --nocapture
18992 #[test]
18993 #[ignore = "sets the process-global superblock size: run it alone"]
18994 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
18995 let _knobs = crate::speed::knob_write();
18996 if !have_ffmpeg() {
18997 eprintln!("SKIP: no ffmpeg");
18998 return;
18999 }
19000 force_sb128(true);
19001 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
19002 std::fs::create_dir_all(&dir).unwrap();
19003 let clip = dir.join("smpte-pan-1280x768.y4m");
19004 let ok = Command::new("ffmpeg")
19005 .args(["-v", "error", "-y", "-f", "lavfi"])
19006 .args(["-i", "smptebars=size=1600x768:rate=24"])
19007 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
19008 .args(["-pix_fmt", "yuv420p"])
19009 .arg(&clip)
19010 .status()
19011 .expect("ffmpeg failed to run")
19012 .success();
19013 assert!(ok, "ffmpeg could not write the synthetic clip");
19014 let (width, height) = (1280usize, 768usize);
19015 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
19016 let _ = take_b128_residual_hits();
19017 let _ = crate::tile::take_sb128_residual_hits();
19018 force_b128_residual(true);
19019 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
19020 let (won, coded) = (
19021 take_b128_residual_hits(),
19022 crate::tile::take_sb128_residual_hits(),
19023 );
19024 eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
19025 assert!(
19026 coded > 0,
19027 "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
19028 );
19029 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19030 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19031 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19032 let recon = &frame.reconstruction;
19033 for (plane, got, want) in [
19034 ("luma", &dec.y, &recon.y),
19035 ("U", &dec.u, &recon.u),
19036 ("V", &dec.v, &recon.v),
19037 ] {
19038 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19039 assert_eq!(
19040 differ,
19041 0,
19042 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
19043 own reconstruction",
19044 got.len()
19045 );
19046 assert_eq!(
19047 got.len(),
19048 want.len(),
19049 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19050 got.len(),
19051 want.len()
19052 );
19053 }
19054 }
19055 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19056 assert_eq!(
19057 encoded.frames.len(),
19058 ff.len(),
19059 "frame count: ours vs ffmpeg"
19060 );
19061 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19062 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19063 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19064 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19065 }
19066 }
19067
19068 /// lane-edge128: a 128x128 root block WITH a residual on a clip whose
19069 /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec
19070 /// 5.11.56) codes ONE literal for the block that first reaches a unit and
19071 /// copies it over every unit the block SPANS, so the four units of a 128
19072 /// root share one index -- while the encoder's CDEF search prices a
19073 /// preset per unit and its filter replay applied all four. Only the first
19074 /// reached the stream, so every decoder filtered the other three with the
19075 /// origin's strengths and the encoder's reconstruction (the picture the
19076 /// next frame predicts from) was a filter apart from what a decoder
19077 /// produces. RED before this lane on the native BD gate's bars 2160p row
19078 /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples,
19079 /// the rows above the 128 superblock's own edge); the stream itself was
19080 /// always right -- ffmpeg and our own decoder agreed with each other and
19081 /// disagreed with the encoder.
19082 ///
19083 /// `take_cdef_covered_units` is the gate on the fixture (class
19084 /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair
19085 /// for the whole frame codes no literal at all and witnesses nothing.
19086 ///
19087 /// cargo test -p ec-av1 --release --lib -- --ignored \
19088 /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture
19089 #[test]
19090 #[ignore = "sets the process-global superblock size: run it alone"]
19091 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
19092 let _knobs = crate::speed::knob_write();
19093 if !have_ffmpeg() {
19094 eprintln!("SKIP: no ffmpeg");
19095 return;
19096 }
19097 force_sb128(true);
19098 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
19099 std::fs::create_dir_all(&dir).unwrap();
19100 let clip = dir.join("testsrc2-1280x768.y4m");
19101 // Detailed synthetic content: its CDEF search spends more than one
19102 // strength pair, which is what puts a `cdef_idx` literal in the tile.
19103 let ok = Command::new("ffmpeg")
19104 .args(["-v", "error", "-y", "-f", "lavfi"])
19105 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19106 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19107 .arg(&clip)
19108 .status()
19109 .expect("ffmpeg failed to run")
19110 .success();
19111 assert!(ok, "ffmpeg could not write the synthetic clip");
19112 let (width, height) = (1280usize, 768usize);
19113 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19114 force_b128_root(true);
19115 force_b128_residual(true);
19116 let _ = crate::tile::take_sb128_residual_hits();
19117 let _ = crate::filter_search::take_cdef_covered_units();
19118 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
19119 let coded = crate::tile::take_sb128_residual_hits();
19120 let covered = crate::filter_search::take_cdef_covered_units();
19121 eprintln!(
19122 "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
19123 another unit's literal: {covered}"
19124 );
19125 assert!(
19126 coded > 0,
19127 "no 128x128 block carried a residual on this clip"
19128 );
19129 assert!(
19130 covered > 0,
19131 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
19132 cannot witness the rule",
19133 );
19134 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19135 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19136 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19137 for (plane, got, want) in [
19138 ("luma", &dec.y, &frame.reconstruction.y),
19139 ("U", &dec.u, &frame.reconstruction.u),
19140 ("V", &dec.v, &frame.reconstruction.v),
19141 ] {
19142 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19143 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
19144 assert_eq!(
19145 got.len(),
19146 want.len(),
19147 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19148 got.len(),
19149 want.len()
19150 );
19151 }
19152 }
19153 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19154 assert_eq!(
19155 encoded.frames.len(),
19156 ff.len(),
19157 "frame count: ours vs ffmpeg"
19158 );
19159 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19160 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19161 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19162 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19163 }
19164 }
19165
19166 /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
19167 /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
19168 /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
19169 /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
19170 /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
19171 /// rect partition with [`force_b128_rect`]) so every inter root of the
19172 /// clip goes through it; the `coded > 0` assert is the guard that catches
19173 /// the next fixture drift (the whole-128 twin of this witness went RED
19174 /// twice that way).
19175 ///
19176 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
19177 /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
19178 #[test]
19179 #[ignore = "sets the process-global superblock size: run it alone"]
19180 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
19181 let _knobs = crate::speed::knob_write();
19182 if !have_ffmpeg() {
19183 eprintln!("SKIP: no ffmpeg");
19184 return;
19185 }
19186 force_sb128(true);
19187 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
19188 std::fs::create_dir_all(&dir).unwrap();
19189 let clip = dir.join("smpte-pan-1280x768.y4m");
19190 let ok = Command::new("ffmpeg")
19191 .args(["-v", "error", "-y", "-f", "lavfi"])
19192 .args(["-i", "smptebars=size=1600x768:rate=24"])
19193 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
19194 .args(["-pix_fmt", "yuv420p"])
19195 .arg(&clip)
19196 .status()
19197 .expect("ffmpeg failed to run")
19198 .success();
19199 assert!(ok, "ffmpeg could not write the synthetic clip");
19200 let (width, height) = (1280usize, 768usize);
19201 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
19202 force_b128_rect(1);
19203 force_b128_rectres(true);
19204 let _ = take_b128_rectres_hits();
19205 let _ = crate::tile::take_sb128_rectres_hits();
19206 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
19207 let (won, coded) = (
19208 take_b128_rectres_hits(),
19209 crate::tile::take_sb128_rectres_hits(),
19210 );
19211 eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
19212 assert!(
19213 coded > 0,
19214 "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
19215 );
19216 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19217 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19218 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19219 let recon = &frame.reconstruction;
19220 for (plane, got, want) in [
19221 ("luma", &dec.y, &recon.y),
19222 ("U", &dec.u, &recon.u),
19223 ("V", &dec.v, &recon.v),
19224 ] {
19225 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19226 assert_eq!(
19227 differ,
19228 0,
19229 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
19230 own reconstruction",
19231 got.len()
19232 );
19233 assert_eq!(
19234 got.len(),
19235 want.len(),
19236 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19237 got.len(),
19238 want.len()
19239 );
19240 }
19241 }
19242 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19243 assert_eq!(
19244 encoded.frames.len(),
19245 ff.len(),
19246 "frame count: ours vs ffmpeg"
19247 );
19248 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19249 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19250 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19251 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19252 }
19253 }
19254
19255 /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
19256 /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
19257 /// the two 64x64 squares through the one-chunk arm (the shape libaom's
19258 /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
19259 /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
19260 /// reference picture the GOP has not produced yet, which refuses before
19261 /// any AB root is coded.
19262 ///
19263 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
19264 /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
19265 #[test]
19266 #[ignore = "sets the process-global superblock size: run it alone"]
19267 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
19268 let _knobs = crate::speed::knob_write();
19269 if !have_ffmpeg() {
19270 eprintln!("SKIP: no ffmpeg");
19271 return;
19272 }
19273 force_sb128(true);
19274 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
19275 std::fs::create_dir_all(&dir).unwrap();
19276 let clip = dir.join("testsrc2-1280x768.y4m");
19277 let ok = Command::new("ffmpeg")
19278 .args(["-v", "error", "-y", "-f", "lavfi"])
19279 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19280 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19281 .arg(&clip)
19282 .status()
19283 .expect("ffmpeg failed to run")
19284 .success();
19285 assert!(ok, "ffmpeg could not write the synthetic clip");
19286 let (width, height) = (1280usize, 768usize);
19287 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19288 force_b128_ab(4);
19289 force_b128_rectres(true);
19290 let _ = take_b128_rectres_hits();
19291 let _ = crate::tile::take_sb128_rectres_hits();
19292 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
19293 let (won, coded) = (
19294 take_b128_rectres_hits(),
19295 crate::tile::take_sb128_rectres_hits(),
19296 );
19297 eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
19298 assert!(
19299 coded > 0,
19300 "no AB piece carried a residual on this clip, so it cannot witness the arm",
19301 );
19302 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19303 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19304 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19305 let recon = &frame.reconstruction;
19306 for (plane, got, want) in [
19307 ("luma", &dec.y, &recon.y),
19308 ("U", &dec.u, &recon.u),
19309 ("V", &dec.v, &recon.v),
19310 ] {
19311 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19312 assert_eq!(
19313 differ,
19314 0,
19315 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
19316 own reconstruction",
19317 got.len()
19318 );
19319 assert_eq!(
19320 got.len(),
19321 want.len(),
19322 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19323 got.len(),
19324 want.len()
19325 );
19326 }
19327 }
19328 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19329 assert_eq!(
19330 encoded.frames.len(),
19331 ff.len(),
19332 "frame count: ours vs ffmpeg"
19333 );
19334 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19335 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19336 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19337 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19338 }
19339 }
19340
19341 /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
19342 /// half WITH a residual under a clip whose CDEF search codes a
19343 /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
19344 /// and the decoder stamps BOTH units it spans with it, so the owner map
19345 /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
19346 /// collapse the pair -- exactly the bug class that broke bars 2160p at
19347 /// the whole-128 root. RED before this lane by construction: no rect
19348 /// piece could carry a residual, so no such literal existed.
19349 ///
19350 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
19351 /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
19352 #[test]
19353 #[ignore = "sets the process-global superblock size: run it alone"]
19354 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
19355 let _knobs = crate::speed::knob_write();
19356 if !have_ffmpeg() {
19357 eprintln!("SKIP: no ffmpeg");
19358 return;
19359 }
19360 force_sb128(true);
19361 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
19362 std::fs::create_dir_all(&dir).unwrap();
19363 let clip = dir.join("testsrc2-1280x768.y4m");
19364 // Detailed synthetic content: its CDEF search spends more than one
19365 // strength pair, which is what puts a `cdef_idx` literal in the tile.
19366 let ok = Command::new("ffmpeg")
19367 .args(["-v", "error", "-y", "-f", "lavfi"])
19368 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19369 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19370 .arg(&clip)
19371 .status()
19372 .expect("ffmpeg failed to run")
19373 .success();
19374 assert!(ok, "ffmpeg could not write the synthetic clip");
19375 let (width, height) = (1280usize, 768usize);
19376 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19377 force_b128_rect(1);
19378 force_b128_rectres(true);
19379 let _ = crate::tile::take_sb128_rectres_hits();
19380 let _ = crate::filter_search::take_cdef_covered_units();
19381 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
19382 let coded = crate::tile::take_sb128_rectres_hits();
19383 let covered = crate::filter_search::take_cdef_covered_units();
19384 eprintln!(
19385 "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
19386 another unit's literal: {covered}"
19387 );
19388 assert!(coded > 0, "no 128x64 half carried a residual on this clip");
19389 assert!(
19390 covered > 0,
19391 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
19392 cannot witness the rule",
19393 );
19394 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19395 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19396 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19397 for (plane, got, want) in [
19398 ("luma", &dec.y, &frame.reconstruction.y),
19399 ("U", &dec.u, &frame.reconstruction.u),
19400 ("V", &dec.v, &frame.reconstruction.v),
19401 ] {
19402 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19403 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
19404 assert_eq!(
19405 got.len(),
19406 want.len(),
19407 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19408 got.len(),
19409 want.len()
19410 );
19411 }
19412 }
19413 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19414 assert_eq!(
19415 encoded.frames.len(),
19416 ff.len(),
19417 "frame count: ours vs ffmpeg"
19418 );
19419 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19420 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19421 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19422 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19423 }
19424 }
19425
19426 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
19427 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
19428 /// `write_compound_block` chain every smaller compound block takes, at a
19429 /// window it had never been exercised at. RED before this lane: the
19430 /// search passed an empty compound list at the 128 root, so the count was
19431 /// 0 and no such block existed to decode.
19432 ///
19433 /// cargo test -p ec-av1 --release --lib -- --ignored \
19434 /// a_128_root_compound_block --nocapture
19435 #[test]
19436 #[ignore = "sets the process-global superblock size: run it alone"]
19437 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
19438 let _knobs = crate::speed::knob_write();
19439 if !have_ffmpeg() {
19440 eprintln!("SKIP: no ffmpeg");
19441 return;
19442 }
19443 force_sb128(true);
19444 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
19445 std::fs::create_dir_all(&dir).unwrap();
19446 let clip = dir.join("testsrc2-1280x768.y4m");
19447 // Moving objects that occlude each other: a pan is coded by one
19448 // reference outright, and a compound pair only pays where the two
19449 // references disagree.
19450 let ok = Command::new("ffmpeg")
19451 .args(["-v", "error", "-y", "-f", "lavfi"])
19452 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19453 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19454 .arg(&clip)
19455 .status()
19456 .expect("ffmpeg failed to run")
19457 .success();
19458 assert!(ok, "ffmpeg could not write the synthetic clip");
19459 let (width, height) = (1280usize, 768usize);
19460 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19461 // The compound candidate wins the 128 block's own search on this pan
19462 // but the root then loses to its four cells, so the root is forced
19463 // (the residual arm is left at its default, off).
19464 force_b128_root(true);
19465 let _ = take_b128_compound_hits();
19466 let _ = crate::tile::take_sb128_compound_hits();
19467 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19468 let (won, coded) = (
19469 take_b128_compound_hits(),
19470 crate::tile::take_sb128_compound_hits(),
19471 );
19472 eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
19473 assert!(
19474 coded > 0,
19475 "no compound 128x128 block was coded on this clip"
19476 );
19477 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19478 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19479 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19480 for (plane, got, want) in [
19481 ("luma", &dec.y, &frame.reconstruction.y),
19482 ("U", &dec.u, &frame.reconstruction.u),
19483 ("V", &dec.v, &frame.reconstruction.v),
19484 ] {
19485 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19486 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
19487 assert_eq!(
19488 got.len(),
19489 want.len(),
19490 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19491 got.len(),
19492 want.len()
19493 );
19494 }
19495 }
19496 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19497 assert_eq!(
19498 encoded.frames.len(),
19499 ff.len(),
19500 "frame count: ours vs ffmpeg"
19501 );
19502 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19503 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19504 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19505 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19506 }
19507 }
19508
19509 /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
19510 /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
19511 /// square. Three passes over one `testsrc2` clip:
19512 ///
19513 /// * HORZ forced at every root ([`force_b128_rect`]), so every context
19514 /// the 128x64 shape reads is exercised rather than the handful the RD
19515 /// would pick;
19516 /// * VERT forced the same way;
19517 /// * UNFORCED, which is the count the gate rows are read against -- the
19518 /// same clip with the RD free to choose among NONE / HORZ / VERT /
19519 /// four superblocks.
19520 ///
19521 /// Each pass is sample-exact against the encoder's own reconstruction
19522 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
19523 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
19524 /// before this lane by construction: `write_sb128_root` could only name
19525 /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
19526 ///
19527 /// cargo test -p ec-av1 --release --lib -- --ignored \
19528 /// a_128_root_horz_and_vert --nocapture
19529 #[test]
19530 #[ignore = "sets the process-global superblock size: run it alone"]
19531 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
19532 let _knobs = crate::speed::knob_write();
19533 if !have_ffmpeg() {
19534 eprintln!("SKIP: no ffmpeg");
19535 return;
19536 }
19537 force_sb128(true);
19538 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
19539 std::fs::create_dir_all(&dir).unwrap();
19540 let clip = dir.join("testsrc2-1280x768.y4m");
19541 let ok = Command::new("ffmpeg")
19542 .args(["-v", "error", "-y", "-f", "lavfi"])
19543 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19544 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19545 .arg(&clip)
19546 .status()
19547 .expect("ffmpeg failed to run")
19548 .success();
19549 assert!(ok, "ffmpeg could not write the synthetic clip");
19550 let (width, height) = (1280usize, 768usize);
19551 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19552 let mut unforced = (0usize, 0usize);
19553 for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
19554 force_b128_rect(force);
19555 let _ = take_b128_horz_hits();
19556 let _ = take_b128_vert_hits();
19557 let _ = crate::tile::take_sb128_horz_hits();
19558 let _ = crate::tile::take_sb128_vert_hits();
19559 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19560 let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
19561 let (coded_h, coded_v) = (
19562 crate::tile::take_sb128_horz_hits(),
19563 crate::tile::take_sb128_vert_hits(),
19564 );
19565 eprintln!(
19566 "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
19567 {coded_h} 128x64 + {coded_v} 64x128 halves"
19568 );
19569 match force {
19570 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
19571 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
19572 // The unforced count is REPORTED, not asserted: it is the
19573 // number the gate is read against, and a zero here would be
19574 // an RD result, not a defect (the forced passes already prove
19575 // the writer and the reader agree on the shape).
19576 _ => unforced = (won_h, won_v),
19577 }
19578 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19579 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
19580 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19581 for (plane, got, want) in [
19582 ("luma", &dec.y, &frame.reconstruction.y),
19583 ("U", &dec.u, &frame.reconstruction.u),
19584 ("V", &dec.v, &frame.reconstruction.v),
19585 ] {
19586 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19587 assert_eq!(
19588 differ, 0,
19589 "{label} frame {i}: {plane} -- {differ} samples differ"
19590 );
19591 assert_eq!(
19592 got.len(),
19593 want.len(),
19594 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
19595 got.len(),
19596 want.len()
19597 );
19598 }
19599 }
19600 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19601 assert_eq!(
19602 encoded.frames.len(),
19603 ff.len(),
19604 "{label}: frame count: ours vs ffmpeg"
19605 );
19606 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19607 assert_eq!(
19608 dec.y, frame.reconstruction.y,
19609 "{label} frame {i}: ffmpeg luma"
19610 );
19611 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
19612 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
19613 }
19614 }
19615 force_b128_rect(0);
19616 eprintln!(
19617 "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
19618 unforced.0, unforced.1
19619 );
19620 }
19621
19622 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
19623 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
19624 /// Five passes over the same `testsrc2` clip
19625 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
19626 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
19627 /// context and every visit order the shape reads is exercised rather than
19628 /// the handful the RD would pick, and then an UNFORCED pass whose
19629 /// per-shape count is REPORTED (it is the number the gate rows are read
19630 /// against).
19631 ///
19632 /// Each pass is sample-exact against the encoder's own reconstruction
19633 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
19634 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
19635 /// before this lane by construction: `write_sb128_root` could only name
19636 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
19637 ///
19638 /// cargo test -p ec-av1 --release --lib -- --ignored \
19639 /// a_128_root_ab_shapes --nocapture
19640 #[test]
19641 #[ignore = "sets the process-global superblock size: run it alone"]
19642 fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
19643 let _knobs = crate::speed::knob_write();
19644 if !have_ffmpeg() {
19645 eprintln!("SKIP: no ffmpeg");
19646 return;
19647 }
19648 force_sb128(true);
19649 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
19650 std::fs::create_dir_all(&dir).unwrap();
19651 let clip = dir.join("testsrc2-1280x768.y4m");
19652 let ok = Command::new("ffmpeg")
19653 .args(["-v", "error", "-y", "-f", "lavfi"])
19654 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19655 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19656 .arg(&clip)
19657 .status()
19658 .expect("ffmpeg failed to run")
19659 .success();
19660 assert!(ok, "ffmpeg could not write the synthetic clip");
19661 let (width, height) = (1280usize, 768usize);
19662 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19663 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
19664 let mut unforced = [0usize; 4];
19665 for force in [4u8, 5, 6, 7, 0] {
19666 force_b128_ab(force);
19667 let label = if force == 0 {
19668 "unforced"
19669 } else {
19670 names[usize::from(force) - 4]
19671 };
19672 let _ = take_b128_ab_hits();
19673 let _ = crate::tile::take_sb128_ab_hits();
19674 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19675 let won = take_b128_ab_hits();
19676 let coded = crate::tile::take_sb128_ab_hits();
19677 eprintln!(
19678 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
19679 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
19680 );
19681 if force == 0 {
19682 // The unforced counts are REPORTED, not asserted: a zero here
19683 // would be an RD result, not a defect (the four forced passes
19684 // already prove the writer and the reader agree on the shape).
19685 unforced = won;
19686 } else {
19687 let i = usize::from(force) - 4;
19688 assert!(
19689 coded[i] > 0,
19690 "no {label} root was coded with {label} forced"
19691 );
19692 }
19693 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19694 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
19695 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19696 for (plane, got, want) in [
19697 ("luma", &dec.y, &frame.reconstruction.y),
19698 ("U", &dec.u, &frame.reconstruction.u),
19699 ("V", &dec.v, &frame.reconstruction.v),
19700 ] {
19701 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19702 assert_eq!(
19703 differ, 0,
19704 "{label} frame {i}: {plane} -- {differ} samples differ"
19705 );
19706 assert_eq!(
19707 got.len(),
19708 want.len(),
19709 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
19710 got.len(),
19711 want.len()
19712 );
19713 }
19714 }
19715 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19716 assert_eq!(
19717 encoded.frames.len(),
19718 ff.len(),
19719 "{label}: frame count: ours vs ffmpeg"
19720 );
19721 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19722 assert_eq!(
19723 dec.y, frame.reconstruction.y,
19724 "{label} frame {i}: ffmpeg luma"
19725 );
19726 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
19727 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
19728 }
19729 }
19730 force_b128_ab(0);
19731 eprintln!(
19732 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
19733 unforced[0], unforced[1], unforced[2], unforced[3],
19734 );
19735 }
19736
19737 #[test]
19738 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
19739 let _knobs = crate::speed::knob_read();
19740 let fctx = &crate::decode::FrameCtx::for_encoder();
19741 // 256x128, not the 128x64 this started at: once a leaf could search
19742 // its second reference (lane-av1comp4) the small card's every
19743 // eligible block went to a compound winner, which commits its flat
19744 // transform, and the split below stopped firing on content that
19745 // still splits at every larger size ([[gate-blind-to-feature]] --
19746 // the guard is right, the fixture had shrunk under it).
19747 let (width, height) = (256usize, 128usize);
19748 let pictures: Vec<Picture> = (0..5)
19749 .map(|i| panned_test_card(width, height, i * 3))
19750 .collect();
19751 let _ = take_inter_tx_split_hits();
19752 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19753 let raw = take_inter_tx_split_hits();
19754 // Summed over the four block classes the census keys on (leaf/32x32 x
19755 // single/compound): this assert is about the split firing at all.
19756 let split = [
19757 raw.iter().step_by(2).sum::<usize>(),
19758 raw.iter().skip(1).step_by(2).sum::<usize>(),
19759 ];
19760 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
19761 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
19762 // content splits -- a green round trip in which the split never fires
19763 // would prove only the flat path.
19764 if tx_select() && tx_select_inter() {
19765 assert!(split[1] > 0, "the inter var-tx split never fired");
19766 }
19767 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19768 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19769 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19770 let recon = &frame.reconstruction;
19771 for (plane, got, want, stride) in [
19772 ("luma", &dec.y, &recon.y, width),
19773 ("U", &dec.u, &recon.u, width / 2),
19774 ("V", &dec.v, &recon.v, width / 2),
19775 ] {
19776 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
19777 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
19778 panic!(
19779 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
19780 reconstruction {} ({} of {} samples differ)",
19781 at % stride,
19782 at / stride,
19783 got[at],
19784 want[at],
19785 got.iter().zip(want).filter(|(a, b)| a != b).count(),
19786 got.len(),
19787 );
19788 }
19789 }
19790 }
19791 }
19792
19793 /// The rate term the mode search ranks every decision by has to be the
19794 /// rate the writer then spends. The search prices a block's coefficients
19795 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
19796 /// against the default CDFs a tile starts from and the contexts of a
19797 /// block whose neighbours coded nothing -- while the tile writer codes
19798 /// them against a state that has been adapting all frame (the
19799 /// price-the-narrowing class). This measures that drift: the sum of what
19800 /// the search paid for the coefficients it kept, against the bytes the
19801 /// writer actually emitted for the whole tile (which also carries the
19802 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
19803 /// expected to be the larger of the two).
19804 #[test]
19805 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
19806 let _knobs = crate::speed::knob_read();
19807 let fctx = &crate::decode::FrameCtx::for_encoder();
19808 let (width, height) = (256usize, 128usize);
19809 let pictures: Vec<Picture> = (0..5)
19810 .map(|i| panned_test_card(width, height, i * 2))
19811 .collect();
19812 let _ = take_predicted_bits();
19813 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19814 let predicted = take_predicted_bits();
19815 assert_eq!(predicted.len(), encoded.frames.len());
19816
19817 eprintln!("frame predicted bits written bits drift");
19818 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
19819 // defect this gate exists to catch), a positive one is the written
19820 // side carrying syntax the coefficient sum leaves out -- and since
19821 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
19822 // on that side, so the two directions no longer share a bound.
19823 let mut worst_over: f64 = 0.0;
19824 let mut worst_under: f64 = 0.0;
19825 // The census is per CODED frame, so it is zipped in coding order --
19826 // which is not display order under a pyramid.
19827 let coded: Vec<&Encoded> = encoded
19828 .coding_order
19829 .iter()
19830 .map(|&i| &encoded.frames[i])
19831 .collect();
19832 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
19833 let written = frame.tile.len() as f64 * 8.0;
19834 let drift = (written - bits) / written;
19835 worst_over = worst_over.max(-drift);
19836 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
19837 // all (150-250 bits of tile, nearly all of it partition/mode/mv
19838 // syntax the coefficient sum never counts), so its ratio measures
19839 // that floor rather than any drift. Frames under 512 written bits
19840 // are left out of the under-price bound for that reason; the
19841 // over-price bound -- the defect direction, where the search pays
19842 // MORE than the writer -- still covers every frame.
19843 if written >= 512.0 {
19844 worst_under = worst_under.max(drift);
19845 }
19846 eprintln!(
19847 "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
19848 drift * 100.0
19849 );
19850 }
19851 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
19852 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
19853 // over-prices every frame but the last (its sum EXCLUDES the
19854 // partition/mode/skip/mv syntax the written side carries, so the true
19855 // coefficient over-price is larger still): the writer's CDFs adapt to
19856 // the content while the search's stay at the defaults. The bound is
19857 // set just above the worst measured point -- a widening drift is the
19858 // thing this gate exists to catch.
19859 assert!(
19860 worst_over <= 0.16,
19861 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
19862 worst_over * 100.0
19863 );
19864 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
19865 // the worst inter frame, where nearly every block now codes an MV
19866 // residual and a reference the coefficient sum never counts. Re-measured
19867 // at +29.6% once the encoder's grid published compound blocks properly
19868 // (compound share 8.8% -> 11.5%): a compound block carries a second
19869 // reference tree, a compound mode symbol and -- for the half-new modes
19870 // -- an MV residual, none of which the coefficient sum counts.
19871 // lane-av1txbits: pricing against the tables the frame's writer really
19872 // starts from collapses the over-price above to nothing, so the whole
19873 // remaining gap is the syntax the coefficient sum leaves out. That is
19874 // the default on a non-screen frame since lane-av1price2 (this
19875 // fixture is one), and it reads +32.6% here.
19876 // lane-av1obmc: every eligible single-reference inter block now also
19877 // carries a `motion_mode` symbol the coefficient sum never counts,
19878 // and an OBMC block carries the more expensive of the two values --
19879 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
19880 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
19881 // decisions, so this bound and the byte pins above FAIL BY DESIGN
19882 // under it; the default path (no motion_mode syntax at all) is the
19883 // one they are measured on.
19884 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
19885 // coding pyramid now, so the five frames are a key frame, a hidden
19886 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
19887 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
19888 // near-empty leaves below it. Both bounds stand where they were.
19889 // lane-av1rejudge: local warp is ON by default now, so every eligible
19890 // single-reference block carries that same `motion_mode` symbol (a
19891 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
19892 // +34.9% here, one point past the OBMC reading above. The bound moves
19893 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
19894 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
19895 // symbol and one or two magnitude symbols, none of which the
19896 // coefficient sum counts either -- +36.9% here against the same
19897 // fixture's +34.9% with `EC_AV1_CFL=0`.
19898 // ... and a directional block whose `angle_delta_y` is no longer
19899 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
19900 assert!(
19901 worst_under <= 0.40,
19902 "the writer spent {:.2}% more than the search priced -- more than \
19903 the mode/mv syntax outside the coefficient sum explains",
19904 worst_under * 100.0
19905 );
19906 }
19907
19908 /// The census behind step (1) of the pricer lane: for every transform
19909 /// block the writer really codes, what the search priced those levels at
19910 /// against what the writer spent on them, split by table set and non-zero
19911 /// count. One average hides the interesting part -- the classes the
19912 /// estimate is systematically wrong about (all-zero blocks, the
19913 /// one-coefficient blocks the inter search lives on) -- so the split is
19914 /// printed and only the total is asserted on.
19915 #[test]
19916 fn pricer_error_census_by_block_class() {
19917 let _knobs = crate::speed::knob_read();
19918 let fctx = &crate::decode::FrameCtx::for_encoder();
19919 let (width, height) = (256usize, 128usize);
19920 let pictures: Vec<Picture> = (0..5)
19921 .map(|i| panned_test_card(width, height, i * 2))
19922 .collect();
19923 crate::tile::pricer_census_on();
19924 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19925 let rows = crate::tile::take_pricer_census();
19926 assert!(!rows.is_empty(), "the census saw no transform block");
19927
19928 println!("| set | nz | blocks | priced bits | written bits | error |");
19929 println!("|---|---|---|---|---|---|");
19930 let (mut priced_all, mut written_all) = (0.0, 0.0);
19931 for ((set, bucket), (blocks, priced, written)) in &rows {
19932 priced_all += priced;
19933 written_all += written;
19934 println!(
19935 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
19936 crate::tile::census_bucket_label(*bucket),
19937 if *written > 0.0 {
19938 (priced - written) / written * 100.0
19939 } else {
19940 0.0
19941 }
19942 );
19943 }
19944 println!(
19945 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
19946 rows.values().map(|r| r.0).sum::<u64>(),
19947 (priced_all - written_all) / written_all * 100.0
19948 );
19949 assert!(written_all > 0.0);
19950 }
19951
19952 /// Step (2) of the pricer lane: the same census, but on the REAL clips
19953 /// the BD gate scores -- one film clip and the screen capture -- so the
19954 /// question the film/screen split raises can be answered from data. Real
19955 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
19956 /// the screen capture larger, and the census says why: on a screen
19957 /// capture the frame's own starting tables are the tables of a frame that
19958 /// coded PALETTE and long runs of zero blocks, so they are far from the
19959 /// tables the writer ends the frame with; the pricer error does not fall
19960 /// the way it does on film.
19961 ///
19962 /// Not a gate -- it prints. Run it once per mode:
19963 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
19964 /// --ignored pricer_error_census_on_clips --nocapture
19965 #[test]
19966 #[ignore = "reads the real library, needs ffmpeg"]
19967 fn pricer_error_census_on_clips() {
19968 let _knobs = crate::speed::knob_write();
19969 if !have_ffmpeg() {
19970 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
19971 return;
19972 }
19973 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first),
19974 // so this probe reads the same tree the preflight validates. Its
19975 // `assert!(!clips.is_empty())` below was already a hard failure, so no
19976 // skip shape changes here — only the root does.
19977 let fixtures = crate::library_fixture::root();
19978 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
19979 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
19980 if film.exists() {
19981 clips.push(("film 1080p".to_string(), film));
19982 }
19983 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
19984 && let Some(p) = manifest
19985 .lines()
19986 .skip(1)
19987 .filter_map(|l| l.split('\t').next())
19988 .find(|p| {
19989 p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
19990 })
19991 {
19992 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
19993 }
19994 assert!(!clips.is_empty(), "no source clip available");
19995 let (width, height, frames) = (640usize, 384usize, 6usize);
19996 for (name, path) in &clips {
19997 let fctx = &crate::decode::FrameCtx::for_encoder();
19998 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
19999 SCREEN_FRAMES.iter().for_each(|c| {
20000 c.store(0, std::sync::atomic::Ordering::Relaxed);
20001 });
20002 let _ = crate::tile::take_pricing_hits();
20003 crate::tile::pricer_census_on();
20004 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
20005 let rows = crate::tile::take_pricer_census();
20006 let (price_default, price_real) = crate::tile::take_pricing_hits();
20007 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20008 println!(
20009 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
20010 {screen_on}, pricer armings default={price_default} real={price_real}"
20011 );
20012 println!("| set | nz | blocks | priced bits | written bits | error |");
20013 println!("|---|---|---|---|---|---|");
20014 let (mut priced_all, mut written_all) = (0.0, 0.0);
20015 for ((set, bucket), (blocks, priced, written)) in &rows {
20016 priced_all += priced;
20017 written_all += written;
20018 println!(
20019 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
20020 crate::tile::census_bucket_label(*bucket),
20021 if *written > 0.0 {
20022 (priced - written) / written * 100.0
20023 } else {
20024 0.0
20025 }
20026 );
20027 }
20028 println!(
20029 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
20030 rows.values().map(|r| r.0).sum::<u64>(),
20031 (priced_all - written_all) / written_all * 100.0
20032 );
20033 assert!(
20034 written_all > 0.0,
20035 "{name}: the census saw no transform block"
20036 );
20037 }
20038 }
20039
20040 /// Low motion has to actually buy something: at least one inter frame of
20041 /// a panning sequence has to cost fewer bytes than the key frame that
20042 /// starts it, and the inter-block share it prints has to be non-zero --
20043 /// a search that never picks an inter mode would still pass a rate gate
20044 /// on a picture with no motion in it (the class this repo calls
20045 /// gate-blind-to-feature), so the share is printed even though it is not
20046 /// asserted on beyond being reachable at all.
20047 #[test]
20048 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
20049 let _knobs = crate::speed::knob_read();
20050 let fctx = &crate::decode::FrameCtx::for_encoder();
20051 let (width, height) = (256usize, 128usize);
20052 let pictures: Vec<Picture> = (0..5)
20053 .map(|i| panned_test_card(width, height, i * 2))
20054 .collect();
20055 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
20056
20057 let key_bytes = encoded.frames[0].stream.len();
20058 eprintln!("frame bytes inter share");
20059 for (i, frame) in encoded.frames.iter().enumerate() {
20060 eprintln!(
20061 "{i:5} {:5} {:11.2}",
20062 frame.stream.len(),
20063 frame.inter_block_share
20064 );
20065 }
20066 assert!(
20067 encoded.frames[1..]
20068 .iter()
20069 .any(|f| f.stream.len() < key_bytes),
20070 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
20071 );
20072 assert!(
20073 encoded.frames[1..]
20074 .iter()
20075 .any(|f| f.inter_block_share > 0.0),
20076 "no inter frame coded a single inter block -- the search never fired"
20077 );
20078 }
20079
20080 /// A manual perf probe, not a gate: prints where a key frame's and an
20081 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
20082 /// measures before it optimizes rather than guessing. Run with
20083 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
20084 #[test]
20085 #[ignore = "a perf probe, not a gate"]
20086 fn stage_timing_breakdown() {
20087 let _knobs = crate::speed::knob_read();
20088 let fctx = &crate::decode::FrameCtx::for_encoder();
20089 use std::time::Instant;
20090
20091 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
20092 let picture = test_card(width, height);
20093
20094 let t = Instant::now();
20095 let dc_only =
20096 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
20097 let dc_only_t = t.elapsed();
20098
20099 let t = Instant::now();
20100 let non_directional =
20101 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx)
20102 .unwrap();
20103 let non_directional_t = t.elapsed();
20104
20105 let t = Instant::now();
20106 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
20107 let all_modes_t = t.elapsed();
20108
20109 eprintln!(
20110 "\n=== key frame {width}x{height} ===\n\
20111 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
20112 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
20113 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
20114 dc_only.stream.len(),
20115 non_directional.stream.len(),
20116 all_modes.stream.len(),
20117 );
20118
20119 // One inter frame predicting off the key frame's own
20120 // reconstruction, the (256, 256)-padded surface encode_sequence
20121 // itself would hand encode_inter_frame.
20122 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
20123 let padded_pic = picture.padded_to(SUPERBLOCK);
20124 let t = Instant::now();
20125 let inter = encode_inter_frame(
20126 &padded_pic,
20127 &padded_ref,
20128 100,
20129 0.5,
20130 1,
20131 flat_order_hints(1, 0, false),
20132 (width, height),
20133 None,
20134 None,
20135 None,
20136 None,
20137 fctx,
20138 None,
20139 &[],
20140 )
20141 .unwrap();
20142 let inter_t = t.elapsed();
20143 eprintln!(
20144 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
20145 {:.2})",
20146 inter.stream.len(),
20147 inter.inter_block_share
20148 );
20149 }
20150
20151 // Isolated per-call cost of the trial pipeline's own stages, at both
20152 // transform sizes the search runs, averaged over enough calls to
20153 // rise above `Instant::now`'s own noise.
20154 for side in [16usize, 32] {
20155 const N: u32 = 20_000;
20156 let residual: Vec<i32> = (0..side * side)
20157 .map(|i| ((i * 37 % 61) as i32) - 30)
20158 .collect();
20159
20160 let t = Instant::now();
20161 let mut levels = Vec::new();
20162 for _ in 0..N {
20163 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
20164 }
20165 let forward_t = t.elapsed() / N;
20166
20167 let t = Instant::now();
20168 for _ in 0..N {
20169 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
20170 }
20171 let inverse_t = t.elapsed() / N;
20172
20173 let set = if side == 32 {
20174 crate::cdf_state::TxbSet::Luma32
20175 } else {
20176 crate::cdf_state::TxbSet::Luma16
20177 };
20178 let t = Instant::now();
20179 for _ in 0..N {
20180 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
20181 }
20182 let entropy_t = t.elapsed() / N;
20183
20184 let above = vec![128u8; side * 2];
20185 let left = vec![128u8; side * 2];
20186 let mut prediction = vec![0u8; side * side];
20187 let t = Instant::now();
20188 for _ in 0..N {
20189 intra_predict_u8(
20190 D45_PRED,
20191 0,
20192 Some(&above),
20193 Some(&left),
20194 Some(128),
20195 side,
20196 side,
20197 false,
20198 false,
20199 &mut prediction,
20200 fctx,
20201 );
20202 }
20203 let predict_t = t.elapsed() / N;
20204
20205 eprintln!(
20206 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
20207 predict (1 directional mode): {predict_t:>9.2?}\n\
20208 forward_and_quantize: {forward_t:>9.2?}\n\
20209 dequant_and_inverse: {inverse_t:>9.2?}\n\
20210 coeff_bits: {entropy_t:>9.2?}"
20211 );
20212 }
20213 }
20214
20215 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
20216 /// plus what is left over once buckets 0/2/3 are subtracted.
20217 ///
20218 /// lane-av1probes: the two search-shaped buckets OVERLAP and the old
20219 /// print denied it. Bucket 0 is not "the motion search": `stage_since(0,
20220 /// ..)` fires only after `find_best_new_mv` and the global-MV search
20221 /// (`encode.rs:11959`, `:12080`), so it is the NEWMV/GLOBAL sub-search
20222 /// alone. Bucket 1 is EVERY `crate::mc::predict` call, from the search's
20223 /// candidates *and* from a committed inter block's final prediction --
20224 /// and that final prediction runs OUTSIDE any bucket-0 region. So bucket 1
20225 /// is neither inside bucket 0 nor smaller than it, and a print that shows
20226 /// it as "motion search (of which interpolation ...)" necessarily shows
20227 /// a sub-number bigger than its parent. Measured: bucket 0 = 17.82 ms,
20228 /// bucket 1 = 148.63 ms.
20229 ///
20230 /// Which number is real: BOTH timers are right; only the old ARITHMETIC
20231 /// was wrong. Bucket 1 is now printed as its own top-level row, the
20232 /// overlap is stated, and the residual is labelled for what it is -- it
20233 /// absorbs the committed block's own interpolation, so it is not a pure
20234 /// "13-mode intra candidate loop" figure either.
20235 ///
20236 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
20237 #[test]
20238 #[ignore = "a perf probe, not a gate"]
20239 fn stage_timing_breakdown_inter() {
20240 let _knobs = crate::speed::knob_read();
20241 let fctx = &crate::decode::FrameCtx::for_encoder();
20242 use std::time::Instant;
20243
20244 let (width, height) = (1280usize, 720);
20245 let picture = test_card(width, height);
20246 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
20247 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
20248 let padded_pic = picture.padded_to(SUPERBLOCK);
20249
20250 stage_reset();
20251 let t = Instant::now();
20252 let inter = encode_inter_frame(
20253 &padded_pic,
20254 &padded_ref,
20255 100,
20256 0.5,
20257 1,
20258 flat_order_hints(1, 0, false),
20259 (width, height),
20260 None,
20261 None,
20262 None,
20263 None,
20264 fctx,
20265 None,
20266 &[],
20267 )
20268 .unwrap();
20269 let total_t = t.elapsed();
20270 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
20271 // Buckets 0 and 2 and 3 are disjoint and additive. Bucket 1 (every
20272 // `mc::predict` call) is NOT added: it overlaps bucket 0 wherever a
20273 // search candidate calls predict, and it also covers the committed
20274 // block's final prediction, which no other bucket times. Adding it
20275 // would double-count the overlap; leaving it out puts the committed
20276 // prediction (and the intra candidate loop, RD glue, and the symbol
20277 // lookups outside `coeff_bits`) into the residual, which is what the
20278 // residual has always been.
20279 let accounted = motion_search + transform_quant + entropy;
20280 let other = total_t.saturating_sub(accounted);
20281 let overlap = interpolation.saturating_sub(motion_search);
20282
20283 eprintln!(
20284 "\n=== inter frame {width}x{height}, one frame ===\n\
20285 total: {total_t:>9.2?} ({} bytes)\n\
20286 NEWMV/GLOBAL sub-search (bucket 0): {motion_search:>9.2?}\n\
20287 transform + quantize (bucket 2): {transform_quant:>9.2?}\n\
20288 coeff_bits, entropy pricing (bucket 3): {entropy:>9.2?}\n\
20289 buckets 0+2+3 accounted: {accounted:>9.2?}\n\
20290 \n\
20291 OVERLAPPING, not additive: every mc::predict call (bucket 1) {interpolation:>9.2?}\n\
20292 \x20 -- of which {overlap:>9.2?} is OUTSIDE bucket 0 (a committed\n\
20293 \x20 inter block's final prediction, which no bucket above times)\n\
20294 \x20 and the rest is the search candidates' interpolation, already\n\
20295 \x20 inside bucket 0. It is deliberately NOT added to the total.\n\
20296 \n\
20297 residual (13-mode intra candidate loop, the committed block's\n\
20298 \x20 interpolation above, NEARESTMV's own predict, RD glue): {other:>9.2?}",
20299 inter.stream.len(),
20300 );
20301 }
20302
20303 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
20304 /// frames (a dark/flat one, a detailed one, a normal film one) at two
20305 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
20306 /// None`, the baseline this same build produces without
20307 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
20308 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
20309 /// go in the lane report, which is where "ship as default" is decided --
20310 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
20311 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
20312 #[test]
20313 // The three clip paths are HARD-CODED ABSOLUTES under /home/user, not
20314 // env-driven: off this workstation every row prints `SKIP <label>: <path>
20315 // not present on this machine` and the run exits 0 with no numbers. It is
20316 // a local-run probe; there is no fleet-host configuration that makes it
20317 // measure anything.
20318 #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
20319 fn prune_k_quality_sweep() {
20320 let _knobs = crate::speed::knob_read();
20321 let fctx = &crate::decode::FrameCtx::for_encoder();
20322 if !have_ffmpeg() {
20323 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
20324 return;
20325 }
20326 let (width, height) = (640usize, 352usize);
20327 let frames: &[(&str, &str, &str)] = &[
20328 // (label, clip, seek) -- a near-black scene, a busy one, and an
20329 // ordinary film frame, each from a different real file.
20330 (
20331 "dark/flat",
20332 "/home/user/Videos/reela.mp4",
20333 "3",
20334 ),
20335 (
20336 "detailed",
20337 "/home/user/Downloads/reelb.mkv",
20338 "1200",
20339 ),
20340 (
20341 "film",
20342 "/home/user/Videos/Films/reelc.mkv",
20343 "600",
20344 ),
20345 ];
20346 for &(label, clip, skip) in frames {
20347 if !std::path::Path::new(clip).exists() {
20348 eprintln!("SKIP {label}: {clip} not present on this machine");
20349 continue;
20350 }
20351 let picture = clip_frame(clip, skip, width, height);
20352 for &q in &[60u8, 150] {
20353 // SAFETY (not literally unsafe, just process-global): this is
20354 // a single-threaded #[ignore] probe, run by hand, never
20355 // alongside other tests that read Search::top_k.
20356 set_test_top_k_override(None);
20357 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
20358 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
20359 eprint!(
20360 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
20361 baseline.stream.len(),
20362 baseline_psnr
20363 );
20364 for &k in &[3usize, 4, 6] {
20365 set_test_top_k_override(Some(k));
20366 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
20367 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
20368 eprint!(
20369 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
20370 pruned.stream.len(),
20371 pruned_psnr,
20372 pruned_psnr - baseline_psnr
20373 );
20374 }
20375 eprintln!();
20376 }
20377 }
20378 set_test_top_k_override(None);
20379 }
20380
20381 /// Two consecutive decoded frames from one clip, for an inter-frame
20382 /// sweep -- [`clip_frame`] alone only ever gives one.
20383 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
20384 let out = Command::new("ffmpeg")
20385 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
20386 .args(["-vf", &format!("scale={width}:{height}")])
20387 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
20388 .output()
20389 .expect("ffmpeg failed to run");
20390 assert!(
20391 out.status.success(),
20392 "ffmpeg: {}",
20393 String::from_utf8_lossy(&out.stderr)
20394 );
20395 let (luma, chroma) = (width * height, width * height / 4);
20396 let frame_len = luma + 2 * chroma;
20397 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
20398 std::array::from_fn(|i| {
20399 let bytes = &out.stdout[i * frame_len..][..frame_len];
20400 Picture {
20401 width,
20402 height,
20403 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
20404 u: bytes[luma..luma + chroma]
20405 .iter()
20406 .map(|&v| u16::from(v))
20407 .collect(),
20408 v: bytes[luma + chroma..]
20409 .iter()
20410 .map(|&v| u16::from(v))
20411 .collect(),
20412 }
20413 })
20414 }
20415
20416 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
20417 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
20418 /// then one inter frame off it (`search_inter_block`'s own intra
20419 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
20420 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
20421 /// padding step complicates the comparison. Prints bytes and luma PSNR
20422 /// for the inter frame alone, unpruned vs each `K`.
20423 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
20424 #[test]
20425 // Same hard-coded /home/user clip paths as `prune_k_quality_sweep`;
20426 // off this workstation it SKIPs all three rows and prints nothing.
20427 #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
20428 fn prune_k_quality_sweep_inter() {
20429 let _knobs = crate::speed::knob_read();
20430 let fctx = &crate::decode::FrameCtx::for_encoder();
20431 if !have_ffmpeg() {
20432 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
20433 return;
20434 }
20435 let (width, height) = (1280usize, 704usize);
20436 let frames: &[(&str, &str, &str)] = &[
20437 (
20438 "dark/flat",
20439 "/home/user/Videos/reela.mp4",
20440 "3",
20441 ),
20442 (
20443 "detailed",
20444 "/home/user/Downloads/reelb.mkv",
20445 "1200",
20446 ),
20447 (
20448 "film",
20449 "/home/user/Videos/Films/reelc.mkv",
20450 "600",
20451 ),
20452 ];
20453 for &(label, clip, skip) in frames {
20454 if !std::path::Path::new(clip).exists() {
20455 eprintln!("SKIP {label}: {clip} not present on this machine");
20456 continue;
20457 }
20458 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
20459 for &q in &[60u8, 150] {
20460 // SAFETY (not literally unsafe, just process-global): a
20461 // single-threaded #[ignore] probe, run by hand, never
20462 // alongside other tests that read Search::top_k.
20463 set_test_top_k_override_inter(None);
20464 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
20465 let baseline = encode_inter_frame(
20466 &inter_source,
20467 &key.reconstruction,
20468 q,
20469 0.5,
20470 1,
20471 flat_order_hints(1, 0, false),
20472 (width, height),
20473 None,
20474 None,
20475 None,
20476 None,
20477 fctx,
20478 None,
20479 &[],
20480 )
20481 .unwrap();
20482 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
20483 eprint!(
20484 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
20485 baseline.stream.len(),
20486 baseline_psnr
20487 );
20488 for &k in &[3usize, 4, 6] {
20489 set_test_top_k_override_inter(Some(k));
20490 let pruned = encode_inter_frame(
20491 &inter_source,
20492 &key.reconstruction,
20493 q,
20494 0.5,
20495 1,
20496 flat_order_hints(1, 0, false),
20497 (width, height),
20498 None,
20499 None,
20500 None,
20501 None,
20502 fctx,
20503 None,
20504 &[],
20505 )
20506 .unwrap();
20507 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
20508 eprint!(
20509 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
20510 pruned.stream.len(),
20511 pruned_psnr,
20512 pruned_psnr - baseline_psnr
20513 );
20514 }
20515 eprintln!();
20516 }
20517 }
20518 set_test_top_k_override_inter(None);
20519 }
20520
20521 /// `frames` consecutive pictures out of a real clip, scaled to a whole
20522 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
20523 /// to an arbitrary count for the fixture regression gate below.
20524 fn clip_frames(
20525 clip: &str,
20526 skip: &str,
20527 width: usize,
20528 height: usize,
20529 frames: usize,
20530 ) -> Vec<Picture> {
20531 clip_frames_vf(
20532 clip,
20533 skip,
20534 &format!("scale={width}:{height}"),
20535 width,
20536 height,
20537 frames,
20538 )
20539 }
20540
20541 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
20542 /// for a native-resolution CROP instead of a downscale (the downscale is
20543 /// what destroys a screen capture's exact repeats -- class
20544 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
20545 fn clip_frames_vf(
20546 clip: &str,
20547 skip: &str,
20548 vf: &str,
20549 width: usize,
20550 height: usize,
20551 frames: usize,
20552 ) -> Vec<Picture> {
20553 // ONE definition of the gate's loader recipe, shared with
20554 // `examples/enc_probe` so the instrument cannot arm a different source
20555 // than the gate it reports on (class `instrument disagrees with the
20556 // gate`; lane-probe).
20557 crate::probe::source(clip, skip, vf, width, height, frames)
20558 }
20559
20560 /// The standing regression gate on real content: 12 frames of a real
20561 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
20562 /// this crate's own input regardless of its own source codec), encoded
20563 /// as an AV1 GOP and checked against three numeric floors so a
20564 /// compatibility or quality regression fails the suite instead of
20565 /// waiting for a downstream repo's gate to catch it (as happened for a
20566 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
20567 /// refusal, both caught only that way).
20568 ///
20569 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
20570 /// that geometry is already covered elsewhere), chosen only so encode
20571 /// time and gate numbers are not muddied by an edge-block class this
20572 /// test is not about.
20573 ///
20574 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
20575 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
20576 /// below carry a margin off those measured numbers (PSNR floor =
20577 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
20578 #[test]
20579 fn real_clip_encodes_within_its_quality_and_size_budget() {
20580 let _knobs = crate::speed::knob_read();
20581 let fctx = &crate::decode::FrameCtx::for_encoder();
20582 if !have_ffmpeg() {
20583 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
20584 return;
20585 }
20586 // lane-av1clipprobe: the clip's absence was a bare `clip.exists()`
20587 // -> SKIP with no env escape, so this gate reported green on a tree
20588 // with no root `fixtures/`. The probe prints that one line (naming the
20589 // resolved path) and fails under the require envs.
20590 let Some(clip) = crate::library_fixture::require(
20591 "video/h264-1080p-23.976-8bit.mp4",
20592 "real_clip_encodes_within_its_quality_and_size_budget",
20593 ) else {
20594 return;
20595 };
20596 let (width, height, frame_count) = (640usize, 384usize, 12usize);
20597 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
20598 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
20599 assert_eq!(encoded.frames.len(), frame_count);
20600
20601 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
20602 // stream and hands back every frame -- a stream a downstream
20603 // decoder refuses is the exact class of regression this gate
20604 // exists for.
20605 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
20606 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
20607
20608 // Gate 2: quality vs the source did not silently collapse.
20609 let mean_psnr: f64 = decoded
20610 .iter()
20611 .zip(&source)
20612 .map(|(d, s)| psnr(&d.y, &s.y))
20613 .sum::<f64>()
20614 / frame_count as f64;
20615 assert!(
20616 mean_psnr >= 44.91,
20617 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
20618 );
20619
20620 // Gate 3: the stream did not silently bloat.
20621 assert!(
20622 encoded.stream.len() <= 80_340,
20623 "stream grew to {} bytes, over the 80340-byte ceiling",
20624 encoded.stream.len()
20625 );
20626 }
20627
20628 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
20629 /// straddle size: 640x384 is exact on both axes (32-aligned), so
20630 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
20631 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
20632 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
20633 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
20634 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
20635 /// card; this one is the real-clip gate, same three floors.
20636 ///
20637 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
20638 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
20639 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
20640 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
20641 #[test]
20642 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
20643 let _knobs = crate::speed::knob_read();
20644 let fctx = &crate::decode::FrameCtx::for_encoder();
20645 if !have_ffmpeg() {
20646 eprintln!(
20647 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
20648 no ffmpeg"
20649 );
20650 return;
20651 }
20652 // lane-av1clipprobe: see the sibling gate above -- the bare
20653 // `clip.exists()` -> SKIP had no env escape.
20654 let Some(clip) = crate::library_fixture::require(
20655 "video/h264-1080p-23.976-8bit.mp4",
20656 "real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size",
20657 ) else {
20658 return;
20659 };
20660 let (width, height, frame_count) = (704usize, 400usize, 8usize);
20661 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
20662 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
20663 assert_eq!(encoded.frames.len(), frame_count);
20664
20665 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
20666 // stream and hands back every frame.
20667 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
20668 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
20669
20670 // Gate 2: quality vs the source did not silently collapse.
20671 let mean_psnr: f64 = decoded
20672 .iter()
20673 .zip(&source)
20674 .map(|(d, s)| psnr(&d.y, &s.y))
20675 .sum::<f64>()
20676 / frame_count as f64;
20677 assert!(
20678 mean_psnr >= 44.98,
20679 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
20680 );
20681
20682 // Gate 3: the stream did not silently bloat.
20683 assert!(
20684 encoded.stream.len() <= 62_703,
20685 "stream grew to {} bytes, over the 62703-byte ceiling",
20686 encoded.stream.len()
20687 );
20688 }
20689
20690 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
20691 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
20692 /// facade -- timed end to end, so the edith export-time projection is a
20693 /// real number rather than a guess from the isolated key/inter numbers
20694 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
20695 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
20696 #[test]
20697 #[ignore = "a perf probe, not a gate"]
20698 fn sequence_bench_sanity() {
20699 let _knobs = crate::speed::knob_read();
20700 let fctx = &crate::decode::FrameCtx::for_encoder();
20701 use std::time::Instant;
20702 let (width, height) = (1280usize, 720usize);
20703 let pictures: Vec<Picture> = (0..24)
20704 .map(|i| panned_test_card(width, height, i * 3))
20705 .collect();
20706 let t = Instant::now();
20707 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
20708 let elapsed = t.elapsed();
20709 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
20710 eprintln!(
20711 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
20712 elapsed / 24
20713 );
20714 }
20715
20716 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
20717 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
20718 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
20719 /// -- --ignored --nocapture`.
20720 #[test]
20721 #[ignore = "a calibration probe, not a gate"]
20722 fn calibration_sweep_base_q_idx() {
20723 let _knobs = crate::speed::knob_read();
20724 let fctx = &crate::decode::FrameCtx::for_encoder();
20725 if !have_ffmpeg() {
20726 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
20727 return;
20728 }
20729 let (width, height, frames) = (640usize, 384usize, 12usize);
20730 for clip in [
20731 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
20732 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
20733 ] {
20734 // lane-av1clipprobe: the crate's one fixture root and its one
20735 // presence probe -- the bare `path.exists()` -> SKIP -> `continue`
20736 // had no env escape, and with every clip absent the sweep looped
20737 // zero times and passed.
20738 let Some(path) = crate::library_fixture::require(
20739 &format!("video/{clip}"),
20740 &format!("calibration_sweep_base_q_idx: {clip}"),
20741 ) else {
20742 continue;
20743 };
20744 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
20745 eprintln!("--- {clip} ---");
20746 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
20747 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
20748 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
20749 let mean_psnr: f64 = decoded
20750 .iter()
20751 .zip(&source)
20752 .map(|(d, s)| psnr(&d.y, &s.y))
20753 .sum::<f64>()
20754 / frames as f64;
20755 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
20756 eprintln!(
20757 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
20758 encoded.stream.len()
20759 );
20760 }
20761 }
20762 }
20763
20764 // -----------------------------------------------------------------------
20765 // The encoder's standing BD-rate baseline against libaom and rav1e.
20766 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
20767 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
20768 // agreeing with our encoder proves nothing about the bitstream.
20769 // -----------------------------------------------------------------------
20770
20771 /// All-plane PSNR of a decoded picture against its source, on the same
20772 /// 8-bit scale [`psnr`] uses.
20773 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
20774 let cat = |p: &Picture| {
20775 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
20776 v.extend_from_slice(&p.y);
20777 v.extend_from_slice(&p.u);
20778 v.extend_from_slice(&p.v);
20779 v
20780 };
20781 psnr(&cat(decoded), &cat(source))
20782 }
20783
20784 /// The pictures back as the planar 8-bit bytes an encoder reads.
20785 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
20786 let mut raw = Vec::new();
20787 for p in source {
20788 for plane in [&p.y, &p.u, &p.v] {
20789 raw.extend(plane.iter().map(|&s| s as u8));
20790 }
20791 }
20792 raw
20793 }
20794
20795 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
20796 /// through ffmpeg: one point per entry of `points`, each a quality flag
20797 /// set. Returns the ladder ordered by fidelity and the total encode wall
20798 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
20799 /// so both curves are measured by the same decoder.
20800 fn external_ladder(
20801 source: &[Picture],
20802 width: usize,
20803 height: usize,
20804 encoder: &str,
20805 points: &[Vec<String>],
20806 ) -> (Vec<(f64, f64)>, f64) {
20807 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
20808 let dir = std::env::temp_dir();
20809 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
20810 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
20811 let mut ladder = Vec::new();
20812 let mut wall = 0.0;
20813 for (i, params) in points.iter().enumerate() {
20814 let obu = dir.join(format!(
20815 "ec-av1-bd-{}-{encoder}-{i}.obu",
20816 std::process::id()
20817 ));
20818 let start = std::time::Instant::now();
20819 let out = Command::new("ffmpeg")
20820 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
20821 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
20822 .arg(&raw_path)
20823 .args(["-an", "-threads", "1"])
20824 .args(["-g", &source.len().to_string(), "-c:v", encoder])
20825 .args(params)
20826 .args(["-f", "obu"])
20827 .arg(&obu)
20828 .output()
20829 .expect("ffmpeg failed to run");
20830 wall += start.elapsed().as_secs_f64();
20831 assert!(
20832 out.status.success(),
20833 "{encoder} {params:?}: {}",
20834 String::from_utf8_lossy(&out.stderr)
20835 );
20836 let stream = std::fs::read(&obu).expect("reference stream");
20837 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
20838 // lane-dkey: every reference point must also decode through OUR
20839 // decoder, sample-exact against ffmpeg's decode of the same bytes.
20840 // A BD table computed off streams we cannot read is a table about
20841 // an encoder we cannot check; this is the assertion that would
20842 // have caught the `force_integer_mv` defect (its stream decoded to
20843 // 25 dB garbage while this gate stayed green) and the crf-5 key
20844 // frame desync. A failure names the encoder, the point's flags and
20845 // the first differing frame/plane/sample.
20846 // lane-dpm1: a failing reference point is COLLECTED, not panicked
20847 // on, so one run still prints the whole BD table and names every
20848 // bad point instead of stopping at the first. The collection is
20849 // asserted empty by [`assert_ladder_decodes`] at the end of each
20850 // gate.
20851 match crate::stream::decode_stream(&stream) {
20852 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
20853 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
20854 ours.len(),
20855 decoded.len(),
20856 )),
20857 Ok(ours) => {
20858 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
20859 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
20860 note_ladder_failure(format!(
20861 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
20862 decoder decoded {got}, ffmpeg {want}"
20863 ));
20864 break;
20865 }
20866 }
20867 }
20868 Err(e) => note_ladder_failure(format!(
20869 "{encoder} {params:?}: our decoder refused the stream ({e})"
20870 )),
20871 }
20872 let mean: f64 = decoded
20873 .iter()
20874 .zip(source)
20875 .map(|(d, s)| psnr_all(d, s))
20876 .sum::<f64>()
20877 / source.len() as f64;
20878 ladder.push((mean, (stream.len() as f64).log10()));
20879 let _ = std::fs::remove_file(&obu);
20880 }
20881 let _ = std::fs::remove_file(&raw_path);
20882 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
20883 (ladder, wall)
20884 }
20885
20886 /// Every reference ladder point that did not decode sample-exactly
20887 /// through our own decoder, collected across a whole gate run so the BD
20888 /// table still prints and EVERY bad point is named
20889 /// (`encoder params frame plane sample`) instead of only the first.
20890 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
20891
20892 fn note_ladder_failure(msg: String) {
20893 eprintln!("LADDER DECODE FAILURE: {msg}");
20894 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
20895 }
20896
20897 /// Fail the gate at its END on everything [`external_ladder`] collected.
20898 fn assert_ladder_decodes() {
20899 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
20900 assert!(
20901 failures.is_empty(),
20902 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
20903 failures.len(),
20904 failures.join("\n"),
20905 );
20906 }
20907
20908 /// First differing sample between two pictures, as
20909 /// `(plane, index, left, right)` -- so a gate failure names the plane and
20910 /// the sample instead of just "differs". A length difference counts as a
20911 /// mismatch of that plane at the first index past the shorter one.
20912 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
20913 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
20914 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
20915 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
20916 }
20917 if l.len() != r.len() {
20918 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
20919 }
20920 }
20921 None
20922 }
20923
20924 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
20925 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
20926 /// stream is decoded twice -- by ffmpeg and by our own
20927 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
20928 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
20929 /// in Y, U and V over every shown frame in display order. That is itself
20930 /// a gate: it proves the bitstream says what the encoder thinks, in the
20931 /// only two decoders that read it.
20932 fn our_ladder(
20933 name: &str,
20934 source: &[Picture],
20935 width: usize,
20936 height: usize,
20937 fctx: &crate::decode::FrameCtx,
20938 ) -> (Vec<(f64, f64)>, f64) {
20939 let mut ladder = Vec::new();
20940 let mut wall = 0.0;
20941 for &q in &[150u8, 120, 90, 60] {
20942 let start = std::time::Instant::now();
20943 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
20944 // the gate has to be able to re-sweep it. 0.5 is the shipped one
20945 // (`crate::encoder::DEADZONE`).
20946 let deadzone = std::env::var("EC_AV1_DEADZONE")
20947 .ok()
20948 .and_then(|v| v.parse().ok())
20949 .unwrap_or(0.5);
20950 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
20951 wall += start.elapsed().as_secs_f64();
20952 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
20953 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
20954 assert_eq!(
20955 ours.len(),
20956 source.len(),
20957 "{name} q={q}: our decoder's display-order frame count"
20958 );
20959 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
20960 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
20961 panic!(
20962 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
20963 {got}, the encoder reconstructed {want}"
20964 );
20965 }
20966 }
20967 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
20968 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
20969 panic!(
20970 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
20971 {got}, the encoder reconstructed {want}"
20972 );
20973 }
20974 }
20975 let per_frame: Vec<f64> = decoded
20976 .iter()
20977 .zip(source)
20978 .map(|(d, s)| psnr_all(d, s))
20979 .collect();
20980 // lane-txrd: does a tool's loss start at the FIRST inter frame
20981 // (a local mispricing) or grow down the GOP (propagation into
20982 // the reference chain)? One line per q point answers it.
20983 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
20984 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
20985 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
20986 // lane-txrd: per PLANE, because an all-plane mean hides a
20987 // collapse in one of them (class `metric blind to a plane`).
20988 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
20989 let v: Vec<String> = decoded
20990 .iter()
20991 .zip(source)
20992 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
20993 .collect();
20994 v.join(" ")
20995 };
20996 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
20997 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
20998 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
20999 }
21000 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
21001 ladder.push((mean, (encoded.stream.len() as f64).log10()));
21002 }
21003 // What this clip asked for and what the content gate left it coding
21004 // under: a screen clip requests a pyramid and codes flat, and that
21005 // difference is what keeps its row identical to the flat baseline
21006 // (class `gate-blind-to-feature`).
21007 eprintln!(
21008 "{name}: sequence, pyramid requested {:?} effective {:?}",
21009 crate::encoder::Pyramid::from_env(),
21010 last_sequence_pyramid(),
21011 );
21012 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
21013 (ladder, wall)
21014 }
21015
21016 /// [`our_ladder`] through the streaming facade — the surface the editor's
21017 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
21018 /// each stream is also reordered (hidden `ALTREF` first,
21019 /// `show_existing_frame` last per group) and each level is coded at its
21020 /// own quantizer offset; without one it is the flat ladder, which
21021 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
21022 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
21023 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
21024 /// the whole ladder how many frames and how many bytes it spent, and the
21025 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
21026 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
21027 /// flat path, so a requested pyramid can come back `None` here.
21028 fn our_ladder_facade(
21029 name: &str,
21030 source: &[Picture],
21031 width: usize,
21032 height: usize,
21033 pyramid: Option<crate::encoder::Pyramid>,
21034 ) -> (
21035 Vec<(f64, f64)>,
21036 f64,
21037 [usize; 4],
21038 [usize; 4],
21039 Option<crate::encoder::Pyramid>,
21040 ) {
21041 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
21042 let slot = |l: Level| match l {
21043 Level::Key => 0,
21044 Level::Arf => 1,
21045 Level::Leaf => 2,
21046 Level::ShowExisting => 3,
21047 };
21048 let mut ladder = Vec::new();
21049 let mut wall = 0.0;
21050 let mut effective = None;
21051 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
21052 for &q in &[150u8, 120, 90, 60] {
21053 let config = EncoderConfig {
21054 width,
21055 height,
21056 base_q_idx: q,
21057 gop: source.len(),
21058 colour: Colour::Unspecified,
21059 tile_cols_log2: 0,
21060 tile_rows_log2: 0,
21061 };
21062 let start = std::time::Instant::now();
21063 let mut enc = match pyramid {
21064 None => Av1Encoder::new(config).unwrap(),
21065 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
21066 };
21067 let mut packets = Vec::new();
21068 for picture in source {
21069 packets.extend(enc.encode_frames(picture).unwrap());
21070 }
21071 packets.extend(enc.flush().unwrap());
21072 wall += start.elapsed().as_secs_f64();
21073 effective = enc.pyramid();
21074 let mut stream = Vec::new();
21075 for p in &packets {
21076 counts[slot(p.level)] += 1;
21077 bytes[slot(p.level)] += p.data.len();
21078 stream.extend_from_slice(&p.data);
21079 }
21080 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
21081 // correct if the DISPLAY-order output still has one frame per
21082 // source picture, in the right order -- checked against our own
21083 // decoder as well as ffmpeg's, both below.
21084 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
21085 assert_eq!(
21086 ours.len(),
21087 source.len(),
21088 "{name} q={q}: our display-order count"
21089 );
21090 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
21091 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
21092 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
21093 panic!(
21094 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
21095 decoded {got}, our decoder decoded {want}"
21096 );
21097 }
21098 }
21099 let mean: f64 = decoded
21100 .iter()
21101 .zip(source)
21102 .map(|(d, s)| psnr_all(d, s))
21103 .sum::<f64>()
21104 / source.len() as f64;
21105 ladder.push((mean, (stream.len() as f64).log10()));
21106 }
21107 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
21108 (ladder, wall, counts, bytes, effective)
21109 }
21110
21111 /// Byte-exactness gate for encoder work that is meant to change only
21112 /// how long the encoder takes.
21113 ///
21114 /// The BD gate above measures quality, which a speed lane can move by a
21115 /// hair without failing anything; this pins the streams themselves.
21116 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
21117 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
21118 /// in the tile) and again on lane-av1mv's merge of it: an extra
21119 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
21120 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
21121 /// prices coefficients against the tables the frame's writer really
21122 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
21123 /// decision change the BD gate judges. Re-pinned again on
21124 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
21125 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
21126 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
21127 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
21128 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
21129 /// by default ([`warp_on`], a sequence/frame header bit and a new
21130 /// motion_mode symbol on eligible blocks) and
21131 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
21132 /// every inter frame's superblocks now code at their own lambda
21133 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
21134 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
21135 /// and the two var-tx depth searches ([`tx32_depth_search`],
21136 /// [`compound_var_tx`]) are on by default, all three re-judged on the
21137 /// native gate's real film rows.
21138 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
21139 /// every block whose chroma takes it codes a different mode symbol, two
21140 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
21141 /// restores the previous streams. Re-pinned again in the same lane once
21142 /// directional luma winners searched their `angle_delta_y`
21143 /// (`EC_AV1_ANGLE=0` restores that half).
21144 #[test]
21145 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
21146 // These are DEFAULT-PRESET pins: a speed preset switches search levers
21147 // off, so it legitimately moves every byte. Encode at speed 0 whatever
21148 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
21149 let _knobs = crate::speed::knob_write();
21150 let was = crate::speed::speed();
21151 crate::speed::set_speed(0);
21152 if !have_ffmpeg() {
21153 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
21154 return;
21155 }
21156 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
21157 // so a tree with no root `fixtures/` reported this gate green having
21158 // compared nothing at all.
21159 let Some(clip) = crate::library_fixture::require(
21160 "video/h264-1080p-23.976-8bit.mp4",
21161 "the_encoders_own_streams_are_byte_identical_to_their_pins",
21162 ) else {
21163 return;
21164 };
21165 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
21166 // FNV-1a over the stream: a witness that every coded bit is where it
21167 // was, which a byte count alone is not.
21168 let fnv = |b: &[u8]| {
21169 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
21170 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
21171 })
21172 };
21173 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
21174 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
21175 // of 4, its leaves at q+8 and a `show_existing_frame` header per
21176 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
21177 // four frames; four pictures is one short mini-GOP, which is the
21178 // shape that pays least (the ARF's own quality has no later group to
21179 // carry it), so this is not the BD gate's number.
21180 // Re-taken again on lane-av1cfl: the chroma search offers
21181 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
21182 // so every block taking either codes different syntax and different
21183 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
21184 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
21185 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
21186 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
21187 // so these four pictures code as one truncated group -- a hidden
21188 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
21189 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
21190 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
21191 // Re-taken on lane-fintra: the sequence header sets
21192 // `enable_filter_intra`, so every DC_PRED intra block of at most
21193 // 32x32 without a luma palette carries a `use_filter_intra` flag and
21194 // the blocks that take one code a filter-intra mode, a different
21195 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
21196 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
21197 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
21198 // (default pyramid `8:-32:16`, one truncated group of 8 with its
21199 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
21200 // root can code a REAL residual now (one TX_64X64 luma transform and
21201 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
21202 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
21203 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
21204 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
21205 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
21206 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
21207 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
21208 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
21209 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
21210 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
21211 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
21212 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
21213 // these four pictures -- offers every superblock a 64x64 intra root
21214 // now. `EC_AV1_I64=0` restores 8557 / 33345.
21215 // Re-taken on lane-pricer: the inter RD search prices a single
21216 // reference through the tree and the neighbour contexts the writer
21217 // really codes it with, so every inter picture's reference decisions
21218 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
21219 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
21220 // for `skip`/`is_inter` and for the whole compound reference tree, so
21221 // every inter block's cost -- and with it the skip and reference
21222 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
21223 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
21224 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
21225 // single and compound are priced against the same syntax -- 8311 ->
21226 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
21227 // Re-taken on lane-newmv: the motion search charges its own rate term
21228 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
21229 // and each subpel stage re-runs from its own winner
21230 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
21231 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
21232 // and 33014 -> 33090 at q=60.
21233 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
21234 // from libaom's objective tpl mapping, so every inter picture's
21235 // quantizer grid -- and every decision priced against it -- moved
21236 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
21237 // at the merge of both lanes.
21238 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
21239 // per-superblock `delta_qindex` at 1.5x the preset's strength
21240 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
21241 // grids -- and every decision priced against them -- moved:
21242 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
21243 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
21244 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
21245 // pixels -- and the leaves that predict from them -- moved:
21246 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
21247 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
21248 // the shipped stream did not move.
21249 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
21250 // picture is coded in 128x128 superblocks now, the inter ones
21251 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
21252 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
21253 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
21254 // by default, on top of the ARF temporal filter).
21255 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
21256 // candidates the 64 root already did ([`b128_compound`]), so every
21257 // inter frame that carries `reference_select` codes different blocks
21258 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
21259 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
21260 // Re-taken on lane-arftf: that filter's strength swept on the deciding
21261 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
21262 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
21263 // 33017 at q=60 (the same LENGTH, different bytes).
21264 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
21265 // lane-rlclamp onto the 128 compound default.
21266 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
21267 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
21268 // so every inter frame whose RD takes one codes a different partition
21269 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
21270 // quantizer the rect cut never wins its own comparison on this clip.
21271 // `EC_AV1_B128HV=0` restores 8290 exactly.
21272 let pins: [(u8, usize, u64); 2] = [
21273 (150, 8291, 0x1f00bb0eb099a27f),
21274 (60, 33227, 0x57ee6b1f8eacd881),
21275 ];
21276 let coded: Vec<(u8, usize, u64)> = pins
21277 .iter()
21278 .map(|&(q, _, _)| {
21279 let e = encode_sequence(&source, q, 0.5).unwrap();
21280 (q, e.stream.len(), fnv(&e.stream))
21281 })
21282 .collect();
21283 crate::speed::set_speed(was);
21284 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
21285 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
21286 }
21287 }
21288
21289 /// A ladder is only a ladder if both axes rise together.
21290 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
21291 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
21292 for w in ladder.windows(2) {
21293 assert!(
21294 w[1].0 > w[0].0 && w[1].1 > w[0].1,
21295 "{name}: not monotone, {ladder:?}"
21296 );
21297 }
21298 }
21299
21300 /// The sweep behind [`screen_content`]'s constants
21301 /// (`unswept-decision-constants`), on the SAME five clips
21302 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
21303 /// same native crop: for each colour bound N the share of 16x16 luma
21304 /// blocks with 2..=N distinct colours, and the share of those whose
21305 /// per-pixel variance also clears a floor V -- libaom's
21306 /// `av1_set_screen_content_options` counts the variance-cleared blocks
21307 /// too (its `counts_2`, which gates intrabc), and without that term a
21308 /// smooth dark film frame reads as screen content.
21309 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
21310 #[test]
21311 #[ignore = "reads the real library"]
21312 fn probe_screen_detect() {
21313 let _knobs = crate::speed::knob_read();
21314 if !have_ffmpeg() {
21315 eprintln!("SKIP probe_screen_detect: no ffmpeg");
21316 return;
21317 }
21318 let limits = [4usize, 8, 16, 32, 64, 128];
21319 let floors = [0u64, 4, 16, 64, 256];
21320 // The census of one clip at one size: mean share, over the frames, of
21321 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
21322 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
21323 let mut acc = [[0f64; 5]; 6];
21324 for picture in frames {
21325 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
21326 let mut hit = [[0usize; 5]; 6];
21327 let mut blocks = 0usize;
21328 for by in (0..ch).step_by(16) {
21329 for bx in (0..cw).step_by(16) {
21330 let mut seen = [false; 256];
21331 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
21332 for row in 0..16 {
21333 for col in 0..16 {
21334 let v = y[(by + row) * cw + bx + col];
21335 sum += u64::from(v);
21336 sq += u64::from(v) * u64::from(v);
21337 if !seen[usize::from(v)] {
21338 seen[usize::from(v)] = true;
21339 colors += 1;
21340 }
21341 }
21342 }
21343 let var = (sq - sum * sum / 256) / 256;
21344 blocks += 1;
21345 for (li, &limit) in limits.iter().enumerate() {
21346 if colors > 1 && colors <= limit {
21347 for (fi, &floor) in floors.iter().enumerate() {
21348 hit[li][fi] += usize::from(var > floor);
21349 }
21350 }
21351 }
21352 }
21353 }
21354 for li in 0..6 {
21355 for fi in 0..5 {
21356 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
21357 }
21358 }
21359 }
21360 let n = frames.len().max(1) as f64;
21361 eprintln!(
21362 "{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:",
21363 frames.len()
21364 );
21365 eprintln!(
21366 " N \\ V |{}",
21367 floors.iter().map(|f| format!("{f:>8}")).collect::<String>()
21368 );
21369 for (li, &limit) in limits.iter().enumerate() {
21370 eprintln!(
21371 " {limit:>5} |{}",
21372 (0..5)
21373 .map(|fi| format!("{:>7.1}%", acc[li][fi] / n))
21374 .collect::<String>()
21375 );
21376 }
21377 };
21378 for (name, path, seek) in native_gate_clips() {
21379 let Some((nw, nh)) = probe_dims(&path) else {
21380 eprintln!("SKIP {name}: ffprobe gave no size");
21381 continue;
21382 };
21383 let cw = nw.min(1920) / 128 * 128;
21384 let ch = nh.min(1024) / 128 * 128;
21385 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21386 let frames = clip_frames_vf(
21387 &path,
21388 &seek,
21389 &format!("crop={cw}:{ch}:{x}:{y0}"),
21390 cw,
21391 ch,
21392 12,
21393 );
21394 census(&name, &frames, cw, ch);
21395 // The 640x384 gate scales instead of cropping, and the scaling
21396 // changes the census (bars smooth out): the constants have to
21397 // separate at BOTH sizes.
21398 let small = clip_frames(&path, &seek, 640, 384, 12);
21399 census(&name, &small, 640, 384);
21400 }
21401 }
21402
21403 /// The detector against the WHOLE real library (class
21404 /// `unswept-decision-constants`, user rule "his data is the gate"):
21405 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
21406 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
21407 /// duration, four frames each, 8-bit 4:2:0, at native size or a
21408 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
21409 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
21410 /// Prints per file and offset the share of qualifying 16x16 blocks, the
21411 /// [`screen_content`] verdict and a content hint (mean luma, luma
21412 /// standard deviation, inter MAD), then sweeps the colour bound against
21413 /// the variance floor over the whole library: for each (N, V) the worst
21414 /// (highest) share among the camera/film rows against the best (lowest)
21415 /// among the screen-recording rows, so the rule with the widest gap can
21416 /// be read off. Rows carry the manifest index, codec and size only --
21417 /// no titles, no home paths.
21418 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
21419 #[test]
21420 #[ignore = "reads the real library"]
21421 fn probe_screen_library() {
21422 let _knobs = crate::speed::knob_read();
21423 if !have_ffmpeg() {
21424 eprintln!("SKIP probe_screen_library: no ffmpeg");
21425 return;
21426 }
21427 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
21428 let fixtures = crate::library_fixture::root();
21429 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
21430 else {
21431 eprintln!("SKIP probe_screen_library: no real-library manifest");
21432 return;
21433 };
21434 let limits = [4usize, 8, 16, 32, 64];
21435 let floors = [0u64, 4, 8, 16, 32, 64, 128];
21436 // Whatever ffmpeg gave us, without the exact-count assertion the
21437 // gate loaders make: a seek near the end of a clip returns fewer
21438 // frames, and that is a row to print, not a panic.
21439 let decode =
21440 |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
21441 let out = Command::new("ffmpeg")
21442 .args(["-v", "error", "-ss", seek, "-i", clip])
21443 .args(["-frames:v", &n.to_string()])
21444 .args(["-vf", vf])
21445 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
21446 .output();
21447 let Ok(out) = out else { return Vec::new() };
21448 if !out.status.success() {
21449 return Vec::new();
21450 }
21451 let (luma, chroma) = (w * h, w * h / 4);
21452 let frame_len = luma + 2 * chroma;
21453 (0..out.stdout.len() / frame_len)
21454 .map(|i| {
21455 let b = &out.stdout[i * frame_len..][..frame_len];
21456 Picture {
21457 width: w,
21458 height: h,
21459 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
21460 u: b[luma..luma + chroma]
21461 .iter()
21462 .map(|&v| u16::from(v))
21463 .collect(),
21464 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
21465 }
21466 })
21467 .collect()
21468 };
21469 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
21470 // variance > V, for every (N, V) of the sweep grid, over one frame.
21471 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
21472 let mut hit = [[0usize; 7]; 5];
21473 let mut blocks = 0usize;
21474 for by in (0..h).step_by(16) {
21475 for bx in (0..w).step_by(16) {
21476 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
21477 let mut seen = [false; 256];
21478 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
21479 for row in 0..bh {
21480 for col in 0..bw {
21481 let v = y[(by + row) * w + bx + col];
21482 sum += u64::from(v);
21483 sq += u64::from(v) * u64::from(v);
21484 if !seen[usize::from(v)] {
21485 seen[usize::from(v)] = true;
21486 colors += 1;
21487 }
21488 }
21489 }
21490 let n = (bh * bw) as u64;
21491 let var = (sq - sum * sum / n) / n;
21492 blocks += 1;
21493 for (li, &limit) in limits.iter().enumerate() {
21494 if colors > 1 && colors <= limit {
21495 for (fi, &floor) in floors.iter().enumerate() {
21496 hit[li][fi] += usize::from(var > floor);
21497 }
21498 }
21499 }
21500 }
21501 }
21502 let mut out = [[0f64; 7]; 5];
21503 for li in 0..5 {
21504 for fi in 0..7 {
21505 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
21506 }
21507 }
21508 out
21509 };
21510 // (index, label, path, duration, screen-by-its-own-content). The
21511 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
21512 // are desktop recordings; everything else in this library is camera
21513 // or film material.
21514 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
21515 for (label, file) in [
21516 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
21517 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
21518 ] {
21519 let path = fixtures.join("video").join(file);
21520 if path.exists() {
21521 rows.push((
21522 "fx".into(),
21523 label.into(),
21524 path.to_str().unwrap().into(),
21525 10.0,
21526 false,
21527 ));
21528 }
21529 }
21530 for (i, line) in manifest.lines().skip(1).enumerate() {
21531 let f: Vec<&str> = line.split('\t').collect();
21532 if f.len() < 10 {
21533 continue;
21534 }
21535 let (path, codec) = (f[0], f[2]);
21536 if codec == "-" || codec.is_empty() {
21537 continue;
21538 }
21539 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
21540 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
21541 continue;
21542 };
21543 if !std::path::Path::new(path).exists() {
21544 eprintln!("SKIP {}: file is gone", i + 1);
21545 continue;
21546 }
21547 let name = path.rsplit('/').next().unwrap_or(path);
21548 let is_capture = path.contains("/OBS/")
21549 || (name.len() > 19
21550 && name.as_bytes()[4] == b'-'
21551 && name.as_bytes()[7] == b'-'
21552 && name.as_bytes()[10] == b' '
21553 && name.as_bytes()[13] == b'-');
21554 rows.push((
21555 format!("{}", i + 1),
21556 format!("{codec} {w}x{h}"),
21557 path.to_string(),
21558 f[8].parse::<f64>().unwrap_or(0.0),
21559 is_capture,
21560 ));
21561 }
21562 // Per (N, V): the worst camera/film row and the best screen row, so
21563 // the separation of the whole library is one subtraction.
21564 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
21565 eprintln!(
21566 "| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |"
21567 );
21568 for (idx, label, path, dur, is_capture) in &rows {
21569 let Some((nw, nh)) = probe_dims(path) else {
21570 eprintln!("SKIP {idx}: ffprobe gave no size");
21571 continue;
21572 };
21573 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
21574 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21575 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
21576 let mut file_grid = [[0f64; 7]; 5];
21577 let mut file_frames = 0usize;
21578 for pct in [10u32, 50, 90] {
21579 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
21580 let frames = decode(path, &seek, &vf, cw, ch, 4);
21581 if frames.is_empty() {
21582 eprintln!(
21583 "| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |",
21584 if *is_capture { "screen" } else { "camera" }
21585 );
21586 continue;
21587 }
21588 let (mut share, mut yes, mut mean, mut sd, mut mad) =
21589 (0f64, 0usize, 0f64, 0f64, 0f64);
21590 let mut prev: Option<Vec<u8>> = None;
21591 for picture in &frames {
21592 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
21593 let grid = census(&y, cw, ch);
21594 for li in 0..5 {
21595 for fi in 0..7 {
21596 file_grid[li][fi] += grid[li][fi];
21597 }
21598 }
21599 file_frames += 1;
21600 // The shipped rule is (16 colours, var > 16): grid row 2,
21601 // floor 16 is column 3.
21602 share += grid[2][3];
21603 yes += usize::from(screen_content(&y, cw, cw, ch));
21604 let n = y.len() as f64;
21605 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
21606 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
21607 mean += sum / n;
21608 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
21609 if let Some(p) = &prev {
21610 mad += p
21611 .iter()
21612 .zip(&y)
21613 .map(|(&a, &b)| f64::from(a.abs_diff(b)))
21614 .sum::<f64>()
21615 / n;
21616 }
21617 prev = Some(y);
21618 }
21619 let f = frames.len() as f64;
21620 eprintln!(
21621 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
21622 if *is_capture { "screen" } else { "camera" },
21623 share / f,
21624 if yes * 2 > frames.len() {
21625 "SCREEN"
21626 } else {
21627 "camera"
21628 },
21629 frames.len(),
21630 mean / f,
21631 sd / f,
21632 mad / (f - 1.0).max(1.0),
21633 );
21634 }
21635 if file_frames == 0 {
21636 continue;
21637 }
21638 for li in 0..5 {
21639 for fi in 0..7 {
21640 let s = file_grid[li][fi] / file_frames as f64;
21641 match is_capture {
21642 true => scr_min[li][fi] = scr_min[li][fi].min(s),
21643 false => cam_max[li][fi] = cam_max[li][fi].max(s),
21644 }
21645 }
21646 }
21647 }
21648 eprintln!(
21649 "sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):"
21650 );
21651 eprintln!(
21652 " N \\ V |{}",
21653 floors
21654 .iter()
21655 .map(|f| format!("{:>18}", format!("V>{f}")))
21656 .collect::<String>()
21657 );
21658 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
21659 for (li, &limit) in limits.iter().enumerate() {
21660 let mut row = String::new();
21661 for fi in 0..7 {
21662 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
21663 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
21664 if s - c > best {
21665 best = s - c;
21666 best_rule = (limit, floors[fi]);
21667 }
21668 }
21669 eprintln!(" {limit:>5} |{row}");
21670 }
21671 // The threshold sits at the midpoint of the widest gap; the shipped
21672 // constant is its reciprocal in whole parts of the frame.
21673 let (li, fi) = (
21674 limits.iter().position(|&l| l == best_rule.0).unwrap(),
21675 floors.iter().position(|&f| f == best_rule.1).unwrap(),
21676 );
21677 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
21678 eprintln!(
21679 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
21680 best_rule.0,
21681 best_rule.1,
21682 best,
21683 cam_max[li][fi],
21684 scr_min[li][fi],
21685 mid,
21686 (100.0 / mid.max(0.1)).round() as usize,
21687 );
21688 }
21689
21690 /// The missing instrument: what this encoder costs against libaom and
21691 /// rav1e at matched fidelity, and how long it takes to get there.
21692 ///
21693 /// Recipe, identical on all three sides: 12 consecutive frames of each
21694 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
21695 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
21696 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
21697 /// it by default), 4:2:0 8-bit in and out. Reference points:
21698 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
21699 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
21700 /// tile_cols=1:tile_rows=1:threads=1`
21701 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
21702 /// ffmpeg-decoded frames of each encoder's own stream.
21703 ///
21704 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
21705 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
21706 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
21707 /// four encodes of that ladder together):
21708 ///
21709 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
21710 /// |---|---|---|---|---|
21711 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
21712 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
21713 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
21714 ///
21715 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
21716 /// the encoder takes -- every stream it writes is byte-identical, so the
21717 /// BD columns are this box's own re-run of the same recipe rather than a
21718 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
21719 /// rav1e). What moved is the wall of the four encodes:
21720 ///
21721 /// | clip | wall ours before | after | instructions:u before -> after |
21722 /// |---|---|---|---|
21723 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
21724 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
21725 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
21726 ///
21727 /// Three exact steps, none of which touches a coded bit: the coefficient
21728 /// rate pricer stopped rebuilding every CDF table per candidate
21729 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
21730 /// tile once per candidate (`decode::FilterReplay`), and the forward
21731 /// transform stopped transforming the all-zero residual that 70% of its
21732 /// calls carry.
21733 ///
21734 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
21735 ///
21736 /// | step | 1080p | 2160p | screen |
21737 /// |---|---|---|---|
21738 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
21739 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
21740 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
21741 ///
21742 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
21743 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
21744 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
21745 /// -- all three decided on the REAL film rows of
21746 /// [`bd_rate_screen_native`], which this downscaled recipe does not
21747 /// carry:
21748 ///
21749 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
21750 /// |---|---|---|---|
21751 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
21752 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
21753 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
21754 ///
21755 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
21756 /// DEFAULT of the sequence path this gate codes through -- the bars are
21757 /// non-screen so they take it, the capture is gated flat:
21758 ///
21759 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
21760 /// |---|---|---|---|---|
21761 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
21762 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
21763 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
21764 ///
21765 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
21766 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
21767 /// facade arm -- which is what "one mini-GOP driver, two entry points"
21768 /// means here. This downscaled recipe HATES the pyramid (as it hates
21769 /// every knob the real film rows of `bd_rate_screen_native` keep, which
21770 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
21771 /// above. The capture's row is the flat row to the byte in both runs --
21772 /// that equality IS the content gate.
21773 ///
21774 /// Loop restoration is NOT in yet: it is the one filter whose parameters
21775 /// are per restoration UNIT inside the tile payload, so it needs both
21776 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
21777 /// buffer to solve against -- neither of which this frame-header-level
21778 /// search reaches.
21779 ///
21780 /// The baseline it replaced, before an inter frame's blocks chose their
21781 /// own partition, was +501.4/+504.4/+440.9 against libaom and
21782 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
21783 ///
21784 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
21785 /// fidelity, while spending far more time than either (the partition
21786 /// search's own cost, uncut: see the two intra-pruning variants measured
21787 /// and rejected in the lane report). No
21788 /// threshold is asserted yet -- this run sets the baseline; the gate
21789 /// asserts four monotone points per ladder, and at EVERY ladder point of
21790 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
21791 /// `crate::stream::decode_stream` -- and asserts the encoder's
21792 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
21793 /// and V over every shown frame in display order. A failure names the
21794 /// clip, the q, the frame, the plane and the first differing sample.
21795 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
21796 /// which exposes no per-packet reconstruction, so that path asserts the
21797 /// two decoders against each other on all three planes.)
21798 ///
21799 /// Run:
21800 /// cargo test -p ec-av1 --release --lib -- --ignored \
21801 /// bd_rate_vs_libaom_and_rav1e --nocapture
21802 #[test]
21803 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
21804 fn bd_rate_vs_libaom_and_rav1e() {
21805 let _knobs = crate::speed::knob_write();
21806 if !have_ffmpeg() {
21807 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
21808 return;
21809 }
21810 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
21811 let fixtures = crate::library_fixture::root();
21812 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
21813 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
21814 // rows for real content (the real rows live in the native gate).
21815 for (label, name) in [
21816 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
21817 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
21818 ] {
21819 // lane-av1clipprobe: the one probe, so a missing clip is RED under
21820 // the require envs instead of a drop-with-no-escape.
21821 if let Some(path) = crate::library_fixture::require(
21822 &format!("video/{name}"),
21823 &format!("bd_rate_vs_libaom_and_rav1e: {label}"),
21824 ) {
21825 clips.push((label.to_string(), path));
21826 }
21827 }
21828 // Screen capture: the repo carries no screen-capture fixture, so take
21829 // the first OBS recording the real-library manifest names.
21830 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
21831 Ok(manifest) => {
21832 let screen = manifest
21833 .lines()
21834 .skip(1)
21835 .filter_map(|l| l.split('\t').next())
21836 .find(|p| {
21837 p.contains("/OBS/")
21838 && p.ends_with(".mkv")
21839 && std::path::Path::new(p).exists()
21840 });
21841 match screen {
21842 Some(p) => clips.push((
21843 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
21844 std::path::PathBuf::from(p),
21845 )),
21846 None => {
21847 eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
21848 }
21849 }
21850 }
21851 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
21852 }
21853 assert!(!clips.is_empty(), "no source clip available");
21854
21855 let (width, height, frames) = (640usize, 384usize, 12usize);
21856 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
21857 .iter()
21858 .map(|q| {
21859 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
21860 .map(String::from)
21861 .to_vec()
21862 })
21863 .collect();
21864 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
21865 .iter()
21866 .map(|q| {
21867 vec![
21868 "-rav1e-params".to_string(),
21869 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
21870 ]
21871 })
21872 .collect();
21873 println!(
21874 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
21875 );
21876 println!(
21877 "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"
21878 );
21879 println!("|---|---|---|---|---|");
21880 for (name, path) in &clips {
21881 let fctx = &crate::decode::FrameCtx::for_encoder();
21882 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
21883 let _ = take_partition_hits();
21884 let _ = crate::tile::take_palette_hits();
21885 SCREEN_FRAMES.iter().for_each(|c| {
21886 c.store(0, std::sync::atomic::Ordering::Relaxed);
21887 });
21888 let _ = take_uv_mode_hits();
21889 let _ = crate::tile::take_inter_mode_hits();
21890 let _ = crate::tile::take_drl_hits();
21891 let _ = crate::tile::take_ref_hits();
21892 let _ = crate::tile::take_compound_mode_hits();
21893 let _ = crate::tile::take_compound_pair_hits();
21894 let _ = crate::tile::take_compound_size_hits();
21895 let _ = crate::tile::take_compound_leaf_mode_hits();
21896 let _ = take_b64_root_hits();
21897 let _ = take_b64_residual_hits();
21898 let _ = take_b64_compound_hits();
21899 let _ = crate::motion::take_census();
21900 // The entry-surface arm: run the SAME ladder through the
21901 // streaming facade the editor's export calls, which must print
21902 // the same BD numbers as the sequence path -- byte for byte the
21903 // same stream now that both drive one mini-GOP driver
21904 // (lane-av1pyrdef).
21905 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
21906 let (ours, ours_wall) = match facade {
21907 false => our_ladder(name, &source, width, height, fctx),
21908 true => {
21909 let pyramid = crate::encoder::Pyramid::from_env();
21910 let (ladder, wall, counts, bytes, effective) =
21911 our_ladder_facade(name, &source, width, height, pyramid);
21912 eprintln!(
21913 "{name}: facade, pyramid requested {pyramid:?} effective \
21914 {effective:?} -- frames key {} arf {} leaf {} \
21915 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
21916 counts[0],
21917 counts[1],
21918 counts[2],
21919 counts[3],
21920 bytes[0],
21921 bytes[1],
21922 bytes[2],
21923 bytes[3],
21924 );
21925 (ladder, wall)
21926 }
21927 };
21928 // How often the inter split actually fired over this clip's four
21929 // encodes, against the whole 32x32 that was the only outcome
21930 // before (gate-blind-to-feature).
21931 let [whole32, split32, whole16, split16] = take_partition_hits();
21932 // Which inter modes actually fired over this clip's four encodes,
21933 // and at which DRL index -- a mode nobody picks is a mode the BD
21934 // number cannot be crediting (gate-blind-to-feature).
21935 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
21936 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
21937 let refs = crate::tile::take_ref_hits();
21938 let modes_total = (nearest + near + global + new).max(1);
21939 eprintln!(
21940 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
21941 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
21942 {drl0}/{drl1}/{drl2}/{drl3}",
21943 100.0 * nearest as f64 / modes_total as f64,
21944 100.0 * near as f64 / modes_total as f64,
21945 100.0 * global as f64 / modes_total as f64,
21946 100.0 * new as f64 / modes_total as f64,
21947 );
21948 // The compound census: what share of the coded inter blocks took
21949 // a compound reference at all, which compound mode they took, and
21950 // which pair (gate-blind-to-feature -- a compound mode nobody
21951 // picks cannot be what a BD number credits).
21952 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
21953 // superblocks were left whole at all, and how many of those coded
21954 // a residual or took a compound reference.
21955 let (roots, root_res, root_comp) = (
21956 take_b64_root_hits(),
21957 take_b64_residual_hits(),
21958 take_b64_compound_hits(),
21959 );
21960 eprintln!(
21961 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
21962 );
21963 let comp_modes = crate::tile::take_compound_mode_hits();
21964 let comp_pairs = crate::tile::take_compound_pair_hits();
21965 let comp_sizes = crate::tile::take_compound_size_hits();
21966 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
21967 let comp_total: usize = comp_modes.iter().sum();
21968 eprintln!(
21969 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
21970 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
21971 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
21972 modes_total + comp_total,
21973 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
21974 comp_modes[0],
21975 comp_modes[1],
21976 comp_modes[2],
21977 comp_modes[3],
21978 comp_modes[6],
21979 comp_modes[7],
21980 comp_pairs[3],
21981 comp_pairs[6],
21982 );
21983 eprintln!(
21984 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
21985 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
21986 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6], comp_leaf[7],
21987 );
21988 eprintln!(
21989 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
21990 comp_sizes[1], comp_sizes[2], comp_sizes[3],
21991 );
21992 // Where the wall-owning stage actually goes: how many candidate
21993 // evaluations (one `mc::predict` + SAD each) a search spends, how
21994 // many of them are subpel, and how often the winner is the seed
21995 // it started from -- the census the seeded search is judged by.
21996 let [
21997 calls,
21998 evals,
21999 subpel,
22000 rounds,
22001 near_pred,
22002 unmoved,
22003 widest,
22004 widest_moves,
22005 ] = crate::motion::take_census();
22006 let per = |n: u64| n as f64 / calls.max(1) as f64;
22007 eprintln!(
22008 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
22009 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
22010 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
22011 per(evals),
22012 100.0 * subpel as f64 / evals.max(1) as f64,
22013 per(rounds),
22014 100.0 * near_pred as f64 / calls.max(1) as f64,
22015 100.0 * unmoved as f64 / calls.max(1) as f64,
22016 );
22017 // lane-newmv, class `instrument at bound`: how often the winner
22018 // was walked to at the log stage's own WIDEST step -- a high
22019 // share means the search stops where its step lets it, not where
22020 // the content is.
22021 eprintln!(
22022 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
22023 100.0 * widest as f64 / calls.max(1) as f64,
22024 per(widest_moves),
22025 );
22026 eprintln!(
22027 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
22028 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
22029 );
22030 eprintln!(
22031 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
22032 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
22033 whole32 + split32,
22034 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
22035 whole16 + split16,
22036 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
22037 );
22038 // The deblocking level each of this clip's frames chose
22039 // (lane-av1filt): 0 everywhere would mean the filter never fires.
22040 let levels = crate::filter_search::take_chosen_levels();
22041 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
22042 let mean = |f: fn(&Chosen) -> u8| {
22043 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
22044 };
22045 eprintln!(
22046 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
22047 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
22048 levels.len(),
22049 mean(|l| l.0.0),
22050 mean(|l| l.0.1),
22051 mean(|l| l.1.0),
22052 mean(|l| l.1.1),
22053 mean(|l| l.2.0),
22054 mean(|l| l.2.1),
22055 );
22056 // How many strength presets each frame's CDEF list carried and
22057 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
22058 // everywhere would mean the per-unit choice never fires.
22059 let presets = crate::filter_search::take_cdef_presets();
22060 let mut by_bits = [0usize; 4];
22061 for (b, _) in &presets {
22062 by_bits[usize::from(*b)] += 1;
22063 }
22064 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
22065 let on_extra: usize = presets.iter().flat_map(|(_, c)| c.iter().skip(1)).sum();
22066 eprintln!(
22067 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
22068 on a non-default preset ({:.1}%)",
22069 by_bits[0],
22070 by_bits[1],
22071 by_bits[2],
22072 by_bits[3],
22073 on_extra,
22074 units,
22075 100.0 * on_extra as f64 / units.max(1) as f64
22076 );
22077 // How the 64x64 luma restoration units split between
22078 // RESTORE_NONE and Wiener (lane-av1lr).
22079 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
22080 eprintln!(
22081 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
22082 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
22083 );
22084 // Which chroma modes the search actually wins with, against the
22085 // unconditional DC_PRED that was the only outcome before
22086 // (gate-blind-to-feature).
22087 // Screen-content detection and the palette it turns on
22088 // (gate-blind-to-feature): how many frames set
22089 // `allow_screen_content_tools`, how many blocks took a palette,
22090 // and of what size. A film clip must print `screen frames on=0`.
22091 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
22092 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
22093 // Which tables the SEARCH priced against, per frame arming
22094 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
22095 // real starting ones. A film clip must show every inter arming on
22096 // the real side, a screen clip none of them.
22097 let (price_default, price_real) = crate::tile::take_pricing_hits();
22098 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
22099 let palette = crate::tile::take_palette_hits();
22100 eprintln!(
22101 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
22102 palette[0],
22103 (2..=8)
22104 .filter(|&n| palette[n] > 0)
22105 .map(|n| format!("{n}={}", palette[n]))
22106 .collect::<Vec<_>>()
22107 .join(" ")
22108 );
22109 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
22110 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
22111 // only ever fires at one magnitude is a search that never left
22112 // its first candidate (gate-blind-to-feature).
22113 // The luma angle-delta histogram (lane-av1cfl): how many
22114 // directional blocks won at each delta. All-zero would mean the
22115 // refinement never beat the base angle.
22116 let deltas = take_angle_delta_hits();
22117 if deltas.iter().sum::<usize>() > 0 {
22118 eprintln!(
22119 "{name}: angle_delta_y {}",
22120 deltas
22121 .iter()
22122 .enumerate()
22123 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
22124 .collect::<Vec<_>>()
22125 .join(" ")
22126 );
22127 }
22128 let alphas = take_cfl_alpha_hits();
22129 if alphas.iter().sum::<usize>() > 0 {
22130 eprintln!(
22131 "{name}: cfl |alpha| {}",
22132 alphas
22133 .iter()
22134 .enumerate()
22135 .filter(|&(_, &n)| n > 0)
22136 .map(|(a, &n)| format!("{a}={n}"))
22137 .collect::<Vec<_>>()
22138 .join(" ")
22139 );
22140 }
22141 let palette_uv = crate::tile::take_palette_uv_hits();
22142 eprintln!(
22143 "{name}: chroma palette blocks {} sizes {}",
22144 palette_uv[0],
22145 (2..=8)
22146 .filter(|&n| palette_uv[n] > 0)
22147 .map(|n| format!("{n}={}", palette_uv[n]))
22148 .collect::<Vec<_>>()
22149 .join(" ")
22150 );
22151 let uv = take_uv_mode_hits();
22152 let uv_total: usize = uv.iter().sum();
22153 eprintln!(
22154 "{name}: uv modes {}",
22155 uv.iter()
22156 .enumerate()
22157 .filter(|&(_, &n)| n > 0)
22158 .map(|(m, &n)| format!(
22159 "{}={n} ({:.1}%)",
22160 UV_MODE_NAMES[m],
22161 100.0 * n as f64 / uv_total.max(1) as f64
22162 ))
22163 .collect::<Vec<_>>()
22164 .join(" ")
22165 );
22166 // Which transform depth the intra blocks of this clip's key
22167 // frames resolved to (lane-av1tx): depth 0 is one transform over
22168 // the whole block, 1 and 2 its halvings.
22169 let depths = take_tx_depth_hits();
22170 let depth_total: usize = depths.iter().sum();
22171 eprintln!(
22172 "{name}: intra tx depths {}",
22173 depths
22174 .iter()
22175 .enumerate()
22176 .map(|(d, &n)| format!(
22177 "{d}={n} ({:.1}%)",
22178 100.0 * n as f64 / depth_total.max(1) as f64
22179 ))
22180 .collect::<Vec<_>>()
22181 .join(" ")
22182 );
22183 print_inter_tx_census(name);
22184 // lane-av1obmc: how many blocks actually CODED a motion_mode
22185 // symbol and which value they took, by footprint -- "OBMC is on"
22186 // as a measurement rather than a claim (class
22187 // `gate-blind-to-feature`).
22188 let mm = crate::tile::take_motion_mode_hits();
22189 eprintln!(
22190 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
22191 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
22192 eligible)",
22193 mm[0],
22194 mm[1],
22195 mm[2],
22196 mm[3],
22197 mm[4],
22198 mm[5],
22199 mm[6],
22200 mm[7],
22201 mm[8],
22202 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22203 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22204 mm.iter().sum::<usize>(),
22205 );
22206 let (aom, aom_wall) =
22207 external_ladder(&source, width, height, "libaom-av1", &aom_points);
22208 let (rav1e, rav1e_wall) =
22209 external_ladder(&source, width, height, "librav1e", &rav1e_points);
22210 assert_monotone(&format!("{name}: ours"), &ours);
22211 assert_monotone(&format!("{name}: libaom"), &aom);
22212 assert_monotone(&format!("{name}: rav1e"), &rav1e);
22213 let points = ours
22214 .iter()
22215 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22216 .collect::<Vec<_>>()
22217 .join(", ");
22218 println!(
22219 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
22220 bd_rate(&aom, &ours) * 100.0,
22221 bd_rate(&rav1e, &ours) * 100.0,
22222 );
22223 println!(
22224 "| references | libaom {} | rav1e {} | | |",
22225 aom.iter()
22226 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22227 .collect::<Vec<_>>()
22228 .join(", "),
22229 rav1e
22230 .iter()
22231 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22232 .collect::<Vec<_>>()
22233 .join(", "),
22234 );
22235 }
22236 assert_ladder_decodes();
22237 }
22238 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
22239 /// split by block class in lane-av1txdepth): depth 0 is one transform over
22240 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
22241 /// leaves and the 32x32 root, each single-reference or compound. A class
22242 /// with no counts at all never reached `commit_inter_luma` -- which is
22243 /// what its knob being off looks like (class `gate-blind-to-feature`).
22244 fn print_inter_tx_census(name: &str) {
22245 let splits = take_inter_tx_split_hits();
22246 let total: usize = splits.iter().sum();
22247 let row = |label: &str, base: usize| {
22248 let (n0, n1) = (splits[base], splits[base + 1]);
22249 format!(
22250 "{label} 0={n0} 1={n1} ({:.1}% split)",
22251 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
22252 )
22253 };
22254 eprintln!(
22255 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
22256 row("leaf single", 0),
22257 row("leaf compound", 2),
22258 row("32x32 single", 4),
22259 row("32x32 compound", 6),
22260 );
22261 // lane-txrd: which types the two searches actually COMMITTED over
22262 // this row's four encodes -- the gate could not say whether a type
22263 // search fired at all (class `gate-blind-to-feature`).
22264 const NAMES: [&str; 16] = [
22265 "IDTX",
22266 "DCT_DCT",
22267 "ADST_ADST",
22268 "ADST_DCT",
22269 "DCT_ADST",
22270 "V_DCT",
22271 "H_DCT",
22272 "FLIPADST_DCT",
22273 "DCT_FLIPADST",
22274 "FLIPADST_FLIPADST",
22275 "ADST_FLIPADST",
22276 "FLIPADST_ADST",
22277 "V_ADST",
22278 "H_ADST",
22279 "V_FLIPADST",
22280 "H_FLIPADST",
22281 ];
22282 let name_of = |t: usize| NAMES[t];
22283 for (label, hits) in [
22284 ("inter", take_inter_tx_type_hits()),
22285 ("intra", take_tx_type_hits()),
22286 ] {
22287 let total: usize = hits.iter().sum();
22288 let live: Vec<String> = hits
22289 .iter()
22290 .enumerate()
22291 .filter(|&(_, &n)| n > 0)
22292 .map(|(t, &n)| {
22293 format!(
22294 "{}={n} ({:.1}%)",
22295 name_of(t),
22296 100.0 * n as f64 / total.max(1) as f64
22297 )
22298 })
22299 .collect();
22300 eprintln!(
22301 "{name}: {label} tx_type of {total} units -- {}",
22302 live.join(" ")
22303 );
22304 }
22305 let t = take_txrd_stats();
22306 if t[0] > 0 {
22307 eprintln!(
22308 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
22309 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
22310 t[0],
22311 t[1],
22312 t[3] as f64 / 64.0,
22313 t[2],
22314 t[4] as f64 / 64.0,
22315 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
22316 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
22317 );
22318 eprintln!(
22319 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
22320 flat: dsse {:+.2}%, dbits {:+.2}%)",
22321 t[5],
22322 t[6] as f64 / 64.0,
22323 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
22324 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
22325 );
22326 }
22327 }
22328
22329 /// The video stream's coded size, from ffprobe.
22330 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
22331 crate::probe::dims(clip)
22332 }
22333
22334 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
22335 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
22336 /// superblock-aligned one, still centred and still even for 4:2:0.
22337 ///
22338 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
22339 /// superblocks by design, so no default gate row has a block the frame
22340 /// edge cuts through -- while every arbitrary export size does (3840x1608
22341 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
22342 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
22343 /// read on.
22344 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
22345 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
22346 let (w, h) = spec
22347 .split_once('x')
22348 .expect("EC_AV1_NATIVE_CROP is <width>x<height>");
22349 let (cw, ch): (usize, usize) = (
22350 w.parse().expect("crop width"),
22351 h.parse().expect("crop height"),
22352 );
22353 let (nw, nh) = crate::probe::dims(clip)?;
22354 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
22355 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
22356 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
22357 }
22358
22359 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
22360 /// with `probe_screen_detect` so the detector sweep measures exactly the
22361 /// clips the keep table is read off. Selector env vars as documented on
22362 /// the gate; a missing clip prints a SKIP and drops its row.
22363 fn native_gate_clips() -> Vec<(String, String, String)> {
22364 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
22365 let fixtures = crate::library_fixture::root();
22366 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
22367 let (film, film4k, screen) = (
22368 on("EC_AV1_NATIVE_FILM"),
22369 on("EC_AV1_NATIVE_FILM4K"),
22370 on("EC_AV1_NATIVE_SCREEN"),
22371 );
22372 // No selector at all means every clip; any selector means that subset.
22373 let all = !(film || film4k || screen);
22374 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
22375 // not film -- they print as "bars" so no reader takes them for real
22376 // content -- and the two rows below them are the real AV1 films.
22377 let mut clips: Vec<(String, String, String)> = Vec::new();
22378 for (want, label, file) in [
22379 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
22380 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
22381 ] {
22382 if !want {
22383 continue;
22384 }
22385 // lane-av1clipprobe: the one probe, so a missing clip is RED under
22386 // the require envs instead of a dropped row with no escape.
22387 if let Some(path) = crate::library_fixture::require(
22388 &format!("video/{file}"),
22389 &format!("the native BD-rate gate: {label}"),
22390 ) {
22391 clips.push((
22392 label.to_string(),
22393 path.to_str().unwrap().to_string(),
22394 "0".into(),
22395 ));
22396 }
22397 }
22398 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
22399 // The real films, taken out of the real-library manifest by codec and
22400 // coded width so no title and no home path lives in this file. Each
22401 // seek is PINNED (class `seeded fixture not reproducible`) at a
22402 // moving, non-black window -- a black leader would make every arm
22403 // read +0.000 (class `flat sample window`). Both sources are 10-bit
22404 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
22405 // what all three encoders see, so the comparison stays
22406 // encoder-vs-encoder.
22407 let pick = |width: &str| -> Option<String> {
22408 let m = manifest.as_ref().ok()?;
22409 m.lines()
22410 .skip(1)
22411 .map(|l| l.split('\t').collect::<Vec<_>>())
22412 .find(|f| {
22413 f.len() > 4
22414 && f[2] == "av1"
22415 && f[3] == width
22416 && std::path::Path::new(f[0]).exists()
22417 })
22418 .map(|f| f[0].to_string())
22419 };
22420 for (want, label, width, seek) in [
22421 (all || film, "film A (1080p source)", "1920", "00:35:00"),
22422 (
22423 all || film4k,
22424 "film B (2160p HDR source)",
22425 "3840",
22426 "00:40:00",
22427 ),
22428 ] {
22429 if !want {
22430 continue;
22431 }
22432 match pick(width) {
22433 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
22434 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
22435 }
22436 }
22437 if all || screen {
22438 match &manifest {
22439 Ok(manifest) => match manifest
22440 .lines()
22441 .skip(1)
22442 .filter_map(|l| l.split('\t').next())
22443 .find(|p| {
22444 p.contains("/OBS/")
22445 && p.ends_with(".mkv")
22446 && std::path::Path::new(p).exists()
22447 }) {
22448 Some(p) => clips.push((
22449 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
22450 p.to_string(),
22451 "0".into(),
22452 )),
22453 None => {
22454 eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
22455 }
22456 },
22457 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
22458 }
22459 }
22460 clips
22461 }
22462
22463 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
22464 /// downscales the OBS capture to 640x384, which destroys exactly the
22465 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
22466 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
22467 /// on that recipe is taken on content the tool cannot serve. This arm
22468 /// crops -- never scales -- a superblock-aligned window out of the middle
22469 /// of the capture at its own resolution (at most 1920x1024, so the wall
22470 /// stays in the minutes) and runs the same 12-frame, four-quantizer
22471 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
22472 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
22473 /// sample-exactness assertion `our_ladder` makes.
22474 ///
22475 /// It is its own `--ignored` test so the default gate's wall does not
22476 /// grow. Every variant is an environment knob, and each of those is a
22477 /// `OnceLock` read once per process, so a variant is a separate run:
22478 ///
22479 /// cargo test -p ec-av1 --release --lib -- --ignored \
22480 /// bd_rate_screen_native --nocapture # baseline
22481 /// EC_AV1_INTRABC=1 ... same command # intra block copy
22482 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
22483 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
22484 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
22485 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
22486 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
22487 ///
22488 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
22489 /// through (lane-av1pyrdef); the run prints the requested and the
22490 /// effective pyramid per clip, and a screen clip's effective one is
22491 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
22492 /// streaming facade instead, which prints the per-level frame and byte
22493 /// census and asserts ffmpeg's decode against our own decoder on all
22494 /// three planes in display order; both arms code the same bytes
22495 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
22496 ///
22497 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
22498 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
22499 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
22500 /// cost -- so every "film" column in the historical tables of this file
22501 /// is that generator, not film. The real content is `film A`, `film B`
22502 /// (native crops out of the two AV1 films the real-library manifest
22503 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
22504 /// decision only the bars rows support is not supported.
22505 ///
22506 /// Measured 2026-09-07, the five rows before and after the screen
22507 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
22508 /// BOTH real films were classified as screen content on 48/48 frames, so
22509 /// their coefficients were priced against the DEFAULT CDFs and the
22510 /// palette search ran over film; after, both are non-screen (0/48) and
22511 /// the capture is unchanged at 48/48:
22512 ///
22513 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
22514 /// |---|---|---|---|
22515 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
22516 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
22517 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
22518 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
22519 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
22520 ///
22521 /// Both bars rows and the capture are byte-identical across that change
22522 /// (their classification never moved); the palette search over film was
22523 /// costing roughly a tenth of the film rows' wall.
22524 ///
22525 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
22526 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
22527 /// the capture is gated flat and does not move a byte:
22528 ///
22529 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
22530 /// |---|---|---|---|---|
22531 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
22532 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
22533 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
22534 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
22535 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
22536 ///
22537 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
22538 /// which is the point of the shared driver: the two entry points code one
22539 /// stream. The bars rows are fixtures (recorded, never a decision); the
22540 /// two real films are what the pyramid ships for.
22541 ///
22542 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
22543 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
22544 /// setting any one of them keeps only the selected rows (the two 1080p
22545 /// rows, the two 2160p rows, the capture row respectively). A missing
22546 /// real film SKIPs its row; it never fails the gate.
22547 #[test]
22548 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
22549 fn bd_rate_screen_native() {
22550 let _knobs = crate::speed::knob_read();
22551 native_bd_arm("bd_rate_screen_native", 12, false);
22552 }
22553
22554 /// The LONG-GOP arm of the native BD gate: the same recipe as
22555 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
22556 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
22557 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
22558 /// reaches libaom as `--kf-max-dist=48` and rav1e as
22559 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
22560 /// inter pictures.
22561 ///
22562 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
22563 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
22564 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
22565 /// above 12 codes the same stream there -- the shipped `16` was measured
22566 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
22567 /// group (class `instrument at bound` / `gate blind to feature`). The
22568 /// user's exports are long GOPs, so the pyramid shape is decided here.
22569 ///
22570 /// cargo test -p ec-av1 --release --lib -- --ignored \
22571 /// bd_rate_film_long_gop --nocapture
22572 ///
22573 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
22574 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
22575 /// Read every row off the log's own "pyramid requested/effective" print,
22576 /// never off the argument order of the runs (lane-pyr3 misattributed
22577 /// three rows that way).
22578 ///
22579 /// Table: `lanes/pyr4.sweep.txt`.
22580 #[test]
22581 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
22582 fn bd_rate_film_long_gop() {
22583 let _knobs = crate::speed::knob_write();
22584 native_bd_arm("bd_rate_film_long_gop", 48, true);
22585 }
22586
22587 /// The shared driver of the two native BD arms above: `frames` pictures
22588 /// per row (the sequence's `gop` is the same number, so one key frame),
22589 /// four quantizers, `films_only` dropping every row but the two real
22590 /// films.
22591 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
22592 if !have_ffmpeg() {
22593 eprintln!("SKIP {label}: no ffmpeg");
22594 return;
22595 }
22596 let mut clips = native_gate_clips();
22597 if films_only {
22598 clips.retain(|(name, _, _)| name.starts_with("film "));
22599 }
22600 if clips.is_empty() {
22601 eprintln!("SKIP {label}: no clip");
22602 return;
22603 }
22604
22605 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
22606 .iter()
22607 .map(|q| {
22608 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
22609 .map(String::from)
22610 .to_vec()
22611 })
22612 .collect();
22613 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
22614 .iter()
22615 .map(|q| {
22616 vec![
22617 "-rav1e-params".to_string(),
22618 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
22619 ]
22620 })
22621 .collect();
22622 println!(
22623 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
22624 intrabc {}, palette maxcolors {}",
22625 armed_tiles(),
22626 crate::par::tile_threads(),
22627 intrabc_enabled(),
22628 palette_max_colors(),
22629 );
22630 println!(
22631 "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |"
22632 );
22633 println!("|---|---|---|---|---|");
22634 for (name, path, seek) in &clips {
22635 let fctx = &crate::decode::FrameCtx::for_encoder();
22636 if probe_dims(path).is_none() {
22637 eprintln!("SKIP {name}: ffprobe gave no size");
22638 continue;
22639 }
22640 // A whole number of 128-wide superblocks, at most 1920x1024, out
22641 // of the middle of the frame; the offsets stay even for 4:2:0.
22642 // ONE definition, shared with `examples/enc_probe` so the probe
22643 // cannot measure a different window than this gate (lane-probe).
22644 let (vf, cw, ch) = match native_crop_override(path) {
22645 Some(over) => over,
22646 None => crate::probe::gate_crop(path),
22647 };
22648 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
22649 SCREEN_FRAMES.iter().for_each(|c| {
22650 c.store(0, std::sync::atomic::Ordering::Relaxed);
22651 });
22652 let _ = crate::tile::take_palette_hits();
22653 let _ = crate::tile::take_palette_uv_hits();
22654 let _ = crate::tile::take_intrabc_hits();
22655 let _ = take_intrabc_search();
22656 let _ = crate::tile::take_filter_intra_hits();
22657 let _ = take_edge_census();
22658 // The sequence path itself codes the pyramid now
22659 // (lane-av1pyrdef), and prints what it requested and what the
22660 // content gate left effective.
22661 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
22662 // lane-sse: the blocks the true frame edge cuts through, and how
22663 // much of their RAW squared error sat in the padding the encoder
22664 // invented past it -- what the inside-only score stopped ranking
22665 // on. Empty on a superblock-aligned crop, which is every default
22666 // gate row (class `gate-blind-to-feature`).
22667 if edge_census() {
22668 for (side, n, inside, padding) in take_edge_census() {
22669 eprintln!(
22670 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
22671 padding_sse={padding} ({:.1}% of raw)",
22672 100.0 * padding as f64 / (inside + padding).max(1) as f64,
22673 );
22674 }
22675 }
22676 // gate-blind-to-feature: what the screen tools actually did at
22677 // native resolution, over this clip's four encodes.
22678 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
22679 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
22680 // Which tables the SEARCH priced against, per frame arming
22681 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
22682 // real starting ones. A film clip must show every inter arming on
22683 // the real side, a screen clip none of them.
22684 let (price_default, price_real) = crate::tile::take_pricing_hits();
22685 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
22686 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
22687 // superblocks stayed whole, and how many of those coded a
22688 // residual, split that residual's luma, or took a compound
22689 // reference (class `gate-blind-to-feature`).
22690 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
22691 // the superblocks offered the trial were coded whole.
22692 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
22693 eprintln!(
22694 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
22695 {i64_edge} on a superblock the frame edge cuts",
22696 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
22697 );
22698 eprintln!(
22699 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
22700 {} (search) / {} (writer); rect/AB pieces with a residual \
22701 {} (search) / {} (writer)",
22702 take_b128_none_hits(),
22703 crate::tile::take_sb128_none_hits(),
22704 take_b128_residual_hits(),
22705 crate::tile::take_sb128_residual_hits(),
22706 take_b128_rectres_hits(),
22707 crate::tile::take_sb128_rectres_hits(),
22708 );
22709 eprintln!(
22710 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
22711 take_b64_root_hits(),
22712 take_b64_residual_hits(),
22713 take_b64_var_tx_hits(),
22714 take_b64_compound_hits(),
22715 );
22716 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
22717 // of every priced block): what the deadzone quantiser handed the
22718 // RDOQ pass and what the pass changed, over every TRIAL block of
22719 // this row's four encodes -- not over the coded stream, so it is
22720 // the bits AT STAKE in the search, not in the bitstream.
22721 let rq = crate::tile::take_rdoq_stats();
22722 if rq[0] > 0 {
22723 eprintln!(
22724 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
22725 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
22726 rq[0],
22727 rq[1],
22728 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
22729 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
22730 rq[4],
22731 rq[5],
22732 rq[7] as f64 / 64.0,
22733 rq[6] as f64 / 64.0,
22734 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
22735 );
22736 }
22737 // lane-av1obmc2: the same motion_mode census the 640x384 gate
22738 // prints (class `gate-blind-to-feature`) -- how many blocks coded
22739 // the symbol at each footprint and how many took OBMC. Without it
22740 // the native table, which is the standing keep table, could not
22741 // say whether the tool fired at all.
22742 let mm = crate::tile::take_motion_mode_hits();
22743 eprintln!(
22744 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
22745 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
22746 eligible)",
22747 mm[0],
22748 mm[1],
22749 mm[2],
22750 mm[3],
22751 mm[4],
22752 mm[5],
22753 mm[6],
22754 mm[7],
22755 mm[8],
22756 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22757 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22758 mm.iter().sum::<usize>(),
22759 );
22760 print_inter_tx_census(name);
22761 // lane-last2 (class `gate-blind-to-feature`): which reference the
22762 // 32x32-and-below inter blocks of this clip's four encodes chose.
22763 // The native table is the standing keep table, so a second past
22764 // reference that never won a block has to be visible HERE and not
22765 // only in a synthetic witness.
22766 let rh = crate::encode::take_ref_frame_hits();
22767 let rtot: usize = rh.iter().sum();
22768 eprintln!(
22769 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
22770 (LAST2 {:.1}%)",
22771 rh[1],
22772 rh[2],
22773 rh[4],
22774 rh[7],
22775 rtot,
22776 100.0 * rh[2] as f64 / rtot.max(1) as f64,
22777 );
22778 let palette = crate::tile::take_palette_hits();
22779 let palette_uv = crate::tile::take_palette_uv_hits();
22780 let ibc = crate::tile::take_intrabc_hits();
22781 let search = take_intrabc_search();
22782 eprintln!(
22783 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
22784 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
22785 won {})",
22786 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
22787 palette[0],
22788 palette_uv[0],
22789 ibc[0],
22790 search[0],
22791 search[1],
22792 search[2],
22793 );
22794 // gate-blind-to-feature: how often the five recursive filter-intra
22795 // modes actually won a block over this clip's four encodes -- a
22796 // tool that never fires is not measured by the row above it.
22797 let fi = crate::tile::take_filter_intra_hits();
22798 eprintln!(
22799 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
22800 filter_intra_on(),
22801 fi[0],
22802 fi[1],
22803 fi[2],
22804 fi[3],
22805 fi[4],
22806 fi[5],
22807 );
22808 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
22809 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
22810 assert_monotone(&format!("{name}: ours"), &ours);
22811 assert_monotone(&format!("{name}: libaom"), &aom);
22812 assert_monotone(&format!("{name}: rav1e"), &rav1e);
22813 let points = ours
22814 .iter()
22815 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22816 .collect::<Vec<_>>()
22817 .join(", ");
22818 println!(
22819 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
22820 bd_rate(&aom, &ours) * 100.0,
22821 bd_rate(&rav1e, &ours) * 100.0,
22822 );
22823 // lane-pareto2: the two references at THEIR fast presets, plus
22824 // SVT-AV1, measured in the SAME arm as the row above -- the only
22825 // way the wall column of a Pareto table means anything (class:
22826 // wall tables are comparable only inside one interleaved batch).
22827 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
22828 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
22829 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
22830 [50, 100, 150, 200]
22831 .iter()
22832 .map(|q| {
22833 vec![
22834 "-rav1e-params".to_string(),
22835 format!(
22836 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
22837 ),
22838 ]
22839 })
22840 .collect()
22841 };
22842 let aom_at = |cu: u32| -> Vec<Vec<String>> {
22843 [5, 20, 35, 45]
22844 .iter()
22845 .map(|q| {
22846 vec![
22847 "-cpu-used".to_string(),
22848 cu.to_string(),
22849 "-b:v".to_string(),
22850 "0".to_string(),
22851 "-crf".to_string(),
22852 q.to_string(),
22853 ]
22854 })
22855 .collect()
22856 };
22857 let svt_at = |pr: u32| -> Vec<Vec<String>> {
22858 [20, 35, 45, 55]
22859 .iter()
22860 .map(|q| {
22861 vec![
22862 "-preset".to_string(),
22863 pr.to_string(),
22864 "-crf".to_string(),
22865 q.to_string(),
22866 "-svtav1-params".to_string(),
22867 "lp=1".to_string(),
22868 ]
22869 })
22870 .collect()
22871 };
22872 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
22873 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
22874 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
22875 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
22876 ];
22877 if have_encoder("libsvtav1") {
22878 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
22879 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
22880 } else {
22881 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
22882 }
22883 for (label, encoder, points) in arms {
22884 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
22885 // A REFERENCE stream our decoder cannot read is a note in
22886 // this table, not a gate failure: these rows exist to
22887 // price the references, and `assert_ladder_decodes` keeps
22888 // its teeth for the two ladders the keep table is read off.
22889 let notes =
22890 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
22891 if !notes.is_empty() {
22892 eprintln!(
22893 "{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)",
22894 notes.len()
22895 );
22896 }
22897 assert_monotone(&format!("{name}: {label}"), &lad);
22898 println!(
22899 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
22900 bd_rate(&aom, &lad) * 100.0,
22901 bd_rate(&rav1e, &lad) * 100.0,
22902 );
22903 }
22904 }
22905 }
22906 assert_ladder_decodes();
22907 }
22908
22909 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
22910 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
22911 /// on the two film clips at their native gate crop. The 2160p clip loses
22912 /// at every arm of the propagating map and the named suspect was that its
22913 /// heavily filtered flat cells give a tiny denominator, so the dependence
22914 /// ratio explodes exactly where coding is cheap; this prints the numbers
22915 /// that confirm or refute it.
22916 #[test]
22917 // Reads ONLY `fixtures/video/h264-{1080p,2160p}-23.976-8bit.mp4` -- the
22918 // COLOUR-BARS fixtures, in a centred crop. It never opens a film, so the
22919 // old reason ("the film fixtures") sent readers looking for content the
22920 // test cannot read. 0.9 s; prints the per-cell intra-MAD distribution.
22921 #[ignore = "0.9 s; reads only the fixtures/video COLOUR-BARS clips (not the films) and prints the per-cell intra-MAD distribution"]
22922 fn tpl_intra_denominator_histogram() {
22923 let _knobs = crate::speed::knob_read();
22924 if !have_ffmpeg() {
22925 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
22926 return;
22927 }
22928 for (label, file) in [
22929 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
22930 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
22931 ] {
22932 // lane-av1clipprobe: the one probe, so a missing clip is RED under
22933 // the require envs. With both clips absent this histogram used to
22934 // loop zero times and pass having printed nothing.
22935 let Some(path) = crate::library_fixture::require(
22936 &format!("video/{file}"),
22937 &format!("tpl_intra_denominator_histogram: {label}"),
22938 ) else {
22939 continue;
22940 };
22941 let path = path.to_str().unwrap();
22942 let Some((nw, nh)) = probe_dims(path) else {
22943 eprintln!("SKIP {label}: ffprobe gave no size");
22944 continue;
22945 };
22946 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
22947 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
22948 let source = clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
22949 let mut costs: Vec<f64> = Vec::new();
22950 for pic in &source {
22951 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
22952 costs.extend(
22953 super::tpl_intra_costs(&y8, cw, ch)
22954 .iter()
22955 .map(|&c| f64::from(c)),
22956 );
22957 }
22958 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
22959 let mut sorted = costs.clone();
22960 sorted.sort_by(f64::total_cmp);
22961 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
22962 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
22963 eprintln!(
22964 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
22965 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
22966 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
22967 below 1.0x {} ({:.1}%)",
22968 costs.len(),
22969 q(0.0),
22970 q(0.01),
22971 q(0.05),
22972 q(0.25),
22973 q(0.50),
22974 q(0.75),
22975 q(0.99),
22976 q(1.0),
22977 below(0.25),
22978 100.0 * below(0.25) as f64 / costs.len() as f64,
22979 below(0.5),
22980 100.0 * below(0.5) as f64 / costs.len() as f64,
22981 below(1.0),
22982 100.0 * below(1.0) as f64 / costs.len() as f64,
22983 );
22984 }
22985 }
22986
22987 /// The probe arms the gate's source (lane-probe, class `instrument
22988 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
22989 /// command line and had no `-ss`, so it read film B from frame 0 -- a
22990 /// black leader -- and coded 59 kB where the gate's own ladder point
22991 /// coded 89 kB of the same title; every census taken through it was
22992 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
22993 /// the shared loader honours the seek (arming the probe's way and the
22994 /// gate's way gives byte-identical streams, and dropping the seek does
22995 /// not), on a synthetic clip whose content moves over time.
22996 #[test]
22997 fn the_probe_arms_the_gates_source() {
22998 let _knobs = crate::speed::knob_write();
22999 if !have_ffmpeg() {
23000 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
23001 return;
23002 }
23003 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
23004 std::fs::create_dir_all(&dir).unwrap();
23005 let clip = dir.join("testsrc2.y4m");
23006 // 384x202: neither side is a multiple of 128, so the gate's centre
23007 // window is a real derivation and not the frame itself -- exactly the
23008 // shape film B has (3840x1608, never 3840x2160).
23009 let ok = Command::new("ffmpeg")
23010 .args([
23011 "-v",
23012 "error",
23013 "-y",
23014 "-f",
23015 "lavfi",
23016 "-i",
23017 "testsrc2=size=384x202:rate=10",
23018 ])
23019 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
23020 .arg(&clip)
23021 .status()
23022 .expect("ffmpeg failed to run")
23023 .success();
23024 assert!(ok, "ffmpeg could not write the synthetic clip");
23025 let path = clip.to_str().unwrap();
23026
23027 // The window: superblock-aligned, centred, even offsets.
23028 let (vf, w, h) = crate::probe::gate_crop(path);
23029 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
23030
23031 let (seek, q) = ("00:00:01", 150u8);
23032 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
23033 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
23034 assert!(
23035 gate.iter()
23036 .zip(&probe)
23037 .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
23038 "the probe's source differs from the gate's at the same window"
23039 );
23040 let bytes = |src: &[Picture]| {
23041 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
23042 .unwrap()
23043 .stream
23044 };
23045 assert_eq!(
23046 bytes(&gate),
23047 bytes(&probe),
23048 "probe and gate code different bytes"
23049 );
23050 // The two witnesses that both halves of the arming reach ffmpeg: the
23051 // seek, and the crop's own offset (the film-B defect in miniature --
23052 // the probe was reading `crop=..:568` of a 1608-high frame).
23053 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
23054 assert_ne!(
23055 bytes(&gate),
23056 bytes(&unseeked),
23057 "seeked and unseeked arming coded the same bytes -- the seek is inert"
23058 );
23059 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
23060 assert_ne!(
23061 bytes(&gate),
23062 bytes(&offset),
23063 "centred and top-aligned windows coded the same bytes -- the crop is inert"
23064 );
23065 std::fs::remove_dir_all(&dir).ok();
23066 }
23067
23068 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
23069 /// point inside the test binary, to compare against `examples/enc_probe`.
23070 #[test]
23071 // Panics on the first `env::var(...).unwrap()` when unset -- it needs FIVE
23072 // variables, not "a clip": `EC_PARITY_DIMS`, `EC_PARITY_FRAMES`,
23073 // `EC_PARITY_Q`, `EC_PARITY_CLIP`, `EC_PARITY_SS`, `EC_PARITY_VF`. Prints
23074 // one PARITY line (bytes + fnv1a of the stream) to diff against
23075 // `examples/enc_probe`.
23076 #[ignore = "diagnostic: needs EC_PARITY_{DIMS,FRAMES,Q,CLIP,SS,VF} -- all five, it unwraps the first missing one; prints one PARITY hash line"]
23077 fn probe_parity_point() {
23078 let _knobs = crate::speed::knob_write();
23079 let g = |k: &str| std::env::var(k).unwrap();
23080 let (w, h) = g("EC_PARITY_DIMS")
23081 .split_once(':')
23082 .map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap()))
23083 .unwrap();
23084 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
23085 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
23086 let source = clip_frames_vf(
23087 &g("EC_PARITY_CLIP"),
23088 &g("EC_PARITY_SS"),
23089 &g("EC_PARITY_VF"),
23090 w,
23091 h,
23092 frames,
23093 );
23094 let fctx = &crate::decode::FrameCtx::for_encoder();
23095 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
23096 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
23097 for &b in &e.stream {
23098 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
23099 }
23100 eprintln!(
23101 "PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
23102 e.stream.len(),
23103 crate::speed::speed(),
23104 crate::encoder::Pyramid::from_env(),
23105 last_sequence_pyramid()
23106 );
23107 }
23108 /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The
23109 /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`):
23110 /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in
23111 /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32
23112 /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags
23113 /// the census's far row measures were already banked by `arf_altref`.
23114 /// This census stays the PRICING arm (class `gate-blind-to-feature`): its
23115 /// best-of-two SAD shares are read against the fire share the gate census
23116 /// prints (`references ... LAST2 n (n%)`) and the refutation in
23117 /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the
23118 /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off
23119 /// `LAST`, the backward `ALTREF`, and the rate term price in.
23120 ///
23121 /// The measurement is on the gate's own window and loader (`gate_crop`,
23122 /// 12 pictures) of the two real films: every 16x16 luma block of every
23123 /// picture gets one full-pel diamond search against the NEAR reference
23124 /// and the same search against the FAR one, at the two lags the pyramid
23125 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
23126 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
23127 /// reference wins at all and by more than 10%, and -- the number the
23128 /// decision is taken on -- the total SAD of best-of-{near, far} against
23129 /// the total SAD of near alone, which is the prediction energy a second
23130 /// reference could remove before any rate is paid for naming it.
23131 ///
23132 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
23133 #[test]
23134 #[ignore = "reads the real films"]
23135 fn last2_census() {
23136 if !have_ffmpeg() {
23137 eprintln!("SKIP last2_census: no ffmpeg");
23138 return;
23139 }
23140 const SIDE: usize = 16;
23141 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
23142 // `None` when the displaced block leaves the picture.
23143 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
23144 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
23145 if sy < 0 || sx < 0 {
23146 return None;
23147 }
23148 let (sy, sx) = (sy as usize, sx as usize);
23149 if sy + SIDE > r.height || sx + SIDE > r.width {
23150 return None;
23151 }
23152 let mut acc = 0u64;
23153 for row in 0..SIDE {
23154 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
23155 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
23156 acc += c
23157 .iter()
23158 .zip(p)
23159 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
23160 .sum::<u64>();
23161 }
23162 Some(acc)
23163 };
23164 // A log-step diamond from the zero motion vector: the cheapest search
23165 // that still finds real pans. Both references get exactly this one,
23166 // so the comparison is search-fair.
23167 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
23168 let mut best = (
23169 sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX),
23170 (0isize, 0isize),
23171 );
23172 let mut step = 16isize;
23173 while step >= 1 {
23174 let centre = best.1;
23175 for (dy, dx) in [
23176 (-1, -1),
23177 (-1, 0),
23178 (-1, 1),
23179 (0, -1),
23180 (0, 1),
23181 (1, -1),
23182 (1, 0),
23183 (1, 1),
23184 ] {
23185 let mv = (centre.0 + dy * step, centre.1 + dx * step);
23186 if let Some(s) = sad(cur, r, bx, by, mv) {
23187 if s < best.0 {
23188 best = (s, mv);
23189 }
23190 }
23191 }
23192 step /= 2;
23193 }
23194 best.0
23195 };
23196 println!(
23197 "| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |"
23198 );
23199 println!("|---|---|---|---|---|---|---|---|");
23200 for (name, path, seek) in native_gate_clips() {
23201 if !name.starts_with("film ") {
23202 continue;
23203 }
23204 let (vf, cw, ch) = crate::probe::gate_crop(&path);
23205 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
23206 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
23207 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
23208 let (mut near_sad, mut best_sad) = (0u64, 0u64);
23209 for i in far..pictures.len() {
23210 let cur = &pictures[i];
23211 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
23212 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
23213 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
23214 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
23215 blocks += 1;
23216 wins += u64::from(f < n);
23217 big += u64::from(f as f64 * 1.1 < n as f64);
23218 near_sad += n;
23219 best_sad += n.min(f);
23220 }
23221 }
23222 }
23223 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
23224 println!(
23225 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
23226 pct(wins),
23227 pct(big),
23228 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
23229 );
23230 }
23231 }
23232 }
23233
23234 /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
23235 /// temporal filter of its SOURCE would take off it, priced before any
23236 /// encoder change (class `gate-blind-to-feature`).
23237 ///
23238 /// The stream census says our top ARF costs 6992 B a frame against
23239 /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
23240 /// quality, and that 61% of the gap is residual, not syntax. Two
23241 /// explanations are separable here without an encoder: our anchor
23242 /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
23243 /// the residual it codes at that lag is dominated by film grain, which no
23244 /// motion search can predict (source noise). So, per ARF position of the
23245 /// gate's own 48-picture window:
23246 ///
23247 /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
23248 /// * the same at lag 8 with the CURRENT picture temporally filtered --
23249 /// a libaom-shaped motion-compensated average of the +-2 display
23250 /// neighbours, weights `exp(-mse / strength)` -- which is the residual
23251 /// energy an ARF temporal filter would remove, and
23252 /// * PSNR of that filtered picture against the unfiltered one, the
23253 /// CEILING the filtered ARF's own PSNR is then measured under (the
23254 /// BD gate scores against the unfiltered source).
23255 ///
23256 /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
23257 /// --ignored arf_pred_census --nocapture
23258 #[test]
23259 #[ignore = "reads the real films"]
23260 fn arf_pred_census() {
23261 if !have_ffmpeg() {
23262 eprintln!("SKIP arf_pred_census: no ffmpeg");
23263 return;
23264 }
23265 const SIDE: usize = 16;
23266 let strength: f64 = std::env::var("EC_ARF_TF_S")
23267 .ok()
23268 .and_then(|v| v.parse().ok())
23269 .unwrap_or(30.0);
23270 let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
23271 // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
23272 // when the displaced block leaves the picture.
23273 let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
23274 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
23275 if sy < 0 || sx < 0 {
23276 return None;
23277 }
23278 let (sy, sx) = (sy as usize, sx as usize);
23279 if sy + SIDE > r.height || sx + SIDE > r.width {
23280 return None;
23281 }
23282 let mut acc = 0u64;
23283 for row in 0..SIDE {
23284 let c = &cur[row * cw..][..SIDE];
23285 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
23286 acc += c
23287 .iter()
23288 .zip(p)
23289 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
23290 .sum::<u64>();
23291 }
23292 Some((acc, (sy, sx)))
23293 };
23294 // The same log-step diamond `last2_census` uses, so the two censuses'
23295 // SADs are comparable.
23296 let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
23297 let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
23298 Some(v) => v,
23299 None => return (u64::MAX, (by, bx)),
23300 };
23301 let mut centre = (0isize, 0isize);
23302 let mut step = 16isize;
23303 while step >= 1 {
23304 let from = centre;
23305 for (dy, dx) in [
23306 (-1, -1),
23307 (-1, 0),
23308 (-1, 1),
23309 (0, -1),
23310 (0, 1),
23311 (1, -1),
23312 (1, 0),
23313 (1, 1),
23314 ] {
23315 let mv = (from.0 + dy * step, from.1 + dx * step);
23316 if let Some(s) = at(cur, cw, r, bx, by, mv) {
23317 if s.0 < best.0 {
23318 best = s;
23319 centre = mv;
23320 }
23321 }
23322 }
23323 step /= 2;
23324 }
23325 best
23326 };
23327 println!(
23328 "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
23329 );
23330 println!("|---|---|---|---|---|---|---|");
23331 for (name, path, seek) in native_gate_clips() {
23332 if !name.starts_with("film ") {
23333 continue;
23334 }
23335 let (vf, cw, ch) = crate::probe::gate_crop(&path);
23336 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
23337 let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
23338 let (mut tf_sse, mut tf_px) = (0f64, 0u64);
23339 for i in (8..pictures.len()).step_by(8) {
23340 arfs += 1;
23341 let cur = &pictures[i];
23342 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
23343 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
23344 let block: Vec<u16> = (0..SIDE)
23345 .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
23346 .collect();
23347 n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
23348 n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
23349 // The temporal filter: each +-2 display neighbour is
23350 // motion-compensated onto this block and averaged in
23351 // with libaom's shape, a weight that falls with the
23352 // match's own mean squared error.
23353 let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
23354 let mut wsum = 1.0f64;
23355 // `EC_ARF_TF_PAST=1` restricts the filter to the
23356 // DISPLAY-PAST neighbours -- the only ones the
23357 // encoder's own group buffer holds when it codes its
23358 // top ARF (the group's future is not buffered yet).
23359 let offs: &[isize] = match past {
23360 true => &[-2, -1],
23361 false => &[-2, -1, 1, 2],
23362 };
23363 for &d in offs {
23364 let j = i as isize + d;
23365 let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
23366 else {
23367 continue;
23368 };
23369 let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
23370 let mut sse = 0f64;
23371 for row in 0..SIDE {
23372 for col in 0..SIDE {
23373 let d = f64::from(

Showing the first 1 MiB of this file. View raw.