forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8ce79c1Tahinli2 months ago2682 commits

encode.rs16118 lines, 728.5 KiBHistoryRawDownload
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};
43use crate::transform::{
44 TxType, dequant_and_inverse_typed_wh, forward_and_quantize,
45 forward_and_quantize_scaled, forward_and_quantize_typed,
46 forward_and_quantize_typed_scaled,
47};
48
49/// The side of the larger of the two luma blocks this encoder codes, in
50/// samples.
51const BLOCK: usize = 32;
52
53/// The side of the smaller one, which a 32x32 block may be split into four of.
54const SUB: usize = 16;
55
56/// The side of a superblock, which is what the partition tree starts from.
57pub(crate) const SUPERBLOCK: usize = 64;
58
59// lane-sb128 r1: the superblock size in samples the intra-reach rules
60// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the
61// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and
62// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128
63// superblock changes every answer inside it (the tables themselves are
64// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
65// stays the encoder's own fixed 64.
66
67/// Sets the superblock size [`Reach`] answers against (64 or 128).
68pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
69 fctx.reach_sb_px.with(|c| c.set(px));
70}
71
72fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
73 fctx.reach_sb_px.with(|c| c.get())
74}
75
76/// How heavily the mode search weighs rate against squared error, in units of
77/// the quantizer's reconstruction step squared per bit.
78///
79/// Swept three times over his clips and three synthetic pictures
80/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
81/// the three lane reports). The first sweep, before the mode symbol was
82/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
83/// third sweep, after the levels were costed through the writer's own CDFs
84/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
85/// on film and -0.20% against -0.14% on screen capture.
86///
87/// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than
88/// those ladders, and 0.1 was far off the point: the rate term was carrying
89/// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom /
90/// vs rav1e for 1080p film, 2160p film, screen capture:
91///
92/// | lambda | 1080p | 2160p | screen |
93/// |--------|-------|-------|--------|
94/// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 |
95/// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 |
96/// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 |
97/// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
98/// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 |
99/// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 |
100/// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 |
101/// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 |
102/// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 |
103///
104/// and on the native 1920x1024 crops, which is the table that decides:
105///
106/// | lambda | film 1080p | film 2160p | screen |
107/// |--------|------------|------------|--------|
108/// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 |
109/// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 |
110/// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 |
111/// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 |
112///
113/// 0.0375 was the best point on two clips of three there and cost the "2160p
114/// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept
115/// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the
116/// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of
117/// whose cells have no intra cost -- no real film supported the point.
118///
119/// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL
120/// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs
121/// libaom / vs rav1e, everything else at the shipped defaults:
122///
123/// | lambda | bars 1080p | bars 2160p | film A | film B | screen |
124/// |--------|------------|------------|--------|--------|--------|
125/// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 |
126/// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 |
127/// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 |
128/// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 |
129/// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 |
130/// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 |
131///
132/// Real film wants roughly HALF the rate weight the bars asked for: the bowl
133/// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep
134/// against the shipped 0.05, while the bars rows walk the other way (they are
135/// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so
136/// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture
137/// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx
138/// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall.
139const LAMBDA_SCALE: f64 = 0.0275;
140
141/// The rate weight a HIDDEN frame (a pyramid ARF, coded but not shown) codes
142/// under, as a multiple of [`LAMBDA_SCALE`] (lane-arfcen).
143///
144/// The ARF-vs-ARF census says our top ARF codes residual over HALF its area
145/// (rav1e's, at the same display position, over 26-30%) and comes out 1.4-2.5x
146/// its bytes at the same PSNR, while every leaf that predicts from it is
147/// still 0.4 dB behind rav1e's -- i.e. the ARF's extra fidelity is bought at
148/// a rate weight fitted on shown frames and does not propagate. This is the
149/// one knob that prices a hidden frame's rate differently from its q, which
150/// the pyramid's q offsets cannot do (they move lambda and step together).
151const HIDDEN_LAMBDA_FACTOR: f64 = 1.0;
152
153/// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build.
154fn hidden_lambda_factor() -> f64 {
155 match std::env::var("EC_AV1_LAMBDA_HIDDEN").ok().and_then(|v| v.parse().ok()) {
156 Some(f) => f,
157 None => HIDDEN_LAMBDA_FACTOR,
158 }
159}
160
161/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
162/// picks it is the thing running. A release build has no such knob.
163fn lambda_scale() -> f64 {
164 let swept = std::env::var("EC_AV1_LAMBDA")
165 .ok()
166 .and_then(|v| v.parse::<f64>().ok());
167 match swept {
168 Some(scale) if cfg!(test) => scale,
169 _ => LAMBDA_SCALE,
170 }
171}
172
173/// How a key frame's lambda differs from an inter frame's: libaom weighs the
174/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
175/// of 128), because every later frame predicts from the key frame, so an error
176/// left in it is paid for over the whole group. This encoder has no temporal
177/// propagation model at all, and this factor is the cheapest stand-in for one.
178/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
179///
180/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
181/// libaom / vs rav1e:
182///
183/// | k_key | 1080p | 2160p | screen |
184/// |---|---|---|---|
185/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
186/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
187/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
188/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
189///
190/// The two films want the key frame coded finer and the screen capture wants
191/// the opposite, by about the same amount, and at native the whole lever is
192/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
193/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
194/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
195/// per-frame-type weight; the real lever here is temporal propagation
196/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
197/// predict from, not each frame.
198const KEY_LAMBDA_FACTOR: f64 = 1.0;
199
200/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
201fn key_lambda_factor() -> f64 {
202 match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) {
203 Some(k) if cfg!(test) => k,
204 _ => KEY_LAMBDA_FACTOR,
205 }
206}
207
208// Every frame's predicted coefficient bits since the last
209// `take_predicted_bits`, in coding order -- the encoder half of
210// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
211#[cfg(test)]
212thread_local! {
213 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
214}
215
216/// Records one frame's predicted coefficient bits.
217#[cfg(test)]
218fn record_predicted_bits(bits: f64) {
219 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
220}
221
222/// Takes (and clears) what the frames encoded on this thread were predicted to
223/// spend on coefficients.
224#[cfg(test)]
225pub(crate) fn take_predicted_bits() -> Vec<f64> {
226 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
227}
228
229/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
230pub(crate) const SPLIT_INTER_8: bool = true;
231
232/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
233/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
234/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
235/// turns it off for an A/B on one build.
236/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
237/// residual as one transform over the whole block or as the four transforms
238/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
239/// intra block inside the inter frame. ON since lane-av1tx2, which found why
240/// the streams desynced -- the writer counted the [`crate::decode::
241/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
242/// reader drops the term -- and measured the split search: BD-rate vs libaom
243/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
244/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
245/// A/B on one build.
246fn tx_select_inter() -> bool {
247 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
248 crate::envflags::var("EC_AV1_TX_SELECT_INTER")
249 .ok()
250 .map(|v| !matches!(v.as_str(), "0" | "off"))
251 });
252 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
253}
254
255fn tx_select() -> bool {
256 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
257 crate::envflags::var("EC_AV1_TX_SELECT")
258 .ok()
259 .map(|v| !matches!(v.as_str(), "0" | "off"))
260 });
261 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
262}
263
264fn split_inter_8() -> bool {
265 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
266 Some(v) if cfg!(test) => v != "0",
267 _ => crate::speed::at(&crate::speed::SPLIT_8),
268 }
269}
270
271/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
272/// NEARESTMV candidate it always had.
273pub(crate) const LEAF_NEW_MV: bool = true;
274
275/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
276/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
277/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
278/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
279pub(crate) const EXTRA_REF_NEW_MV: bool = true;
280
281/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
282/// own best vector before that reference's `NEWMV` search is skipped: a
283/// factor on the search cost scale, `1.0` meaning "as good or better".
284/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
285/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
286/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
287/// extra searches drop from +27% to +4% of the base count -- and on screen
288/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
289/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
290/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
291/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
292/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
293/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
294/// own noise. 0.35 stays; the lever that did move at the new rate weight is
295/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
296const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
297
298/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
299fn extra_new_skip_margin() -> f64 {
300 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
301 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
302 _ => EXTRA_NEW_SKIP_MARGIN,
303 }
304}
305
306/// The margin on a LEAF's SECOND-reference motion search, the same early-out
307/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
308/// `NEWMV`: the search is skipped when that reference's own
309/// `NEAREST_NEARESTMV` vector already prices this many times better than the
310/// leaf's `LAST` search found. `0.0` never skips.
311///
312/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
313/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
314/// 2160p (38195 with no second-reference search at all):
315/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
316/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
317/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
318/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
319/// of its extra searches; past it the calls double for another -0.3/-0.5.
320/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
321/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
322/// so the margin is pure wall on that content (+10% searches at 0.8).
323///
324/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
325/// the native gate with local warp on, BD vs libaom / vs rav1e:
326///
327/// | margin | film 1080p | film 2160p | screen |
328/// |---|---|---|---|
329/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
330/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
331/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
332/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
333/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
334///
335/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
336/// with screen flat -- and it beats never-skipping, i.e. the early-out is
337/// still worth having, just at a looser margin than the old rate weight
338/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
339/// 32.6s at 2160p), which is the price of the extra second-reference
340/// searches.
341const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
342
343/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
344/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
345fn leaf_second_new_margin() -> f64 {
346 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
347 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
348 None => LEAF_SECOND_NEW_MARGIN,
349 }
350}
351
352/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
353fn leaf_second_new_mv() -> bool {
354 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
355 Some(v) => v != "0",
356 None => crate::speed::at(&crate::speed::LEAF_SECOND),
357 }
358}
359
360/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
361/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
362/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
363/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
364/// was missing was the encoder ever forming one below 32x32.
365pub(crate) const LEAF_COMPOUND: bool = true;
366
367/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
368fn leaf_compound() -> bool {
369 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
370 Some(v) => v != "0",
371 None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
372 }
373}
374
375/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
376fn leaf_new_mv() -> bool {
377 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
378 Some(v) if cfg!(test) => v != "0",
379 _ => LEAF_NEW_MV,
380 }
381}
382
383/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
384/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
385/// the true frame edge cut through was ever split there; inside the frame
386/// every block was coded whole, which left the partition decision the key
387/// frame already makes unmade for eleven frames out of twelve.
388pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
389
390/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
391/// measurement that keeps it is running (test builds only, like
392/// [`lambda_scale`]).
393fn split_inter_blocks() -> bool {
394 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
395 Some(v) if cfg!(test) => v != "0",
396 _ => crate::speed::at(&crate::speed::SPLIT_INTER),
397 }
398}
399
400/// Whether the inter search offers the whole superblock as ONE 64x64 block
401/// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32
402/// quadrants it would otherwise always split into.
403///
404/// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6
405/// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of
406/// them skip at 328 bytes a frame -- while every block this encoder wrote was
407/// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669
408/// bits against rav1e's 61,988, about 46% of the film B gap.
409///
410/// lane-tx64: no longer skip-only. The root also prices a REAL residual --
411/// one TX_64X64 luma transform (`transform.rs`'s forward network has always
412/// reached 64 points; what was missing was the block coder and the writer
413/// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`],
414/// which carries that arm's own gate table. Still refused at the 64 root:
415/// compound references, a depth-1 4x32x32 var-tx tree, intra, and a
416/// superblock the true frame edge cuts through.
417///
418/// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the
419/// root and restores the skip-only shape lane-b64 shipped.
420pub(crate) const B64_ROOT: bool = true;
421
422/// How many superblocks took the 64x64 root since the last
423/// [`take_b64_root_hits`], so a gate reports how often it fires rather than
424/// assuming it does (class `gate-blind-to-feature`).
425static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
426
427/// The 64x64-root count since the last call, and zero it.
428pub fn take_b64_root_hits() -> usize {
429 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
430}
431
432/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
433/// Preset-gated: it re-prices the block once per candidate level, so it buys
434/// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
435///
436/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
437/// which is what the byte pins are taken under when they name it.
438fn rdoq_on() -> bool {
439 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
440 crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0")
441 });
442 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
443}
444
445/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in
446/// units of one squared AC quantiser step -- the search's own
447/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency.
448///
449/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`],
450/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock
451/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here:
452/// corner-cut, ceiling = a superblock the temporal map weighs away from the
453/// frame average has its coefficients optimised at the frame's weight. The
454/// upgrade is one `lambda` field on the trial call sites, which is the whole
455/// mode-search argument list.
456///
457/// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom
458/// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above
459/// the mode search's own weight, and it is the same multiplier on all three
460/// rows:
461///
462/// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen |
463/// |---|---|---|---|
464/// | 0.7 | +27.6 | +39.5 | +29.6 |
465/// | 1.0 | +26.3 | +37.5 | +29.1 |
466/// | 1.3 | +25.6 | +37.0 | +28.8 |
467/// | 1.6 | +24.6 | +35.9 | +28.7 |
468/// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 |
469/// | 3.2 | +24.7 | +36.1 | +29.4 |
470///
471/// A coefficient's rate is worth twice here what the mode search prices it
472/// at, and the likeliest reason is that the price is taken against tables
473/// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded
474/// late in a frame whose `txb_skip`/`base` tables have narrowed really costs
475/// less than the pricer says, and this pass is the one decision taken per
476/// COEFFICIENT, so it feels that error most. The honest fix is an adapted
477/// price, not a fitted multiplier; this is the fitted multiplier, and its
478/// bowl is measured rather than assumed.
479const RDOQ_LAMBDA_MULT: f64 = 2.2;
480
481/// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term
482/// calibration sweep).
483fn rdoq_lambda() -> f64 {
484 static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
485 crate::envflags::var("EC_AV1_RDOQ_LAMBDA")
486 .ok()
487 .and_then(|v| v.parse().ok())
488 .unwrap_or(RDOQ_LAMBDA_MULT)
489 });
490 lambda_scale() * *MULT
491}
492
493/// [`B64_ROOT`], or what `EC_AV1_B64` names.
494fn b64_root() -> bool {
495 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
496 crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0")
497 });
498 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
499}
500
501/// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched
502/// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64
503/// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner)
504/// and one TX_32X32 per chroma plane -- and compared against the four 32x32
505/// quadrants at the same lambda, exactly the shape the inter root
506/// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to
507/// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`);
508/// nothing produced one, so the key frame -- 21.6% of a real film stream --
509/// coded every superblock split while libaom and rav1e leave 45-54% of theirs
510/// whole.
511///
512/// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on
513/// it), no filter intra (`filter_intra_size_class` has no 64 row) and no
514/// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32
515/// level grid, so only depth 0 is representable) -- the root is refused
516/// outright on an `allow_intrabc` frame, whose quadrant searches carry DV
517/// state a discarded trial would desync.
518///
519/// Switched off by `EC_AV1_I64=0` in any build.
520pub(crate) const I64_ROOT: bool = true;
521
522/// How many key-frame superblocks were coded as one 64x64 intra block since
523/// the last [`take_i64_root_hits`], so a gate reports the fire rate rather
524/// than assuming it (class `gate-blind-to-feature`).
525/// Index 1 is how many were OFFERED the trial at all, so a gate reads a
526/// SHARE and not a bare count.
527static I64_HITS: [std::sync::atomic::AtomicUsize; 2] =
528 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
529
530/// The key-frame `(whole, offered)` 64x64-intra-root counts since the last
531/// call, and zero them.
532pub fn take_i64_root_hits() -> [usize; 2] {
533 std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
534}
535
536/// [`I64_ROOT`], or what `EC_AV1_I64` names.
537fn i64_root() -> bool {
538 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
539 crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0")
540 });
541 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
542}
543
544/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
545/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
546/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
547/// lane-b64 shipped, so the two can be measured against each other on the
548/// same build.
549///
550/// MEASURED on the native gate (two arms of one build, baseline reproduced to
551/// the tenth): both film rows improve on both columns -- film A
552/// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and
553/// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's
554/// +-0.3 screen clause. So the caller gates this off on a screen frame
555/// (`allow_screen_content_tools`), the same content gate the coding pyramid
556/// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm
557/// already codes them for nothing, and a residual there only spends bits the
558/// intra/palette tools would have spent better.
559///
560/// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` +
561/// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on:
562///
563/// | | skip-only | + residual |
564/// |---|---|---|
565/// | 64x64 share, all frames | 36.4% | 38.3% |
566/// | 64x64 share, leaf frames | 53.3% | 56.0% |
567/// | skip area, all frames | 80.4% | 78.8% |
568/// | skip area, leaf frames | 90.2% | 88.5% |
569/// | stream bytes | 34,366 | 34,295 |
570/// | encoder wall | 13.4s | 9.6s |
571///
572/// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the
573/// TX_64X64 coefficients are really being coded. The root wins MORE often
574/// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is
575/// 45.2%), which is also why the arm is 28% FASTER despite costing three more
576/// transforms per superblock: a root that wins is four quadrant searches that
577/// never run.
578fn b64_residual() -> bool {
579 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
580 crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0")
581 });
582 ENV.unwrap_or(true) && b64_root()
583}
584
585/// How many 64x64 roots came out cheaper with a residual than skipped, since
586/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
587/// rather than assuming one (class `gate-blind-to-feature`).
588static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
589
590/// The non-skip 64x64-root count since the last call, and zero it.
591pub fn take_b64_residual_hits() -> usize {
592 B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
593}
594
595/// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the
596/// `LAST` + extra-reference pairs the 32x32 level already offers, at the
597/// three modes a root can form without a second 64x64 motion search --
598/// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half
599/// is the vector `search_skip_64`'s own single-reference search already
600/// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own
601/// `NEWMV` vector, which only a second search per superblock produces -- the
602/// wall this root exists to save -- so they are not offered here.
603///
604/// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
605fn b64_compound() -> bool {
606 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
607 crate::envflags::var("EC_AV1_B64COMP").ok().map(|v| v != "0")
608 });
609 ENV.unwrap_or(true) && b64_root()
610}
611
612/// How many 64x64 roots took a COMPOUND candidate since the last
613/// [`take_b64_compound_hits`] (class `gate-blind-to-feature`).
614static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
615
616/// The compound 64x64-root count since the last call, and zero it.
617pub fn take_b64_compound_hits() -> usize {
618 B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
619}
620
621/// Whether a 64x64 root that codes a residual may SPLIT its luma transform
622/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by
623/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by
624/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because
625/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose
626/// residual has detail in the other three quadrants cannot code it at all.
627///
628/// Off by `EC_AV1_B64VARTX=0`.
629fn b64_var_tx() -> bool {
630 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
631 crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0")
632 });
633 ENV.unwrap_or(true) && b64_root()
634}
635
636/// How many 64x64 roots split their luma transform since the last
637/// [`take_b64_var_tx_hits`].
638static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
639
640/// The split-luma 64x64-root count since the last call, and zero it.
641pub fn take_b64_var_tx_hits() -> usize {
642 B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
643}
644
645/// Whether a superblock the true frame edge CUTS THROUGH may be left whole
646/// (lane-b64b). AV1 asks only that the block's own half is inside
647/// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already
648/// codes that case; what was missing was a trial whose SSE is scored over the
649/// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse)
650/// instead of over the padding the encoder
651/// invented past the edge. Both gate films are superblock-aligned, so this
652/// only reaches the user's own arbitrary export sizes.
653///
654/// Off by `EC_AV1_B64EDGE=0`.
655fn b64_edge() -> bool {
656 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
657 crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0")
658 });
659 ENV.unwrap_or(true) && b64_root()
660}
661
662/// How many 64x64 roots the frame edge cut through since the last
663/// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are
664/// superblock-aligned, so nothing but a synthetic size fires this).
665static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
666
667/// The edge 64x64-root count since the last call, and zero it.
668pub fn take_b64_edge_hits() -> usize {
669 B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
670}
671
672/// Whether the encoder searches loop restoration at all (spec 7.17): one
673/// Wiener filter per 64x64 luma restoration unit, picked from
674/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
675/// test build, like [`lambda_scale`].
676pub(crate) const RESTORATION: bool = true;
677
678/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
679fn restoration_enabled() -> bool {
680 match std::env::var("EC_AV1_LR").ok() {
681 Some(v) if cfg!(test) => v != "0",
682 _ => crate::speed::at(&crate::speed::RESTORATION),
683 }
684}
685
686/// libaom's `partition_search_breakout` shape: how many non-zero luma
687/// coefficients per 256 luma samples a block may code and still be judged
688/// well enough predicted that the split below it is not worth trying. `0`
689/// disables the breakout (only the existing all-skip prune applies), which
690/// is the default until the sweep below justifies otherwise.
691///
692/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
693/// is where this lane's wall would have gone: 1 cuts the three clips'
694/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
695/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
696/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
697/// encoder's inter quality lives, so `0` ships and the knob stays for a
698/// future explicit speed preset.
699pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
700
701/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
702/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
703/// out under `threshold * lambda` is not offered the split at all, and a
704/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
705/// always, as before this lever.
706///
707/// The census is what points here: the split trial runs on nearly every
708/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
709/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
710/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
711/// points, so the gate has to read the block's own RD cost, not its levels.
712///
713/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
714/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
715/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
716/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
717/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
718/// the largest threshold whose BD stays inside the +0.3 keep rule on every
719/// clip.
720/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
721/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
722/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
723/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
724/// the screen wall). Neither clears the keep rule; 0.125 stays.
725pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
726
727/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
728fn split_rd_threshold() -> f64 {
729 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
730 crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok())
731 });
732 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
733}
734
735/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
736/// [`split_rd_threshold`] withholds the split trial.
737fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
738 split_rd_breakout_at(split_rd_threshold(), cost, side, lambda)
739}
740
741/// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own
742/// early-out reads.
743fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool {
744 t > 0.0 && cost < t * lambda * (side * side) as f64
745}
746
747/// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`]
748/// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64).
749///
750/// The 32x32 level is allowed to loosen its breakout with the speed preset
751/// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured
752/// what that does one size up: at 0.5 a whole superblock is taken at 64x64
753/// without its four quadrants ever being searched, and film B goes
754/// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the
755/// same per-pixel threshold withholds four times as much search -- the
756/// preset's step is priced for the 32 level and does not carry up here.
757fn b64_breakout_threshold() -> f64 {
758 split_rd_threshold().min(SPLIT_RD_THRESHOLD)
759}
760
761/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
762/// build.
763fn split_breakout_coeffs() -> usize {
764 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
765 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
766 _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
767 }
768}
769
770/// How often each partition decision was taken since the last
771/// [`take_partition_hits`], so a gate can report how often a new partition
772/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
773/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
774/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
775static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
776 std::sync::atomic::AtomicUsize::new(0),
777 std::sync::atomic::AtomicUsize::new(0),
778 std::sync::atomic::AtomicUsize::new(0),
779 std::sync::atomic::AtomicUsize::new(0),
780];
781
782/// Records one such decision.
783fn partition_hit(which: usize) {
784 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
785}
786
787/// Takes (and clears) the counts.
788#[cfg(test)]
789pub(crate) fn take_partition_hits() -> [usize; 4] {
790 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
791}
792
793/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
794/// rate-distortion trials the block search actually runs, by kind, and where
795/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
796/// default, and a measurement build rather than a speed one -- the census
797/// runs the SAD pre-pass the unpruned search otherwise skips.
798pub fn census_on() -> bool {
799 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
800 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
801}
802
803/// What each [`CENSUS`] counter counts.
804pub const CENSUS_KINDS: [&str; 11] = [
805 "intra blocks searched (key frame + inter leaves)",
806 "intra luma mode trials",
807 "chroma searches",
808 "chroma mode trials (each = 2 plane trials)",
809 "tx-depth trials (transform units, depth >= 1)",
810 "inter 32x32 blocks searched",
811 "inter block intra-mode trials",
812 "inter mv candidates (each = 3 mc trials)",
813 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
814 " of those, intra won",
815 " of those, the NEARESTMV trial coded no residual",
816];
817
818/// The census counters themselves, indexed by [`CENSUS_KINDS`].
819static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
820 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
821
822/// Where the RD winner sat in the SAD ranking, for the luma intra search and
823/// the chroma mode search -- what says whether a top-N prune would have kept
824/// the block the search actually chose.
825static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
826 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
827static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
828 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
829
830fn census_add(kind: usize, n: usize) {
831 if census_on() {
832 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
833 }
834}
835
836/// Reads (and clears) the census, so a driver can attribute it to its own encode.
837pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
838 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
839 (
840 std::array::from_fn(|i| take(&CENSUS[i])),
841 std::array::from_fn(|i| take(&LUMA_RANK[i])),
842 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
843 )
844}
845
846/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
847/// first -- the census's one shared rule, so the luma and chroma histograms
848/// mean the same thing.
849fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
850 scored
851 .iter()
852 .filter(|&&(score, mode)| {
853 mode != winner
854 && score
855 < scored
856 .iter()
857 .find(|&&(_, m)| m == winner)
858 .map_or(f64::INFINITY, |&(s, _)| s)
859 })
860 .count()
861}
862
863/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
864/// four cost less. Set from the measurement in the lane report.
865const SPLIT_BLOCKS: bool = true;
866
867/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
868/// by calling [`encode_key_frame_inner`] both ways.
869pub(crate) fn split_blocks() -> bool {
870 SPLIT_BLOCKS
871}
872
873/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
874/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
875/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
876/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
877/// stream's decode output actually carries 10-bit precision instead of
878/// silently losing its low 2 bits). The encoder only ever produces values in
879/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
880/// decision); `Plane::source` narrows right back to `u8` at its two
881/// construction sites, a lossless round trip for that range.
882#[derive(Clone, Debug, PartialEq, Eq)]
883pub struct Picture {
884 /// The picture's width in luma samples.
885 pub width: usize,
886 /// Its height in luma samples.
887 pub height: usize,
888 /// The luma plane, `width * height` samples in raster order.
889 pub y: Vec<u16>,
890 /// The U plane, at half the width and half the height.
891 pub u: Vec<u16>,
892 /// The V plane, the same shape as U.
893 pub v: Vec<u16>,
894}
895
896impl Picture {
897 /// A mid-grey picture of the given size.
898 #[must_use]
899 pub fn grey(width: usize, height: usize) -> Self {
900 Self {
901 width,
902 height,
903 y: vec![128; width * height],
904 u: vec![128; width * height / 4],
905 v: vec![128; width * height / 4],
906 }
907 }
908
909 pub(crate) fn check(&self) -> Result<()> {
910 if self.width == 0
911 || !self.width.is_multiple_of(BLOCK)
912 || !self.height.is_multiple_of(BLOCK)
913 || !self.height.is_multiple_of(BLOCK)
914 {
915 return Err(Error::unsupported(
916 "AV1 encode",
917 "the picture must be a whole number of 32x32 blocks in each direction",
918 ));
919 }
920 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
921 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
922 return Err(Error::unsupported(
923 "AV1 encode",
924 "each plane must carry one sample per position at 4:2:0",
925 ));
926 }
927 Ok(())
928 }
929
930 /// What the public entry points require of the picture they are handed,
931 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
932 /// needs a whole chroma sample per two luma ones) and one sample per
933 /// position on each plane.
934 pub(crate) fn check_even(&self) -> Result<()> {
935 if self.width == 0
936 || self.height == 0
937 || !self.width.is_multiple_of(2)
938 || !self.height.is_multiple_of(2)
939 {
940 return Err(Error::unsupported(
941 "AV1 encode",
942 "the picture's width and height must each be even and nonzero",
943 ));
944 }
945 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
946 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
947 return Err(Error::unsupported(
948 "AV1 encode",
949 "each plane must carry one sample per position at 4:2:0",
950 ));
951 }
952 Ok(())
953 }
954
955 /// This picture, padded by edge replication to the next whole number of
956 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
957 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
958 /// sequence (what the inter tile writer's partition needs on top of
959 /// that). Identity (a plain clone, not a copy through the replication
960 /// loop) when the picture is already that size — the multiple-of-32 (or
961 /// -64) fast path is unchanged.
962 pub(crate) fn padded_to(&self, align: usize) -> Picture {
963 let padded_width = self.width.next_multiple_of(align);
964 let padded_height = self.height.next_multiple_of(align);
965 if padded_width == self.width && padded_height == self.height {
966 return self.clone();
967 }
968 Picture {
969 width: padded_width,
970 height: padded_height,
971 y: pad_plane(
972 &self.y,
973 self.width,
974 self.height,
975 padded_width,
976 padded_height,
977 ),
978 u: pad_plane(
979 &self.u,
980 self.width / 2,
981 self.height / 2,
982 padded_width / 2,
983 padded_height / 2,
984 ),
985 v: pad_plane(
986 &self.v,
987 self.width / 2,
988 self.height / 2,
989 padded_width / 2,
990 padded_height / 2,
991 ),
992 }
993 }
994}
995
996/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
997/// (8-bit only, unchanged this round -- widening the encoder is out of this
998/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
999/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
1000/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
1001/// content (every value fits both ways), so this changes no encoder output.
1002#[allow(clippy::too_many_arguments)]
1003fn intra_predict_u8(
1004 mode: u8,
1005 angle_delta: i32,
1006 above: Option<&[u8]>,
1007 left: Option<&[u8]>,
1008 corner: Option<u8>,
1009 bw: usize,
1010 bh: usize,
1011 enable_edge_filter: bool,
1012 smooth_neighbor: bool,
1013 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1014) {
1015 // Three heap allocations per call became three stack buffers: this runs
1016 // once per mode per trial, and an edge is at most `bw + bh` samples while
1017 // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's
1018 // 64x64 intra root predicts through here too, and reads up to `2 * bw`
1019 // samples above).
1020 let mut above_buf = [0u16; 2 * SUPERBLOCK];
1021 let mut left_buf = [0u16; 2 * SUPERBLOCK];
1022 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
1023 // trial of every block, and a 4x4 block writes 32 bytes of it. The
1024 // predictor fills every sample it is handed, so the zeros are dead
1025 // either way -- size the scratch to the block instead of to the largest
1026 // block there is.
1027
1028 let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| {
1029 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1030 *d = u16::from(v);
1031 }
1032 };
1033 if let Some(s) = above {
1034 widen(s, &mut above_buf);
1035 }
1036 if let Some(s) = left {
1037 widen(s, &mut left_buf);
1038 }
1039 let above16 = above.map(|s| &above_buf[..s.len()]);
1040 let left16 = left.map(|s| &left_buf[..s.len()]);
1041 let mut run = |dst16: &mut [u16]| {
1042 crate::intra::predict(
1043 mode,
1044 angle_delta,
1045 above16,
1046 left16,
1047 corner.map(u16::from),
1048 bw,
1049 bh,
1050 enable_edge_filter,
1051 smooth_neighbor,
1052 dst16, fctx,
1053 );
1054 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
1055 *d = s as u8;
1056 }
1057 };
1058 let n = bw * bh;
1059 if n <= 64 {
1060 run(&mut [0u16; 64][..n]);
1061 } else if n <= 256 {
1062 run(&mut [0u16; 256][..n]);
1063 } else if n <= BLOCK * BLOCK {
1064 run(&mut [0u16; BLOCK * BLOCK][..n]);
1065 } else {
1066 run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]);
1067 }
1068}
1069
1070/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
1071/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
1072/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
1073fn filter_intra_predict_u8(
1074 mode: usize,
1075 above: Option<&[u8]>,
1076 left: Option<&[u8]>,
1077 corner: Option<u8>,
1078 side: usize,
1079 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1080) {
1081 let mut above_buf = [0u16; 2 * BLOCK];
1082 let mut left_buf = [0u16; 2 * BLOCK];
1083 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
1084 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1085 *d = u16::from(v);
1086 }
1087 };
1088 if let Some(a) = above {
1089 widen(a, &mut above_buf);
1090 }
1091 if let Some(l) = left {
1092 widen(l, &mut left_buf);
1093 }
1094 let mut dst16 = [0u16; BLOCK * BLOCK];
1095 let n = side * side;
1096 crate::intra::predict_filter_intra(
1097 mode,
1098 above.map(|a| &above_buf[..a.len()]),
1099 left.map(|l| &left_buf[..l.len()]),
1100 corner.map(u16::from),
1101 side,
1102 side,
1103 &mut dst16[..n], fctx,
1104 );
1105 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
1106 *d = v as u8;
1107 }
1108}
1109
1110/// Pads one plane to `(padded_width, padded_height)` by repeating its last
1111/// row and column, so the block coder always sees a whole number of blocks.
1112/// [`crop_plane`] undoes this on the way back out.
1113fn pad_plane<T: Copy + Default>(
1114 source: &[T],
1115 width: usize,
1116 height: usize,
1117 padded_width: usize,
1118 padded_height: usize,
1119) -> Vec<T> {
1120 let mut out = vec![T::default(); padded_width * padded_height];
1121 for row in 0..padded_height {
1122 let src = source[row.min(height - 1) * width..][..width].as_ref();
1123 let dst = &mut out[row * padded_width..][..padded_width];
1124 dst[..width].copy_from_slice(src);
1125 dst[width..].fill(src[width - 1]);
1126 }
1127 out
1128}
1129
1130/// The top-left `width` x `height` region of a plane that is `padded_width`
1131/// wide, which is the render-size crop [`Picture::padded`]'s replication
1132/// exists to let a decoder undo.
1133fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
1134 let mut out = Vec::with_capacity(width * height);
1135 for row in 0..height {
1136 out.extend_from_slice(&source[row * padded_width..][..width]);
1137 }
1138 out
1139}
1140
1141/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
1142/// region a decoder produces, which is the public contract for what a caller
1143/// sees back — the padded planes the encoder coded against never leave this
1144/// module. Identity when the reconstruction is already that size.
1145pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1146 let reconstruction = &encoded.reconstruction;
1147 let cropped = if reconstruction.width == width && reconstruction.height == height {
1148 reconstruction.clone()
1149 } else {
1150 Picture {
1151 width,
1152 height,
1153 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1154 u: crop_plane(
1155 &reconstruction.u,
1156 reconstruction.width / 2,
1157 width / 2,
1158 height / 2,
1159 ),
1160 v: crop_plane(
1161 &reconstruction.v,
1162 reconstruction.width / 2,
1163 width / 2,
1164 height / 2,
1165 ),
1166 }
1167 };
1168 Encoded {
1169 stream: encoded.stream.clone(),
1170 modes: encoded.modes.clone(),
1171 inter_block_share: encoded.inter_block_share,
1172 reconstruction: cropped,
1173 tile: encoded.tile.clone(),
1174 mi_cols: encoded.mi_cols,
1175 mi_rows: encoded.mi_rows,
1176 base_q_idx: encoded.base_q_idx,
1177 tx_select: encoded.tx_select,
1178 switchable_motion_mode: encoded.switchable_motion_mode,
1179 screen: encoded.screen,
1180 start_cdfs: encoded.start_cdfs.clone(),
1181 next_cdfs: encoded.next_cdfs.clone(),
1182 loop_filter: encoded.loop_filter,
1183 loop_restoration: encoded.loop_restoration,
1184 allow_intrabc: encoded.allow_intrabc,
1185 delta: encoded.delta.clone(),
1186 cdef: encoded.cdef,
1187 }
1188}
1189
1190/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1191/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1192#[derive(Clone)]
1193pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1194
1195impl std::fmt::Debug for CdfSnapshot {
1196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1197 f.write_str("CdfSnapshot")
1198 }
1199}
1200
1201/// What one call to [`encode_key_frame`] produced.
1202#[derive(Clone, Debug)]
1203pub struct Encoded {
1204 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1205 /// OBU carrying one tile.
1206 pub stream: Vec<u8>,
1207 /// What a decoder will produce from `stream` — the encoder's own
1208 /// reconstruction, which its prediction was built on.
1209 pub reconstruction: Picture,
1210 /// The luma intra mode each block was coded under, in the order the blocks
1211 /// are coded — raster order among the quadrants of each superblock, and
1212 /// among the four 16x16 blocks of a quadrant that was split.
1213 pub modes: Vec<u8>,
1214 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1215 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1216 /// for a key frame, which has no such choice — so a caller can tell a
1217 /// frame with no motion worth coding from one that never got the chance.
1218 pub inter_block_share: f64,
1219 /// The tile payload alone, undecorated by any OBU framing, and the frame
1220 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1221 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1222 /// off the wire by parsing `stream`'s OBUs instead.
1223 pub(crate) tile: Vec<u8>,
1224 pub(crate) mi_cols: u32,
1225 pub(crate) mi_rows: u32,
1226 pub(crate) base_q_idx: u8,
1227 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1228 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1229 /// and reading it off `stream`'s header is what `decode_stream` does. A
1230 /// test that decodes `tile` directly must pass this one along, or it reads
1231 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1232 /// block.
1233 pub(crate) tx_select: bool,
1234 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1235 /// bit that makes every eligible single-reference inter block carry a
1236 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1237 /// decoding `tile` directly must pass it along or it desyncs at the
1238 /// first eligible block.
1239 pub(crate) switchable_motion_mode: bool,
1240 /// The CDF state this frame's tile writer started from -- the defaults
1241 /// for a key frame and for the first inter frame, and the previous
1242 /// frame's stored tables after that. A test that decodes `tile` directly
1243 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1244 /// the frame's `primary_ref_frame` slot holds (same class as
1245 /// `tx_select`: a header bit a raw tile decode cannot guess).
1246 pub(crate) start_cdfs: CdfSnapshot,
1247 /// What this frame stores into the slots it refreshes (spec 7.20,
1248 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1249 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1250 /// started from when it is on.
1251 pub(crate) next_cdfs: CdfSnapshot,
1252 /// This frame header's chosen deblocking parameters
1253 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1254 /// picture the decoder produces UNDER them, so a test that decodes
1255 /// `tile` directly must pass these along, exactly as it must `tx_select`
1256 /// (class: test asserts against a stale header).
1257 pub(crate) loop_filter: LoopFilterParams,
1258 /// This frame header's chosen CDEF parameters, threaded for the same
1259 /// reason as `loop_filter`.
1260 pub(crate) cdef: CdefParams,
1261 /// This frame header's `allow_screen_content_tools`
1262 /// ([`screen_content`]) -- every intra block of the tile carries the two
1263 /// palette-mode symbols under it, so a raw tile decode that guessed
1264 /// `false` would desync at the first block (same class as `tx_select`).
1265 pub(crate) screen: bool,
1266 /// This frame header's chosen loop restoration parameters, threaded for
1267 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1268 /// filters themselves are coded in `tile`, so a decode of it under a
1269 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1270 pub(crate) loop_restoration: LoopRestorationParams,
1271 /// This frame header's `allow_intrabc` -- every intra block of the tile
1272 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1273 /// guessed `false` would desync at the first block (same class as
1274 /// `screen`/`tx_select`).
1275 pub(crate) allow_intrabc: bool,
1276 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1277 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1278 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1279 /// decode that guessed the defaults desyncs at the first superblock
1280 /// (same class as `screen`/`tx_select`).
1281 pub(crate) delta: ec_av1_syntax::DeltaParams,
1282}
1283
1284thread_local! {
1285 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
1286 /// for on the last key frame encoded on this thread -- read by the gates,
1287 /// which print it beside the block counts (class `gate-blind-to-feature`).
1288 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
1289}
1290
1291/// [`IBC_SHARE`] for the last key frame encoded on this thread.
1292#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1293pub(crate) fn intrabc_source_share() -> f64 {
1294 IBC_SHARE.with(std::cell::Cell::get)
1295}
1296
1297thread_local! {
1298 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
1299 /// header offers the per-frame `allow_screen_content_tools` bit at all.
1300 /// Armed once by the key frame ([`encode_key_frame_inner`], from
1301 /// [`screen_content`]) and read by every header builder after it, so that
1302 /// the inter frames of a screen sequence lay their headers out the same
1303 /// way the sequence header the key frame wrote says they do -- a per-call
1304 /// parameter would have to thread through `inter_frame_headers`' four
1305 /// public entry points and every hand-built-stream test that calls them.
1306 /// A sequence with no screen content leaves this false and writes exactly
1307 /// the bits it wrote before this lane.
1308 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1309}
1310
1311thread_local! {
1312 /// Overrides [`screen_content`] for the calling thread, which is what the
1313 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
1314 /// codes every block losslessly, so both arms of a mode ablation reach
1315 /// infinite PSNR and the ablation measures nothing at all (the
1316 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
1317 /// variable cannot do this -- the tests run in one process, in parallel.
1318 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1319}
1320
1321thread_local! {
1322 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
1323 /// under, AFTER the content gate: the pyramid, or `None` for a stream
1324 /// that stayed flat. Read by the BD gates, which print the requested and
1325 /// the effective pyramid side by side -- a screen clip requests one and
1326 /// codes flat, and that difference is the gate (class
1327 /// `gate-blind-to-feature`).
1328 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
1329 const { std::cell::Cell::new(None) };
1330}
1331
1332/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
1333#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1334pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
1335 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
1336}
1337
1338#[cfg(test)]
1339pub(crate) fn force_screen(value: Option<bool>) {
1340 SCREEN_FORCE.with(|c| c.set(value));
1341}
1342
1343// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
1344// ablation can measure the mode search alone. Setting it also clears the
1345// sequence header's own `enable_filter_intra` bit, so the stream the arm
1346// writes is exactly the one this encoder wrote before the lane.
1347#[cfg(test)]
1348thread_local! {
1349 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1350}
1351
1352#[cfg(test)]
1353pub(crate) fn force_filter_intra(value: Option<bool>) {
1354 FILTER_INTRA_FORCE.with(|c| c.set(value));
1355}
1356
1357pub(crate) fn arm_seq_screen(on: bool) {
1358 SEQ_SCREEN.with(|c| c.set(on));
1359}
1360
1361fn seq_screen() -> bool {
1362 SEQ_SCREEN.with(std::cell::Cell::get)
1363}
1364
1365/// How many distinct colours a 16x16 luma block may hold and still count as
1366/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
1367/// `av1_set_screen_content_options` bound is 4, which separates nothing on
1368/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
1369/// the variance floor below on the five gate clips at BOTH the native crop
1370/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
1371/// the frame is the widest-margin split of those ten rows -- every
1372/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
1373/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
1374/// native and 17.9% scaled.
1375fn screen_colors() -> usize {
1376 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1377 *N.get_or_init(|| {
1378 std::env::var("EC_AV1_SCREEN_COLORS")
1379 .ok()
1380 .and_then(|v| v.parse().ok())
1381 .unwrap_or(16)
1382 })
1383}
1384
1385/// The reciprocal of the frame area those blocks must cover, in tenths --
1386/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
1387/// 8 (an eighth) is the midpoint of the two populations
1388/// `probe_screen_detect` measures at the colour bound and variance floor
1389/// around it. `EC_AV1_SCREEN_PCT`.
1390fn screen_pct() -> usize {
1391 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1392 *N.get_or_init(|| {
1393 std::env::var("EC_AV1_SCREEN_PCT")
1394 .ok()
1395 .and_then(|v| v.parse().ok())
1396 .unwrap_or(10)
1397 })
1398}
1399
1400/// The per-pixel variance a few-colour block must clear before it counts as
1401/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
1402/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
1403/// a smooth dark film frame is all few-colour blocks and reads as a desktop
1404/// capture -- which is exactly what this detector did until 2026-09-07, when
1405/// it called BOTH real films screen content on 48/48 frames, priced every
1406/// coefficient against the default CDFs and ran the palette search over
1407/// film. `probe_screen_detect`: at 16 colours the floor takes both films
1408/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
1409/// 23.6%.
1410fn screen_var() -> u64 {
1411 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1412 *N.get_or_init(|| {
1413 std::env::var("EC_AV1_SCREEN_VAR")
1414 .ok()
1415 .and_then(|v| v.parse().ok())
1416 .unwrap_or(16)
1417 })
1418}
1419
1420/// How many frames [`screen_content`] said yes/no to, so a gate can print
1421/// whether the detector fired at all (class `gate-blind-to-feature`).
1422pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
1423 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
1424
1425/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
1426/// the distinct colours of every 16x16 block and turn the screen-content
1427/// tools on when the blocks holding between 2 and [`screen_colors`] of them
1428/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
1429/// frame. `width` is the plane's
1430/// stride, `true_*` the frame's real (decodable) extent.
1431fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
1432 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
1433 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1434 return forced;
1435 }
1436 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
1437 let on = v != "0";
1438 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1439 return on;
1440 }
1441 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
1442 let mut counted = 0usize;
1443 for by in (0..true_height).step_by(blk) {
1444 for bx in (0..true_width).step_by(blk) {
1445 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
1446 let mut seen = [false; 256];
1447 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
1448 for row in 0..h {
1449 for col in 0..w {
1450 let v = y[(by + row) * width + bx + col];
1451 sum += u64::from(v);
1452 sq += u64::from(v) * u64::from(v);
1453 if !seen[usize::from(v)] {
1454 seen[usize::from(v)] = true;
1455 colors += 1;
1456 }
1457 }
1458 }
1459 // Per-pixel variance over the block's real (edge-clipped) extent.
1460 let n = (h * w) as u64;
1461 let var = (sq - sum * sum / n) / n;
1462 if colors > 1 && colors <= limit && var > floor {
1463 counted += 1;
1464 }
1465 }
1466 }
1467 let on = counted * blk * blk * screen_pct() > true_width * true_height;
1468 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1469 on
1470}
1471
1472/// Whether this SOURCE picture reads as screen content, for a caller that has
1473/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
1474/// gates its coding pyramid on this (a desktop capture keeps the flat
1475/// one-in-one-out structure the BD gate measured it on, camera material takes
1476/// the mini-GOP). The key frame runs the same detector again when it builds
1477/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
1478/// count, so this probe undoes its own tick and leaves the gate prints
1479/// reading one detection per coded frame.
1480pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
1481 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
1482 let on = screen_content(&y, picture.width, picture.width, picture.height);
1483 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1484 on
1485}
1486
1487/// The sequence and frame headers a picture of this size is coded under: one
1488/// tile, one transform size per block, no in-loop filter parameters yet
1489/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
1490/// CDEF strengths in once the tile is coded), no CDF adaptation
1491/// and no tool the tile writer does not code.
1492///
1493/// # Errors
1494/// Returns an error when the picture is larger than the 16-bit frame size the
1495/// sequence header carries.
1496pub fn key_frame_headers(
1497 width: usize,
1498 height: usize,
1499 base_q_idx: u8,
1500) -> Result<(SequenceHeader, FrameHeader)> {
1501 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
1502}
1503
1504/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
1505/// studio (limited) range: what this crate's sequence header carried before
1506/// [`crate::encoder`]'s facade could configure it, and what
1507/// [`key_frame_headers`] still asks for.
1508fn unspecified_color_config() -> ColorConfig {
1509 ColorConfig {
1510 bit_depth: 8,
1511 mono_chrome: false,
1512 num_planes: 3,
1513 color_primaries: 2,
1514 transfer_characteristics: 2,
1515 matrix_coefficients: 2,
1516 color_range: false,
1517 subsampling_x: 1,
1518 subsampling_y: 1,
1519 chroma_sample_position: ChromaSamplePosition::Unknown,
1520 separate_uv_delta_q: false,
1521 }
1522}
1523
1524/// [`key_frame_headers`] with the sequence header's colour config named
1525/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
1526/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
1527/// which is all a player picks a colour transform from and which
1528/// [`crate::encoder::Colour`] is the facade's own name for.
1529///
1530/// # Errors
1531/// The same as [`key_frame_headers`].
1532pub(crate) fn key_frame_headers_colour(
1533 width: usize,
1534 height: usize,
1535 base_q_idx: u8,
1536 color_config: ColorConfig,
1537) -> Result<(SequenceHeader, FrameHeader)> {
1538 let bits = |n: usize| -> Result<u32> {
1539 let n = u32::try_from(n).map_err(|_| too_large())?;
1540 if n == 0 || n > 1 << 16 {
1541 return Err(too_large());
1542 }
1543 Ok((32 - (n - 1).leading_zeros()).max(1))
1544 };
1545 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
1546 let (w, h) = (width as u32, height as u32);
1547 let seq = SequenceHeader {
1548 seq_profile: 0,
1549 operating_points: vec![OperatingPoint {
1550 seq_level_idx: 8,
1551 ..OperatingPoint::default()
1552 }],
1553 frame_width_bits,
1554 frame_height_bits,
1555 max_frame_width: w,
1556 max_frame_height: h,
1557 use_128x128_superblock: false,
1558 // lane-fintra: the encoder's intra search offers the five recursive
1559 // filter-intra modes on eligible blocks, so the sequence bit is set
1560 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
1561 // off and restores the streams this encoder wrote before the lane).
1562 enable_filter_intra: filter_intra_on(),
1563 enable_intra_edge_filter: false,
1564 enable_order_hint: true,
1565 order_hint_bits: 7,
1566 enable_superres: false,
1567 // spec 5.9.19: with the sequence bit set every frame header carries
1568 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
1569 // pair for the whole frame, chosen by `crate::filter_search` -- so no
1570 // `cdef_idx` literal is coded in the tile and a frame that wants no
1571 // CDEF simply carries zero strengths.
1572 enable_cdef: true,
1573 enable_restoration: true,
1574 // SELECT (2) when this sequence's key frame detected screen content
1575 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
1576 // is then coded in every frame header, and only the frames that want
1577 // the palette syntax set it. 0 -- the forced-off form, no bit at all
1578 // -- otherwise, which is what every non-screen stream this encoder
1579 // writes still carries.
1580 seq_force_screen_content_tools: if seq_screen() {
1581 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
1582 } else {
1583 0
1584 },
1585 seq_force_integer_mv: 0,
1586 color_config,
1587 still_picture: false,
1588 reduced_still_picture_header: false,
1589 timing_info: None,
1590 decoder_model_info: None,
1591 initial_display_delay_present_flag: false,
1592 operating_point: 0,
1593 operating_point_idc: 0,
1594 frame_id_numbers_present_flag: false,
1595 delta_frame_id_length: 0,
1596 additional_frame_id_length: 0,
1597 enable_interintra_compound: false,
1598 enable_masked_compound: false,
1599 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
1600 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
1601 // header is byte-identical to the streams before this lane.
1602 enable_warped_motion: warp_on(),
1603 enable_dual_filter: false,
1604 enable_jnt_comp: false,
1605 enable_ref_frame_mvs: false,
1606 film_grain_params_present: false,
1607 };
1608 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
1609 // own (true, unpadded) width and height, not from any block-grid
1610 // alignment — a decoder derives these straight from `frame_width`/
1611 // `frame_height` below, so this must match it exactly.
1612 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
1613 let header = FrameHeader {
1614 frame_type: FrameType::Key,
1615 frame_is_intra: true,
1616 show_frame: true,
1617 error_resilient_mode: true,
1618 // The tile writer keeps the same CDF state the decoder does and
1619 // updates it in the same order, so the frame lets the decoder adapt.
1620 disable_cdf_update: false,
1621 // Nothing reads the state this frame leaves behind: a key frame always
1622 // starts from the defaults, and this encoder emits one frame.
1623 disable_frame_end_update_cdf: true,
1624 force_integer_mv: true,
1625 refresh_frame_flags: 0xFF,
1626 primary_ref_frame: PRIMARY_REF_NONE,
1627 frame_width: w,
1628 frame_height: h,
1629 upscaled_width: w,
1630 render_width: w,
1631 render_height: h,
1632 mi_cols,
1633 mi_rows,
1634 tile_info: TileInfo {
1635 uniform_spacing: true,
1636 cols: 1,
1637 rows: 1,
1638 mi_col_starts: vec![0, mi_cols],
1639 mi_row_starts: vec![0, mi_rows],
1640 tile_size_bytes: 1,
1641 ..TileInfo::default()
1642 },
1643 quantization: QuantizationParams {
1644 base_q_idx,
1645 ..QuantizationParams::default()
1646 },
1647 tx_mode: TxMode::Largest,
1648 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
1649 // intra transform below 32x32, not only 16x16 -- the set this crate
1650 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
1651 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
1652 // so a decoder honouring the header picks the same CDF the writer
1653 // used only if this is set here too, not only on the inter variant
1654 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
1655 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
1656 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
1657 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
1658 // the arithmetic coder's `rng` register from the very first 8x8-leaf
1659 // luma transform onward with no symbol value ever differing.
1660 reduced_tx_set: true,
1661 ..FrameHeader::default()
1662 };
1663 Ok((seq, header))
1664}
1665
1666/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
1667/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
1668/// 1 still holds the key frame however long the GOP runs.
1669pub const GOLDEN_SLOT: u8 = 1;
1670
1671/// The frame header for a shown inter frame that predicts from the single
1672/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
1673/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
1674/// reused verbatim: an inter frame never changes the sequence.
1675///
1676/// # Errors
1677/// Returns an error under the same conditions as [`key_frame_headers`].
1678pub fn inter_frame_headers(
1679 width: usize,
1680 height: usize,
1681 base_q_idx: u8,
1682 order_hint: u32,
1683 last_slot: u8,
1684) -> Result<(SequenceHeader, FrameHeader)> {
1685 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
1686}
1687
1688/// [`inter_frame_headers`] with the three slots named apart: the one read as
1689/// `LAST_FRAME`, the one this frame refreshes, and the one read as
1690/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
1691/// so that the frame two back is still intact in the slot this one is about
1692/// to overwrite -- read before write, spec 7.20's decode order.
1693///
1694/// # Errors
1695/// As [`inter_frame_headers`].
1696pub fn inter_frame_headers_slots(
1697 width: usize,
1698 height: usize,
1699 base_q_idx: u8,
1700 order_hint: u32,
1701 last_slot: u8,
1702 self_slot: u8,
1703 altref_slot: u8,
1704) -> Result<(SequenceHeader, FrameHeader)> {
1705 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
1706 let header = FrameHeader {
1707 frame_type: FrameType::Inter,
1708 frame_is_intra: false,
1709 show_frame: true,
1710 error_resilient_mode: false,
1711 disable_cdf_update: false,
1712 // The tile writer hands its end-of-tile tables to the next frame
1713 // (`encode_sequence_with_ctx`), so the frame stores them the way the
1714 // decoder will load them (spec 7.20).
1715 disable_frame_end_update_cdf: false,
1716 force_integer_mv: false,
1717 order_hint,
1718 primary_ref_frame: 0,
1719 refresh_frame_flags: 1 << self_slot,
1720 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
1721 // names the slot this frame both predicts from and refreshes;
1722 // GOLDEN names slot 1, which the key frame wrote when it refreshed
1723 // all eight and which no inter frame ever overwrites, so it holds
1724 // the key frame's own picture for the whole GOP.
1725 ref_frame_idx: {
1726 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
1727 idx[3] = GOLDEN_SLOT;
1728 idx[6] = altref_slot;
1729 idx
1730 },
1731 allow_high_precision_mv: false,
1732 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
1733 // lane-av1obmc: with this bit set every single-reference inter block
1734 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
1735 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
1736 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
1737 // to the OBMC knob rather than always on: with every block choosing
1738 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
1739 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
1740 // and stays byte-identical to the streams before this lane.
1741 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
1742 // `allow_warped_motion` besides -- which is what makes an eligible
1743 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
1744 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
1745 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
1746 || warp_on(),
1747 allow_warped_motion: warp_on(),
1748 use_ref_frame_mvs: false,
1749 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
1750 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
1751 // set this crate carries a table for at 16x16 (see
1752 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
1753 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
1754 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
1755 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
1756 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
1757 // path) -- with this flag set, `get_tx_set`'s intra branch returns
1758 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
1759 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
1760 reduced_tx_set: true,
1761 ..key
1762 };
1763 Ok((seq, header))
1764}
1765
1766fn too_large() -> Error {
1767 Error::unsupported(
1768 "AV1 encode",
1769 "the picture is larger than a frame size can carry",
1770 )
1771}
1772
1773/// One plane of the picture being coded, and the reconstruction being built
1774/// beside it.
1775/// What one committed 4x4 cell left behind for the coefficient contexts of
1776/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
1777/// is the same state decode.rs records.
1778#[derive(Clone, Copy, Default, PartialEq, Eq)]
1779struct CoefCtx {
1780 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
1781 level: u8,
1782 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
1783 /// the DC itself was zero (tile.rs `dc_vote`).
1784 dc: i8,
1785}
1786
1787/// One plane's coefficient contexts, committed in CODING ORDER: the search
1788/// prices partition TREES, so the neighbour state a candidate reads has to be
1789/// whatever the blocks coded before it left -- the parent's committed
1790/// neighbours for a tree's first child, the just-committed sibling for the
1791/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
1792/// writer's two running bands is what makes that fall out: a trial commits
1793/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
1794/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
1795/// to its left is exactly what the tile writer's `Neighbours` bands will hold
1796/// when it gets there.
1797///
1798/// Before this map the pricer took both contexts as zero, which is exact for
1799/// a luma transform covering its whole block and the largest remaining row of
1800/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
1801#[derive(Default)]
1802struct CoefCtxMap {
1803 cells: Vec<CoefCtx>,
1804 stride: usize,
1805 /// Whether the transforms being priced right now are SMALLER than the
1806 /// block they sit in -- a `TxMode::Select` depth split
1807 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
1808 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
1809 /// trial cannot tell, and it is what decides whether luma reads context 0
1810 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
1811 tu_split: bool,
1812}
1813
1814/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
1815/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
1816/// padding-inclusive score the search used before lane-sse, which is how the
1817/// before/after arms of the straddling gate rows are read off ONE binary.
1818fn edge_sse() -> bool {
1819 static ENV: std::sync::LazyLock<Option<bool>> =
1820 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGESSE").ok().map(|v| v != "0"));
1821 ENV.unwrap_or(true)
1822}
1823
1824/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
1825/// through and the share of their raw squared error that sat in the padding
1826/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
1827/// it, but the numbers are an instrument, not a decision (class
1828/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
1829/// without this census no gate row can say the clip fires at all).
1830fn edge_census() -> bool {
1831 static ENV: std::sync::LazyLock<bool> =
1832 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1"));
1833 *ENV
1834}
1835
1836/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
1837/// 128x128): how many scores clipped, the inside squared error they kept and
1838/// the padding squared error they dropped.
1839static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
1840 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
1841
1842/// One clipped score, for [`take_edge_census`].
1843fn record_edge_score(side: usize, inside: u64, padding: u64) {
1844 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
1845 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1846 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
1847 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
1848}
1849
1850/// The straddling-block census since the last call, and zero it: one
1851/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
1852#[must_use]
1853pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
1854 EDGE_SCORES
1855 .iter()
1856 .enumerate()
1857 .filter_map(|(log2, row)| {
1858 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
1859 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
1860 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
1861 (n != 0).then_some((1usize << log2, n, inside, padding))
1862 })
1863 .collect()
1864}
1865
1866struct Plane<'a> {
1867 source: &'a [u8],
1868 reconstruction: Vec<u8>,
1869 width: usize,
1870 height: usize,
1871 /// The frame's true, decodable extent in this plane's own units --
1872 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
1873 /// not `width`/`height` above, which is the padded coding-surface size.
1874 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
1875 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
1876 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
1877 /// this bound, even though the padded reconstruction buffer holds real
1878 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
1879 /// those instead of stopping here is what desyncs prediction at the true
1880 /// edge.
1881 true_width: usize,
1882 true_height: usize,
1883 /// This plane's own tile's pixel bounds, in this plane's units -- the
1884 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
1885 /// prediction never reaches across a tile edge even though the
1886 /// neighbouring tile's real samples sit right there in the shared
1887 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
1888 /// leaves every edge exactly as it was before tiles existed.
1889 tile_x0: usize,
1890 tile_y0: usize,
1891 tile_x1: usize,
1892 tile_y1: usize,
1893 /// [`CoefCtxMap`]: what the blocks already committed left for the
1894 /// coefficient contexts of the ones still being priced. Sized on the
1895 /// first commit, so a plane literal does not have to know its own extent
1896 /// twice.
1897 ctx: CoefCtxMap,
1898}
1899
1900impl Plane<'_> {
1901 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
1902 /// called at every superblock of the frame-raster search with the rect
1903 /// of the tile that superblock belongs to.
1904 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
1905 self.tile_x0 = x0;
1906 self.tile_y0 = y0;
1907 self.tile_x1 = x1.min(self.width);
1908 self.tile_y1 = y1.min(self.height);
1909 }
1910 /// The reconstructed samples a block at `(x, y)` predicts from: the row
1911 /// above it, the column to its left and the sample between them, each
1912 /// missing where the block sits against an edge of the frame.
1913 ///
1914 /// `reach` says whether the samples above the block's right and below its
1915 /// left are decoded, which is what a directional mode reads into; where
1916 /// they are not, or where the frame ends first, the edge is shorter and
1917 /// the predictor repeats its last sample, exactly as the decoder's clamp
1918 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
1919 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
1920 /// a free per mode per block, on the search's hottest path -- while an
1921 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
1922 /// samples, on the caller's stack.
1923 fn edges_into<'a>(
1924 &self,
1925 x: usize,
1926 y: usize,
1927 side: usize,
1928 reach: Reach,
1929 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
1930 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
1931 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
1932 // Even a block's *own* edge is clamped to the true frame bound, not
1933 // just a `reach` extension: libaom's `av1_predict_intra_block`
1934 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
1935 // this block's own right/bottom to the frame edge -- from
1936 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
1937 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
1938 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
1939 // samples the row/column above/left holds before the decoder starts
1940 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
1941 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
1942 // extent straddles that edge legally (`has_half`) -- the transform
1943 // still covers the whole block, but prediction does not get to read
1944 // real reconstructed pixels past the true edge for its own row/column,
1945 // only for the padded tail it invents.
1946 let own_across = x + side.min(self.true_width.saturating_sub(x));
1947 let across = if reach.above_right {
1948 own_across + side.min(self.true_width.saturating_sub(own_across))
1949 } else {
1950 own_across
1951 }
1952 .min(self.width);
1953 let own_down = y + side.min(self.true_height.saturating_sub(y));
1954 let down = if reach.below_left {
1955 own_down + side.min(self.true_height.saturating_sub(own_down))
1956 } else {
1957 own_down
1958 }
1959 .min(self.height);
1960 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
1961 // whose own origin already sits past the true edge -- only reachable
1962 // through a partition trial priced for comparison on a split this
1963 // frame's straddling quadrant will go on to refuse (see
1964 // `a_picture_off_the_block_grid_is_refused`), never through a block
1965 // this encoder actually commits. Such a block has no true-edge
1966 // samples above or left of it at all, same as `y == 0`/`x == 0`.
1967 let across = across.min(self.tile_x1);
1968 let down = down.min(self.tile_y1);
1969 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
1970 if let Some(n) = above_n {
1971 above_buf[..n]
1972 .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
1973 }
1974 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
1975 if let Some(n) = left_n {
1976 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
1977 *d = self.reconstruction[row * self.width + x - 1];
1978 }
1979 }
1980 let corner = (x > self.tile_x0 && y > self.tile_y0)
1981 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
1982 (
1983 above_n.map(|n| &above_buf[..n]),
1984 left_n.map(|n| &left_buf[..n]),
1985 corner,
1986 )
1987 }
1988
1989 /// Codes one block under one mode without committing it: hands back the
1990 /// levels, the block the decoder would reconstruct, the squared error
1991 /// against the source and an estimate of what the levels cost in bits.
1992 fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
1993 self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx)
1994 }
1995
1996 /// [`Self::trial`] under a named transform type -- what an intra chroma
1997 /// block gets, since chroma codes no `tx_type` symbol and the decoder
1998 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
1999 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
2000 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
2001 #[allow(clippy::too_many_arguments)]
2002 /// Sum of absolute differences between the source block at `(x, y)` and a
2003 /// `side x side` prediction, as the whole number it is.
2004 ///
2005 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
2006 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
2007 /// exactly, so no add here rounds and the order of the adds cannot change
2008 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
2009 /// integer division per sample -- is what lets the row walk vectorize.
2010 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
2011 let mut sad = 0u32;
2012 for row in 0..side {
2013 let source = &self.source[(y + row) * self.width + x..][..side];
2014 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
2015 sad += u32::from(s.abs_diff(p));
2016 }
2017 }
2018 f64::from(sad)
2019 }
2020
2021 /// Squared error between the source block at `(x, y)` and a reconstruction
2022 /// of it, over the part of the block that is INSIDE the true frame.
2023 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
2024 /// `255^2 * 64 * 64`, under 2^28.
2025 ///
2026 /// A block the frame edge cuts through is still coded whole -- the
2027 /// decoder reconstructs its outside samples too and the display crop
2028 /// throws them away -- so scoring the padding would rank a mode, a
2029 /// transform or a partition tree by how well it codes samples the source
2030 /// does not have (libaom clips the same way: `av1_dist_block` measures
2031 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
2032 /// edge pixels, so predicting it is nearly free, but coding coefficients
2033 /// for it spends real bits. Both gate films are superblock-aligned; this
2034 /// only reaches arbitrary export sizes (lane-sse, generalising
2035 /// lane-b64b's 64-root-only rescore of the 64 root).
2036 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
2037 let inside_rows = side.min(self.true_height.saturating_sub(y));
2038 let inside_cols = side.min(self.true_width.saturating_sub(x));
2039 let straddles = inside_rows < side || inside_cols < side;
2040 // The knob is read only for a block the edge cuts, so the interior
2041 // path -- the hot one -- carries no extra load at all.
2042 let (rows, cols) = match straddles && !edge_sse() {
2043 true => (side, side),
2044 false => (inside_rows, inside_cols),
2045 };
2046 let mut sse = 0u64;
2047 for row in 0..rows {
2048 let source = &self.source[(y + row) * self.width + x..][..cols];
2049 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
2050 let d = u32::from(s.abs_diff(r));
2051 sse += u64::from(d * d);
2052 }
2053 }
2054 if straddles && edge_census() {
2055 let (mut inside, mut whole) = (0u64, 0u64);
2056 for row in 0..side {
2057 let source = &self.source[(y + row) * self.width + x..][..side];
2058 for (col, (&s, &r)) in
2059 source.iter().zip(&reconstruction[row * side..][..side]).enumerate()
2060 {
2061 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
2062 whole += d;
2063 if row < inside_rows && col < inside_cols {
2064 inside += d;
2065 }
2066 }
2067 }
2068 record_edge_score(side, inside, whole - inside);
2069 }
2070 sse as f64
2071 }
2072
2073 fn trial_typed(
2074 &self,
2075 at: At,
2076 mode: u8,
2077 // This block's `angle_delta_y`/`angle_delta_uv` (spec
2078 // `read_intra_angle_info`, -3..=3), zero for every non-directional
2079 // mode -- the predictor's own `angle_delta` argument.
2080 angle_delta: i32,
2081 base_q_idx: u8,
2082 deadzone: f64,
2083 tx_type: TxType,
2084 fctx: &crate::decode::FrameCtx,
2085 ) -> Trial {
2086 let At {
2087 x, y, side, reach, ..
2088 } = at;
2089 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2090 let (above, left, corner) =
2091 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2092 // Per-candidate scratch on the search's hottest path, so both buffers
2093 // live on the stack -- `side` is at most `BLOCK` -- rather than
2094 // costing a malloc/free pair per trial (`mc_trial` already does this).
2095 let mut prediction = [0u8; BLOCK * BLOCK];
2096 let prediction = &mut prediction[..side * side];
2097 intra_predict_u8(
2098 mode,
2099 angle_delta,
2100 above,
2101 left,
2102 corner,
2103 side,
2104 side,
2105 false,
2106 false,
2107 prediction, fctx,
2108 );
2109
2110 let mut residual = [0i32; BLOCK * BLOCK];
2111 let residual = &mut residual[..side * side];
2112 for row in 0..side {
2113 for col in 0..side {
2114 residual[row * side + col] =
2115 i32::from(self.source[(y + row) * self.width + x + col])
2116 - i32::from(prediction[row * side + col]);
2117 }
2118 }
2119 #[cfg(test)]
2120 let t = stage_start();
2121 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
2122 // reconstruction below and the price further down are both of the
2123 // grid this trial would really code.
2124 let (levels, rdoq_bits) = if rdoq_on() {
2125 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2126 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2127 );
2128 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2129 let bits = crate::tile::rdoq(
2130 &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(),
2131 );
2132 (levels, Some(bits))
2133 } else {
2134 (
2135 forward_and_quantize_typed(
2136 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2137 ),
2138 None,
2139 )
2140 };
2141 // lane-av1speed2: 60% of the transform units of an inter stream carry
2142 // no coefficient at all, and the square entry point re-inflates that
2143 // case into `side * side` zeros (one allocate-and-memset per trial)
2144 // only for the sum below to add them to the prediction. The `_wh`
2145 // entry hands back the empty all-zero marker instead, and a zero
2146 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
2147 // `p` for a `u8`, so the bytes are the same.
2148 let coded = dequant_and_inverse_typed_wh(
2149 &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type,
2150 );
2151 #[cfg(test)]
2152 stage_since(2, t);
2153
2154 let reconstruction: Vec<u8> = if coded.is_empty() {
2155 prediction.to_vec()
2156 } else {
2157 prediction
2158 .iter()
2159 .zip(&coded)
2160 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2161 .collect()
2162 };
2163 let sse = self.block_sse(x, y, side, &reconstruction);
2164 // What the levels cost is priced through the same CDFs the tile writer
2165 // will code them with, so the search ranks modes -- and the partition
2166 // trial ranks trees -- by the bits they actually spend.
2167 #[cfg(test)]
2168 let t = stage_start();
2169 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2170 // What the search used before it could price a block exactly: a
2171 // level costs its magnitude's width plus a sign and a run. Kept
2172 // reachable from the sweep so the two rate terms can be compared
2173 // on one build.
2174 levels
2175 .iter()
2176 .filter(|&&level| level != 0)
2177 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2178 .sum()
2179 } else if let Some(bits) = rdoq_bits {
2180 // Already priced, against the grid the pass settled on.
2181 bits
2182 } else {
2183 {
2184 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2185 crate::tile::coeff_bits(
2186 &levels,
2187 at.set,
2188 crate::decode::q_ctx_of(base_q_idx),
2189 skip_ctx,
2190 sign_ctx,
2191 )
2192 }
2193 };
2194 #[cfg(test)]
2195 stage_since(3, t);
2196 Trial {
2197 levels,
2198 reconstruction,
2199 sse,
2200 bits,
2201 }
2202 }
2203
2204 /// [`Self::trial`] with the prediction already built, so that an inter
2205 /// block's motion-compensated prediction can go through the same
2206 /// residual/quantize/reconstruct path an intra block's does. `skip`
2207 /// takes the prediction as the reconstruction outright, coding no
2208 /// residual at all — what a `NEARESTMV` block that names no coefficients
2209 /// codes.
2210 #[allow(clippy::too_many_arguments)]
2211 fn code_from_prediction(
2212 &self,
2213 x: usize,
2214 y: usize,
2215 side: usize,
2216 prediction: &[u8],
2217 skip: bool,
2218 base_q_idx: u8,
2219 deadzone: f64,
2220 set: TxbSet,
2221 ) -> Trial {
2222 if skip {
2223 let sse = self.block_sse(x, y, side, prediction);
2224 return Trial {
2225 levels: vec![0i32; side * side],
2226 reconstruction: prediction.to_vec(),
2227 sse,
2228 bits: 0.0,
2229 };
2230 }
2231 // A 64x64 root's residual is four times the scratch every other
2232 // block coder here sizes for [`BLOCK`]; only that one case pays for
2233 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
2234 let mut small = [0i32; BLOCK * BLOCK];
2235 let mut big = if side > BLOCK {
2236 vec![0i32; side * side]
2237 } else {
2238 Vec::new()
2239 };
2240 let residual: &mut [i32] = if side > BLOCK {
2241 &mut big
2242 } else {
2243 &mut small[..side * side]
2244 };
2245 for row in 0..side {
2246 for col in 0..side {
2247 residual[row * side + col] =
2248 i32::from(self.source[(y + row) * self.width + x + col])
2249 - i32::from(prediction[row * side + col]);
2250 }
2251 }
2252 #[cfg(test)]
2253 let t = stage_start();
2254 // lane-rdoq, as in [`Self::trial_typed`].
2255 let (levels, rdoq_bits) = if rdoq_on() {
2256 let (mut levels, scaled) =
2257 forward_and_quantize_scaled(residual, side, 8, i32::from(base_q_idx), deadzone);
2258 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
2259 let bits = crate::tile::rdoq(
2260 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),
2261 );
2262 (levels, Some(bits))
2263 } else {
2264 (
2265 forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone),
2266 None,
2267 )
2268 };
2269 // The same all-zero shortcut [`Self::trial_typed`] takes.
2270 let coded = dequant_and_inverse_typed_wh(
2271 &levels,
2272 side,
2273 side,
2274 8,
2275 i32::from(base_q_idx),
2276 0,
2277 0,
2278 TxType::DctDct,
2279 );
2280 #[cfg(test)]
2281 stage_since(2, t);
2282 let reconstruction: Vec<u8> = if coded.is_empty() {
2283 prediction.to_vec()
2284 } else {
2285 prediction
2286 .iter()
2287 .zip(&coded)
2288 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2289 .collect()
2290 };
2291 let sse = self.block_sse(x, y, side, &reconstruction);
2292 // A 64-point transform codes only its top-left 32x32 corner (spec
2293 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
2294 // key frame writer takes a 32x32 level grid for one). The inverse
2295 // above reads the whole 64x64 array, but the price below and the
2296 // levels the writer takes are that corner.
2297 let levels = if side > BLOCK {
2298 coded_corner(&levels, side, BLOCK)
2299 } else {
2300 levels
2301 };
2302 #[cfg(test)]
2303 let t = stage_start();
2304 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2305 levels
2306 .iter()
2307 .filter(|&&level| level != 0)
2308 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2309 .sum()
2310 } else if let Some(bits) = rdoq_bits {
2311 bits
2312 } else {
2313 {
2314 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
2315 crate::tile::coeff_bits(
2316 &levels,
2317 set,
2318 crate::decode::q_ctx_of(base_q_idx),
2319 skip_ctx,
2320 sign_ctx,
2321 )
2322 }
2323 };
2324 #[cfg(test)]
2325 stage_since(3, t);
2326 Trial {
2327 levels,
2328 reconstruction,
2329 sse,
2330 bits,
2331 }
2332 }
2333
2334 /// Codes this block's luma at transform depth `depth`: the
2335 /// `(side >> depth)^2` transform units in raster order, each predicted
2336 /// from the reconstruction the units before it left behind -- exactly
2337 /// what the decoder's multi-transform-unit branch does (decode.rs
2338 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
2339 /// reconstructed on its own. Commits the result and hands back the
2340 /// block-coordinate levels, the block's squared error and what its
2341 /// coefficients cost.
2342 #[allow(clippy::too_many_arguments)]
2343 fn code_tx_depth(
2344 &mut self,
2345 at: At,
2346 mode: u8,
2347 angle_delta: i32,
2348 depth: usize,
2349 // This block's `filter_intra_mode` when it is coded with one, in
2350 // which case every transform unit predicts recursively off the
2351 // reconstruction the units before it left -- what the decoder does
2352 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
2353 // `filter_intra`), not once over the whole block.
2354 filter_intra: Option<u8>,
2355 search: &Search, fctx: &crate::decode::FrameCtx,
2356 ) -> (Vec<i32>, f64, f64) {
2357 let At { x, y, side, reach, .. } = at;
2358 let tx = side >> depth;
2359 let n = 1usize << depth;
2360 let set = match tx {
2361 32 => TxbSet::Luma32,
2362 16 => TxbSet::Luma16,
2363 8 => TxbSet::Luma8,
2364 _ => TxbSet::Luma4,
2365 };
2366 let mut levels = vec![0i32; side * side];
2367 census_add(4, n * n);
2368 // A unit smaller than its block reads the neighbour magnitude table
2369 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
2370 self.ctx.tu_split = n > 1;
2371 let (mut sse, mut bits) = (0.0, 0.0);
2372 for tu_row in 0..n {
2373 for tu_col in 0..n {
2374 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
2375 let tu = At {
2376 x: x + col_off,
2377 y: y + row_off,
2378 side: tx,
2379 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
2380 set,
2381 };
2382 let trial = match filter_intra {
2383 Some(fi) => {
2384 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2385 let (above, left, corner) =
2386 self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf);
2387 let mut prediction = vec![0u8; tx * tx];
2388 filter_intra_predict_u8(
2389 usize::from(fi),
2390 above,
2391 left,
2392 corner,
2393 tx,
2394 &mut prediction,
2395 fctx,
2396 );
2397 self.code_from_prediction(
2398 tu.x,
2399 tu.y,
2400 tx,
2401 &prediction,
2402 false,
2403 search.base_q_idx,
2404 search.deadzone,
2405 set,
2406 )
2407 }
2408 None => {
2409 self.trial(tu, mode, angle_delta, search.base_q_idx, search.deadzone, fctx)
2410 }
2411 };
2412 sse += trial.sse;
2413 bits += trial.bits;
2414 self.commit(tu.x, tu.y, tx, &trial);
2415 for row in 0..tx {
2416 levels[(row_off + row) * side + col_off..][..tx]
2417 .copy_from_slice(&trial.levels[row * tx..][..tx]);
2418 }
2419 }
2420 }
2421 self.ctx.tu_split = false;
2422 (levels, sse, bits)
2423 }
2424
2425 /// Writes a trial's reconstruction back into the plane, and the
2426 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
2427 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
2428 for row in 0..side {
2429 self.reconstruction[(y + row) * self.width + x..][..side]
2430 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
2431 }
2432 self.commit_ctx(x, y, side, &trial.levels);
2433 }
2434
2435 /// Publishes one committed transform's own context over every 4x4 cell it
2436 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
2437 /// which is what the writer will read when it reaches the next block.
2438 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
2439 if self.ctx.cells.is_empty() {
2440 self.ctx.stride = self.width.div_ceil(4);
2441 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
2442 }
2443 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
2444 let state = CoefCtx {
2445 level: cul,
2446 dc: match levels[0].signum() {
2447 0 => 0,
2448 -1 => -1,
2449 _ => 1,
2450 },
2451 };
2452 let n = (side / 4).max(1);
2453 // Only up to the frame's TRUE extent: the writer's own
2454 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
2455 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
2456 // and leaves the cells past it uncoded even mid-block, so a
2457 // straddling block publishes context for its inside part only.
2458 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
2459 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
2460 for row in 0..rows {
2461 let start = (y / 4 + row) * self.ctx.stride + x / 4;
2462 let end = (start + cols).min(self.ctx.cells.len());
2463 if start < end {
2464 self.ctx.cells[start..end].fill(state);
2465 }
2466 }
2467 }
2468
2469 /// A block committed without any residual at all ([`ibc_commit`]): the
2470 /// cells it covers coded nothing, and leaving an earlier trial's state
2471 /// there would price its neighbours off a block that was never coded.
2472 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
2473 self.commit_ctx(x, y, side, &[0i32]);
2474 }
2475
2476 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
2477 /// plane reads, off what the blocks before it in coding order committed
2478 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
2479 /// the above/left neighbours coded anything (tile.rs
2480 /// `write_block_planes`), luma reads context 0 when its transform covers
2481 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
2482 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
2483 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
2484 /// the same neighbours (tile.rs `dc_sign_ctx`).
2485 ///
2486 /// A neighbour outside this plane's own TILE does not exist, exactly as
2487 /// the writer's per-tile `Neighbours` bands start blank.
2488 ///
2489 /// CLOSED (lane-av1straddle): the decisions this price changes used to
2490 /// make `decode_stream_round_trips_an_odd_size_gop` and
2491 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
2492 /// fail at 216x96. Never this map: the writer coded the phantom
2493 /// transform units of a right-edge-straddling 32x32 (tile.rs
2494 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
2495 /// like decode.rs and libaom), which libdav1d and libaom both refused
2496 /// outright while a decision change was what first walked into it.
2497 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
2498 if self.ctx.cells.is_empty() {
2499 return (0, 0);
2500 }
2501 let n = (side / 4).max(1);
2502 let (cx, cy) = (x / 4, y / 4);
2503 let (mut top, mut left) = (0u8, 0u8);
2504 let mut vote = 0i32;
2505 if y > self.tile_y0 && cy > 0 {
2506 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
2507 top |= cell.level;
2508 vote += i32::from(cell.dc);
2509 }
2510 }
2511 if x > self.tile_x0 && cx > 0 {
2512 for row in 0..n {
2513 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
2514 left |= cell.level;
2515 vote += i32::from(cell.dc);
2516 }
2517 }
2518 let skip_ctx = if set.is_chroma() {
2519 usize::from(top != 0) + usize::from(left != 0)
2520 } else if self.ctx.tu_split {
2521 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
2522 } else {
2523 0
2524 };
2525 let sign_ctx = match vote.signum() {
2526 0 => 0,
2527 -1 => 1,
2528 _ => 2,
2529 };
2530 (skip_ctx, sign_ctx)
2531 }
2532
2533 /// The source samples of one square, contiguous — what a motion search
2534 /// compares its candidates' predictions against ([`motion::search`]'s
2535 /// `source`), since [`Self::source`] itself is the whole plane, strided
2536 /// by [`Self::width`].
2537 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
2538 rows_of(self.source, self.width, x, y, side)
2539 }
2540
2541 /// The reconstructed samples of one square, so that a partition trial can
2542 /// be undone.
2543 /// The reconstructed samples of one square AND the coefficient contexts
2544 /// its cells hold, so that a partition trial can be undone whole: a
2545 /// losing trial that left its own nz/DC state behind would price the
2546 /// blocks after it off a block the tile writer never codes.
2547 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
2548 (
2549 rows_of(&self.reconstruction, self.width, x, y, side),
2550 self.ctx_rows(x, y, side),
2551 )
2552 }
2553
2554 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
2555 if self.ctx.cells.is_empty() {
2556 return Vec::new();
2557 }
2558 let n = (side / 4).max(1);
2559 (0..n)
2560 .flat_map(|row| {
2561 let start = (y / 4 + row) * self.ctx.stride + x / 4;
2562 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
2563 })
2564 .collect()
2565 }
2566
2567 /// Puts a snapshot back.
2568 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
2569 for row in 0..side {
2570 self.reconstruction[(y + row) * self.width + x..][..side]
2571 .copy_from_slice(&saved.0[row * side..][..side]);
2572 }
2573 if saved.1.is_empty() {
2574 return;
2575 }
2576 let n = (side / 4).max(1);
2577 for row in 0..n {
2578 let start = (y / 4 + row) * self.ctx.stride + x / 4;
2579 let end = (start + n).min(self.ctx.cells.len());
2580 if start < end {
2581 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
2582 }
2583 }
2584 }
2585
2586 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
2587 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
2588 /// prescreen by the identical rule rather than a second one that could
2589 /// drift from it.
2590 fn intra_scores(
2591 &self,
2592 at: At,
2593 modes: &[u8],
2594 mode_bits: &[f64; 13],
2595 lambda: f64, fctx: &crate::decode::FrameCtx,
2596 ) -> Vec<(f64, u8)> {
2597 let At {
2598 x, y, side, reach, ..
2599 } = at;
2600 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2601 let (above, left, corner) =
2602 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2603 modes
2604 .iter()
2605 .map(|&mode| {
2606 let mut prediction = vec![0u8; side * side];
2607 intra_predict_u8(
2608 mode,
2609 0,
2610 above,
2611 left,
2612 corner,
2613 side,
2614 side,
2615 false,
2616 false,
2617 &mut prediction, fctx,
2618 );
2619 let sad = self.block_sad(x, y, side, &prediction);
2620 (sad + lambda * mode_bits[usize::from(mode)], mode)
2621 })
2622 .collect()
2623 }
2624
2625 /// Codes one block under every mode the search offers (or, when
2626 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
2627 /// pre-pass plus DC) and commits the one whose squared error and
2628 /// estimated rate come out cheapest.
2629 ///
2630 /// The prediction is built once per mode regardless -- the full RD trial
2631 /// needs it too -- so ranking modes by SAD on that same prediction before
2632 /// running the expensive part (forward transform, quantize, reconstruct,
2633 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
2634 /// only to sum.
2635 fn search_block(
2636 &mut self,
2637 at: At,
2638 search: &Search,
2639 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
2640 ) -> (Vec<Coeff>, u8, i32, f64) {
2641 let At {
2642 x, y, side, reach, ..
2643 } = at;
2644 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2645 let (above, left, corner) =
2646 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2647 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
2648 // the census reports it), so summing it under the default unpruned
2649 // search is `side * side` absolute differences per mode spent on a
2650 // number no one reads.
2651 let want_sad = search.top_k.is_some() || census_on();
2652 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
2653 .modes
2654 .iter()
2655 .map(|&mode| {
2656 let mut prediction = vec![0u8; side * side];
2657 intra_predict_u8(
2658 mode,
2659 0,
2660 above,
2661 left,
2662 corner,
2663 side,
2664 side,
2665 false,
2666 false,
2667 &mut prediction, fctx,
2668 );
2669 let sad = if want_sad {
2670 self.block_sad(x, y, side, &prediction)
2671 } else {
2672 0.0
2673 };
2674 (
2675 sad + search.lambda * mode_bits[usize::from(mode)],
2676 mode,
2677 prediction,
2678 )
2679 })
2680 .collect();
2681 if let Some(k) = search.top_k {
2682 if k < scored.len() {
2683 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
2684 let dc_entry = dc_pos.map(|i| scored.remove(i));
2685 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
2686 scored.truncate(if dc_entry.is_some() {
2687 k.saturating_sub(1)
2688 } else {
2689 k
2690 });
2691 if let Some(dc_entry) = dc_entry {
2692 scored.push(dc_entry);
2693 }
2694 }
2695 }
2696 let ranking: Vec<(f64, u8)> = if census_on() {
2697 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
2698 } else {
2699 Vec::new()
2700 };
2701 census_add(0, 1);
2702 census_add(1, scored.len());
2703 let mut best: Option<(f64, u8, Trial)> = None;
2704 for (_, mode, prediction) in scored {
2705 let trial = self.code_from_prediction(
2706 x,
2707 y,
2708 side,
2709 &prediction,
2710 false,
2711 search.base_q_idx,
2712 search.deadzone,
2713 at.set,
2714 );
2715 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
2716 if best
2717 .as_ref()
2718 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
2719 {
2720 best = Some((cost, mode, trial));
2721 }
2722 }
2723 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
2724 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
2725 // directional modes each carry a -3..=3 delta, three degrees a step,
2726 // which the writer has always coded as ZERO because nothing searched
2727 // it. Refined on the winning mode only -- libaom's own ordering, and
2728 // six extra trials on the directional blocks instead of on every
2729 // block times every mode. The edges are the ones the base angle
2730 // already read (`enable_intra_edge_filter` is off in this encoder's
2731 // sequence header, so no delta changes which samples exist), and the
2732 // predictor is the decoder's, `angle_delta` argument and all.
2733 let mut angle_delta = 0i32;
2734 // Not on a screen frame: measured on the 5-row native gate, the
2735 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
2736 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
2737 // synthetic edges land on the base angles, so every delta there buys
2738 // a symbol and no prediction. Same `search.screen` gate palette and
2739 // intrabc already stand behind.
2740 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
2741 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
2742 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
2743 let mut prediction = vec![0u8; side * side];
2744 for delta in [-3i32, -2, -1, 1, 2, 3] {
2745 intra_predict_u8(
2746 mode,
2747 delta,
2748 above,
2749 left,
2750 corner,
2751 side,
2752 side,
2753 false,
2754 false,
2755 &mut prediction, fctx,
2756 );
2757 let candidate = self.code_from_prediction(
2758 x,
2759 y,
2760 side,
2761 &prediction,
2762 false,
2763 search.base_q_idx,
2764 search.deadzone,
2765 at.set,
2766 );
2767 let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
2768 - zero_bits;
2769 let cost_d = candidate.sse
2770 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
2771 if cost_d < cost {
2772 cost = cost_d;
2773 angle_delta = delta;
2774 trial = candidate;
2775 }
2776 }
2777 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
2778 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2779 }
2780 if census_on() {
2781 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
2782 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2783 }
2784 self.commit(x, y, side, &trial);
2785 // A 64-point transform codes only its top-left 32x32 corner, which is
2786 // the grid `code_from_prediction` hands back (lane-i64).
2787 (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost)
2788 }
2789}
2790
2791/// Where one block sits in its plane, and how far past its own edges its
2792/// prediction may read.
2793#[derive(Clone, Copy)]
2794struct At {
2795 x: usize,
2796 y: usize,
2797 side: usize,
2798 reach: Reach,
2799 /// Which of the tile writer's coefficient tables this block's levels are
2800 /// coded with, and so which the search prices them through.
2801 set: TxbSet,
2802}
2803
2804/// Which of the samples past a block's own edges the decoder has decoded by
2805/// the time it predicts the block, and so which a directional mode may read.
2806///
2807/// The decoder derives these from its `BlockDecoded` flags, which are cleared
2808/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
2809/// that map, this reads the answer the same way libaom and rav1e do: for a
2810/// block whose transform covers it whole, whether the samples above its right
2811/// (or below its left) are decoded depends only on where the block sits inside
2812/// its 64x64 superblock, which is a pinned table per block size.
2813#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2814pub(crate) struct Reach {
2815 pub(crate) above_right: bool,
2816 pub(crate) below_left: bool,
2817}
2818
2819/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
2820/// libaom): for a block that is neither in the superblock's top row nor its
2821/// rightmost column, whether the block above and to its right is coded before
2822/// it. Indexed by the block's position in the superblock, in blocks of its own
2823/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
2824/// 128, not this crate's 64 superblock -- bit by bit from the low end.
2825const HAS_TOP_RIGHT: [&[u8]; 4] = [
2826 &[255, 85, 119, 85, 127, 85, 119, 85],
2827 &[95, 87],
2828 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
2829 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
2830 &[
2831 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
2832 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
2833 ],
2834
2835 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
2836 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
2837 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
2838 // with side 4 outside a TX4 split; without their own row they clamped
2839 // into the 8x8 table and read above-right samples the decoder has not
2840 // written yet (all-zero pixels in the bottom-right triangle of a
2841 // directional 4x4 leaf).
2842 &[
2843 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
2844 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
2845 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
2846 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
2847 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
2848 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
2849 119, 119, 119, 119, 85, 85, 85, 85,
2850 ],
2851];
2852
2853/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
2854/// left.
2855const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
2856 &[84, 16, 84, 0, 84, 16, 84, 0],
2857 &[4, 4],
2858 // has_bl_8x8 (libaom av1/common/reconintra.c)
2859 &[
2860 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
2861 84, 85, 16, 17, 84, 85, 0, 0,
2862 ],
2863
2864 // has_bl_4x4 (same source, same order).
2865 &[
2866 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
2867 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,
2868 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
2869 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,
2870 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
2871 85, 85, 0, 0, 0, 0,
2872 ],
2873];
2874
2875/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
2876/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
2877/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
2878/// rather than in raster order, so the bottom-left square's top-right
2879/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
2880/// libaom switches tables on the partition type (`get_has_tr_table`); the
2881/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
2882/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
2883/// lane-part32 r5 caught reading undecoded samples.
2884const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
2885 // has_tr_vert_16x16
2886 &[255, 0, 119, 0, 127, 0, 119, 0],
2887 // has_tr_vert_32x32
2888 &[15, 7],
2889 // has_tr_vert_8x8
2890 &[
2891 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
2892 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
2893 ],
2894];
2895
2896/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
2897const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
2898 // has_bl_vert_16x16
2899 &[254, 16, 254, 0, 254, 16, 254, 0],
2900 // has_bl_vert_32x32
2901 &[14, 14],
2902 // has_bl_vert_8x8
2903 &[
2904 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
2905 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
2906 ],
2907];
2908
2909thread_local! {
2910 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
2911 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
2912 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
2913 /// threading one bool through this crate's already twenty-argument
2914 /// `decode_block` would touch every call site instead of the two arms
2915 /// that need it.
2916 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2917}
2918
2919/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
2920pub(crate) struct VertAbGuard(bool);
2921
2922impl Drop for VertAbGuard {
2923 fn drop(&mut self) {
2924 VERT_AB_PARTITION.with(|c| c.set(self.0));
2925 }
2926}
2927
2928/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
2929/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
2930/// so no byte is retyped). Each is indexed by
2931/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
2932/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
2933/// superblock grid; on this crate's 64-pixel superblock the highest index a
2934/// shape can reach stays inside its own table, so no wrap is involved.
2935///
2936/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
2937/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
2938/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
2939/// 10 of the 21 reachable superblock positions for above-right and 7 for
2940/// below-left.
2941/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
2942const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119];
2943/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
2944const HAS_BL_4X8: [u8; 64] = [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, 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, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0];
2945/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
2946const HAS_TR_8X4: [u8; 64] = [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, 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, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0];
2947/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
2948const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0];
2949/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
2950const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
2951/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
2952const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
2953/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
2954const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
2955/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
2956const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
2957/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
2958const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
2959/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
2960const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
2961/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
2962const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
2963/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
2964const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
2965/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
2966const HAS_TR_32X64: [u8; 1] = [127];
2967/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
2968const HAS_BL_32X64: [u8; 1] = [0];
2969/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
2970const HAS_TR_64X32: [u8; 1] = [19];
2971/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
2972const HAS_BL_64X32: [u8; 1] = [34];
2973/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
2974const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127];
2975/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
2976const HAS_BL_4X16: [u8; 32] = [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];
2977/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
2978const HAS_TR_16X4: [u8; 32] = [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, 85, 0, 0, 0];
2979/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
2980const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0];
2981/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
2982const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
2983/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
2984const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
2985/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
2986const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
2987/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
2988const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
2989/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
2990const HAS_TR_16X64: [u8; 2] = [255, 127];
2991/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
2992const HAS_BL_16X64: [u8; 2] = [0, 0];
2993/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
2994const HAS_TR_64X16: [u8; 2] = [3, 1];
2995/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
2996const HAS_BL_64X16: [u8; 2] = [42, 42];
2997
2998/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
2999fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
3000 match (bw, bh) {
3001 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
3002 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
3003 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
3004 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
3005 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
3006 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
3007 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
3008 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
3009 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
3010 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
3011 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
3012 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
3013 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
3014 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
3015 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
3016 }
3017}
3018
3019impl Reach {
3020 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3021 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
3022 /// own answer is `block` -- a different rule from the standalone-block
3023 /// tables, because a unit's neighbours are mostly its own block's
3024 /// already-reconstructed units:
3025 /// * top-right: available while the unit to the right is still inside
3026 /// the block (`col_off + tx < bw`); otherwise only the block's top row
3027 /// of units reaches past it, through the block-level answer
3028 /// (libaom's `row_off > 0` branch returns exactly
3029 /// `col_off + txw < plane_bw`).
3030 /// * bottom-left: a unit outside the block's left column has none
3031 /// (libaom returns 0 for `col_off > 0`); inside the block
3032 /// (`row_off + tx < bh`) they are the left unit's, already
3033 /// reconstructed; the bottom row falls back to the block-level answer.
3034 pub(crate) fn of_tu(
3035 bw: usize,
3036 bh: usize,
3037 col_off: usize,
3038 row_off: usize,
3039 // The unit's own width and height in pixels; equal for a square
3040 // transform, different for the rect unit a 1:4 strip's first split
3041 // produces (lane-rectsplitx r1).
3042 tx_w: usize,
3043 tx_h: usize,
3044 block: Self,
3045 ) -> Self {
3046 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
3047 // order, so both libaom predicates special-case it (lane-sb128c r10);
3048 // without this the last unit column of every chunk of a 128x64 block
3049 // predicts from a chunk libaom has not decoded yet.
3050 let wide = bw > 64;
3051 Self {
3052 above_right: if row_off > 0 {
3053 // `has_top_right`'s `row_off > 0` branch: the offset is taken
3054 // modulo the 64-wide chunk, except for the one unit whose
3055 // top-right corner is the centre of a 128x128 block.
3056 if wide {
3057 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
3058 } else {
3059 col_off + tx_w < bw
3060 }
3061 } else if col_off + tx_w < bw {
3062 true
3063 } else {
3064 block.above_right
3065 },
3066 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
3067 // `has_bottom_left`: at the left edge of a right-hand chunk
3068 // the bottom-left pixels are in the already-coded left chunk,
3069 // provided they stay inside it.
3070 (row_off % 64) + tx_h < bh.min(64)
3071 } else if col_off > 0 {
3072 false
3073 } else if row_off + tx_h < bh {
3074 true
3075 } else {
3076 block.below_left
3077 },
3078 }
3079 }
3080
3081 /// What a block of `side` samples at `(x, y)` may read past its own edges,
3082 /// in a frame of `width` by `height`.
3083 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
3084 Self {
3085 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
3086 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
3087 }
3088 }
3089
3090 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
3091 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
3092 /// block's own width for the row stride and by its own height for the
3093 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
3094 /// unlike the square [`Self::of`] which uses one `side` for everything.
3095 pub(crate) fn of_rect(
3096 bw: usize,
3097 bh: usize,
3098 x: usize,
3099 y: usize,
3100 width: usize,
3101 height: usize, fctx: &crate::decode::FrameCtx,
3102 ) -> Self {
3103 Self {
3104 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
3105 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
3106 }
3107 }
3108
3109 /// [`Self::of`] for one transform unit of a square block whose transform
3110 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
3111 /// non-zero `row_off`/`col_off`): interior units answer from the block's
3112 /// own geometry, and only a unit on the block's top row (resp. left
3113 /// column) reaches the table -- which is the BLOCK's table read at the
3114 /// BLOCK's position, never a table row for the transform's size. Letting
3115 /// the unit stand in for a block of its own size agrees with libaom for
3116 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
3117 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
3118 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
3119 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
3120 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
3121 /// the transform covering the whole block, luma): everything before the
3122 /// table lookup is that function's own early-exit ladder.
3123 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3124 let sb_mi: usize = reach_sb_px(fctx) / 4;
3125 let (mi_row, mi_col) = (y / 4, x / 4);
3126 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3127 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3128 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3129 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3130 // Top row of the superblock: the top-right pixels are in the (already
3131 // decoded) superblock above.
3132 if blk_row == 0 {
3133 return true;
3134 }
3135 // Rightmost column: they fall in the superblock to the right.
3136 if ((blk_col + 1) << bw_log2) >= sb_mi {
3137 return false;
3138 }
3139 let table = rect_reach_tables(bw, bh).0;
3140 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
3141 }
3142
3143 /// libaom `has_top_right`'s own index arithmetic:
3144 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
3145 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
3146 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
3147 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
3148 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
3149 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
3150 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
3151 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
3152 (blk_row << (5 - bw_log2)) + blk_col
3153 }
3154
3155 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
3156 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3157 let sb_mi: usize = reach_sb_px(fctx) / 4;
3158 let (mi_row, mi_col) = (y / 4, x / 4);
3159 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3160 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3161 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3162 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3163 // Leftmost column of the superblock: the bottom-left pixels are in
3164 // the left superblock iff they stay inside its height.
3165 if blk_col == 0 {
3166 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
3167 }
3168 // Bottom row (and not the leftmost column): they fall in the
3169 // superblock below, which is not decoded yet.
3170 if ((blk_row + 1) << bh_log2) >= sb_mi {
3171 return false;
3172 }
3173 let table = rect_reach_tables(bw, bh).1;
3174 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
3175 }
3176
3177 /// Marks every [`Reach::of`] made until the returned guard drops as being
3178 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
3179 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
3180 /// unaffected: libaom's own comment says vertical rectangles keep their
3181 /// non-vert table, which is what [`Reach::of_rect`] already reads.
3182 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
3183 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
3184 /// can count the sub-block work that partition creates (lane-ab16).
3185 pub(crate) fn in_vert_ab() -> bool {
3186 VERT_AB_PARTITION.with(std::cell::Cell::get)
3187 }
3188
3189 pub(crate) fn vert_ab_partition() -> VertAbGuard {
3190 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
3191 }
3192
3193 /// Neither, which is all a mode that reads no further than its own edges
3194 /// needs.
3195 pub(crate) fn none() -> Self {
3196 Self {
3197 above_right: false,
3198 below_left: false,
3199 }
3200 }
3201
3202 /// `has_top_right` for a block whose transform covers it whole: the top
3203 /// row of a superblock reads into the superblock above, which is decoded;
3204 /// the rightmost column would read into the superblock to the right, which
3205 /// is not; and everything between is the table's to answer.
3206 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3207 let (row, col, per_side) = Self::position(side, x, y, fctx);
3208 if row == 0 {
3209 return true;
3210 }
3211 if col + 1 == per_side {
3212 return false;
3213 }
3214 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
3215 // (the clamp corner-cut that used to live here is gone); sides
3216 // 16/32/64 share row 0 exactly as libaom's tables repeat.
3217 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
3218 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
3219 // -- a reach over-estimate (extra above-right reference pixels),
3220 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
3221 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
3222 // NB: named `table_row`, not `row` -- `row` above is the block's
3223 // position inside the superblock and is what the bit index below
3224 // steps by (a merge that shadowed it desynced every block size).
3225 let table_row = Self::table(side);
3226 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
3227 HAS_TOP_RIGHT_VERT[table_row]
3228 } else {
3229 HAS_TOP_RIGHT[table_row]
3230 };
3231 Self::bit(
3232 table,
3233 (row * Self::table_stride(side) + col) % (table.len() * 8),
3234 )
3235 }
3236
3237 /// `has_bottom_left` for such a block: the leftmost column of a superblock
3238 /// reads into the superblock to its left, which is decoded only as far
3239 /// down as its own bottom; the bottom row would read into the superblock
3240 /// below, which is not decoded at all; and the table answers the rest.
3241 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3242 let (row, col, per_side) = Self::position(side, x, y, fctx);
3243 if col == 0 {
3244 return row * side + side < reach_sb_px(fctx);
3245 }
3246 if row + 1 == per_side {
3247 return false;
3248 }
3249 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
3250 // (the clamp corner-cut that used to live here is gone); sides
3251 // 16/32/64 share row 0 exactly as libaom's tables repeat.
3252 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
3253 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
3254 // -- a reach over-estimate (extra above-right reference pixels),
3255 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
3256 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
3257 // NB: named `table_row`, not `row` -- `row` above is the block's
3258 // position inside the superblock and is what the bit index below
3259 // steps by (a merge that shadowed it desynced every block size).
3260 let table_row = Self::table(side);
3261 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
3262 HAS_BOTTOM_LEFT_VERT[table_row]
3263 } else {
3264 HAS_BOTTOM_LEFT[table_row]
3265 };
3266 Self::bit(
3267 table,
3268 (row * Self::table_stride(side) + col) % (table.len() * 8),
3269 )
3270 }
3271
3272 /// Where a block sits inside its superblock, in blocks of its own size,
3273 /// and how many of them a superblock is across.
3274 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
3275 let sb = reach_sb_px(fctx);
3276 ((y % sb) / side, (x % sb) / side, sb / side)
3277 }
3278
3279 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
3280 /// these tables to its compile-time maximum superblock (128, spec
3281 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
3282 /// size an encode actually uses, so a block's row in the bit index steps
3283 /// by 128 / `side` even though this crate only ever codes a 64
3284 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
3285 /// here instead indexes the wrong bit for every block size but the one
3286 /// where 64 and 128 give the same stride.
3287 fn table_stride(side: usize) -> usize {
3288 128 / side
3289 }
3290
3291 /// Which of the three block sizes the encoder codes a table row is for.
3292 fn table(side: usize) -> usize {
3293 if side == BLOCK {
3294 1
3295 } else if side == 8 {
3296 2
3297 } else if side == 4 {
3298 3
3299 } else {
3300 0
3301 }
3302 }
3303
3304 /// One bit of a table, counting from the low end of its first byte.
3305 fn bit(table: &[u8], index: usize) -> bool {
3306 (table[index / 8] >> (index % 8)) & 1 != 0
3307 }
3308}
3309
3310/// What one symbol costs against a CDF, in bits.
3311/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
3312/// search, the frame header's `allow_warped_motion` and the sequence's
3313/// `enable_warped_motion`, all three together. ON by default since
3314/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
3315/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
3316/// bits -- back off for an A/B on one build.
3317pub(crate) fn warp_on() -> bool {
3318 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
3319 crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
3320 });
3321 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
3322}
3323
3324/// The smallest LEAF an OBMC candidate is offered for, so the census can
3325/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
3326/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
3327/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
3328///
3329/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
3330/// (12 frames, four quantizers, the standing keep table):
3331///
3332/// | min side | film 1080p | film 2160p | screen |
3333/// |---|---|---|---|
3334/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
3335/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
3336/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
3337/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
3338///
3339/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
3340/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
3341/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
3342/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
3343/// that wins the local RD on five blocks in six and loses ladder bytes is
3344/// the `local-RD-on-references` class again, not a missing footprint.
3345///
3346/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
3347/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
3348/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
3349/// loss on the 1080p film became a 0.3-point win and the other two rows went
3350/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
3351/// of the "local win, ladder loss" it was charged with was the rate weight.
3352/// It still does not meet the keep rule (two down, one flat, both columns).
3353/// The tool stays OFF by default; the upgrade path is the price, not the size
3354/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
3355/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
3356/// 1080p film up, i.e. the same disagreement between the two gates).
3357///
3358/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
3359/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
3360/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
3361/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
3362/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
3363/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
3364/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
3365/// the margin's gain are the same bytes. It stays OFF.
3366fn obmc_min_side() -> usize {
3367 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3368 *N.get_or_init(|| {
3369 std::env::var("EC_AV1_OBMC_MIN")
3370 .ok()
3371 .and_then(|v| v.parse().ok())
3372 .unwrap_or(8)
3373 })
3374}
3375
3376/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
3377/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
3378/// same frame-CDF price the coefficients of a non-screen frame are estimated
3379/// with, not the static default table.
3380/// The same price for whichever alphabet the writer will really use for this
3381/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
3382/// (`allow_warped_motion` and at least one warp sample), otherwise the
3383/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
3384/// search pay it, so the alphabet cancels out of a comparison and only its
3385/// per-value spread decides.
3386fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
3387 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
3388 return 0.0;
3389 };
3390 match warp_alphabet {
3391 true => crate::tile::motion_mode_symbol_bits(row, motion),
3392 false => crate::tile::obmc_symbol_bits(row, motion == 1),
3393 }
3394}
3395
3396/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
3397/// candidate, the header's `allow_warped_motion` and the sequence's
3398/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
3399/// native keep table, against the same build with the knob off:
3400///
3401/// | clip | warp on | off |
3402/// |---|---|---|
3403/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
3404/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
3405/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
3406///
3407/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
3408/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
3409/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
3410/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
3411/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
3412/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
3413/// this is a measured loss, not an inert knob. Same shape as the OBMC
3414/// candidate above it (`obmc_min_side`): a local RD win that does not convert
3415/// into ladder bytes.
3416///
3417/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
3418/// because a tool whose gain is local and whose cost is the rate it adds is
3419/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
3420///
3421/// | clip | warp on | off (both at lambda 0.05) |
3422/// |---|---|---|
3423/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
3424/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
3425/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
3426///
3427/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
3428/// column inside 0.1 everywhere -- which reads as a keep rather than the
3429/// 0.7/0.9 loss it was.
3430///
3431/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
3432/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
3433/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
3434/// ran the conformance shape the lambda lane deferred: every warp stream
3435/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
3436/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
3437/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
3438/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
3439/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
3440/// `allow_warped_motion` and `enable_warped_motion` back off together.
3441///
3442/// The WARPED_CAUSAL prediction of one square single-reference block: the
3443/// decoder's own warp-sample walk (`decode::find_samples` +
3444/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
3445/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
3446/// grid -- never a second implementation of any of the three. `None` when the
3447/// block would code no motion_mode symbol at all, when it has no warp sample
3448/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
3449/// or when the projection is not filter-representable (the decoder would then
3450/// predict translationally, so the mode is pure cost).
3451#[allow(clippy::too_many_arguments)]
3452fn warp_prediction(
3453 grid: &MiGrid,
3454 (mi_row, mi_col): (usize, usize),
3455 (mi_rows, mi_cols): (usize, usize),
3456 (x, y): (usize, usize),
3457 side: usize,
3458 mv: (i32, i32),
3459 ref_frame: i8,
3460 ref_planes: [(&[u16], usize, usize, usize); 3],
3461 fctx: &crate::decode::FrameCtx,
3462) -> Option<[Vec<u8>; 3]> {
3463 let n4 = side / 4;
3464 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
3465 return None;
3466 }
3467 let mut samples = crate::decode::find_samples(
3468 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
3469 );
3470 if samples.is_empty() {
3471 return None;
3472 }
3473 if samples.len() > 1 {
3474 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
3475 }
3476 let params = crate::warp::find_projection(
3477 &samples,
3478 side as i32,
3479 side as i32,
3480 mv.1,
3481 mv.0,
3482 mi_row as i32,
3483 mi_col as i32,
3484 )?;
3485 let mut pred = [
3486 vec![0u16; side * side],
3487 vec![0u16; side * side / 4],
3488 vec![0u16; side * side / 4],
3489 ];
3490 // The translational prediction first, exactly as the decoder builds it,
3491 // then the affine one over the planes whose OWN block is at least 8x8
3492 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
3493 // 4x4 chroma stays translational).
3494 for (i, r) in ref_planes.into_iter().enumerate() {
3495 let luma_plane = i == 0;
3496 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
3497 let s = if luma_plane { side } else { side / 2 };
3498 mc::predict(
3499 r.0,
3500 r.1,
3501 r.2,
3502 r.3,
3503 mv_to_q4(px, mv.1, luma_plane),
3504 mv_to_q4(py, mv.0, luma_plane),
3505 s,
3506 s,
3507 &mut pred[i],
3508 fctx,
3509 );
3510 if crate::decode::warp_plane_allowed(s, s) {
3511 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
3512 crate::warp::warp_affine(
3513 &params,
3514 r.0,
3515 r.2 as i32,
3516 r.3 as i32,
3517 r.1 as i32,
3518 &mut pred[i],
3519 px as i32,
3520 py as i32,
3521 cside,
3522 cside,
3523 cside,
3524 sub,
3525 sub,
3526 fctx,
3527 );
3528 }
3529 }
3530 let [py_buf, pu_buf, pv_buf] = pred;
3531 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
3532 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
3533}
3534
3535pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
3536 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
3537 let width = cdf[symbol] - low;
3538 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
3539 // 32769 prices a symbol can carry; the `log2` behind each is computed
3540 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
3541 // profile -- this function is called for every symbol of every candidate
3542 // the RD search prices). Each entry is exactly the expression this used
3543 // to evaluate, so every price is bit-identical.
3544 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
3545 PRICES.get_or_init(|| {
3546 (0..=32768u32)
3547 .map(|w| -(f64::from(w) / 32768.0).log2())
3548 .collect()
3549 })[usize::from(width)]
3550}
3551
3552/// What the tile writer spends to say a block is coded in each of the thirteen
3553/// modes, given the modes of the blocks above it and to its left: the luma mode
3554/// symbol against the CDF those two neighbours pick, the angle delta a
3555/// directional mode carries, and the chroma mode symbol, whose CDF the luma
3556/// mode itself indexes.
3557///
3558/// Without this the search is blind to what a mode costs to name, which is not
3559/// a rounding error: a directional mode on a picture that does not run that way
3560/// is a rate loss the squared error never sees.
3561/// Codes one square of the picture as a single block: searches the luma mode,
3562/// codes both chroma planes DC, and hands back the block and what it cost --
3563/// squared error plus lambda times the bits its symbols spend.
3564/// How many halvings of a `side`-square block's transform the `tx_depth`
3565/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
3566/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
3567fn max_tx_depth(side: usize) -> usize {
3568 match side {
3569 8 => 1,
3570 16 | 32 => 2,
3571 _ => 0,
3572 }
3573}
3574
3575/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
3576/// Priced at context row 0 -- the writer picks the real row from its
3577/// neighbours' transform sizes, which the search has no view of; the term is
3578/// the same for every depth of one block either way, so it only shifts the
3579/// depth-0-versus-split margin, never the ordering between two splits.
3580fn tx_depth_bits(side: usize, depth: usize) -> f64 {
3581 match side {
3582 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
3583 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
3584 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
3585 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
3586 }
3587}
3588
3589/// How many blocks resolved to each `tx_depth`, the fire count that says
3590/// whether the depth search below reaches its candidates at all.
3591static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
3592 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
3593
3594/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
3595/// to its own encode.
3596#[cfg(test)]
3597pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
3598 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
3599}
3600
3601/// How many inter blocks resolved to each var-tx depth (0 = one transform
3602/// over the whole block, 1 = its four halves), the fire count a gate prints
3603/// to see the split search reach its candidates at all. Indexed
3604/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
3605/// says which of the four block classes the split reaches -- the 32x32 root
3606/// and the compound blocks are this lane's two new ones.
3607static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
3608 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
3609
3610/// Whether a 32x32 inter winner searches its own var-tx depth (the four
3611/// 16x16 units against the flat transform) instead of coding depth 0 blind.
3612/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
3613///
3614/// Rejected three times on the bars rows of the native gate (flat to +0.3).
3615/// lane-av1resweep re-judged it on the two REAL film crops at
3616/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
3617/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
3618///
3619/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
3620/// |---|---|---|---|
3621/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
3622/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
3623/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
3624/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
3625/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
3626///
3627/// The bars rows are ~90% zero-intra-cost cells, so the split never had
3628/// residual to reach there -- the tool was being judged on content that
3629/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
3630fn tx32_depth_search() -> bool {
3631 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
3632 crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
3633 });
3634 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
3635}
3636
3637/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
3638/// trial units have to be predicted from BOTH references
3639/// ([`mc_trial_compound`]) or the split would re-predict them by single-
3640/// reference translation, which is not what the decoder reconstructs.
3641/// ON by default (the table on [`tx32_depth_search`]: on real film it is
3642/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
3643/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
3644/// `EC_AV1_COMP_VARTX`.
3645fn compound_var_tx() -> bool {
3646 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
3647 crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
3648 });
3649 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
3650}
3651
3652/// How many 32x32-and-below inter blocks each reference frame won, indexed by
3653/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
3654/// fire count a gate prints to see an extra reference reach a block at all
3655/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
3656/// chosen is a pyramid that costs bytes and buys nothing).
3657static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
3658 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
3659
3660/// Reads [`REF_FRAME_HITS`] and zeroes it.
3661#[cfg(test)]
3662pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
3663 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
3664}
3665
3666/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
3667#[cfg(test)]
3668pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
3669 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
3670}
3671
3672/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
3673/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
3674/// is one flag, depth 1 is a split root plus one unsplit flag per child
3675/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
3676/// or a 4x4 sub-size).
3677fn txfm_split_bits(side: usize, depth: usize) -> f64 {
3678 let max_tx = side.min(64);
3679 let ctx = |tx: usize| {
3680 crate::decode::txfm_partition_ctx_rect(
3681 crate::decode::TXFM_CTX_INIT,
3682 crate::decode::TXFM_CTX_INIT,
3683 side,
3684 tx,
3685 tx,
3686 )
3687 };
3688 if depth == 0 {
3689 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
3690 }
3691 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
3692 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
3693}
3694
3695/// The inter block's own var-tx decision, once its motion vector is settled:
3696/// its residual as ONE transform over the whole block, or as the four
3697/// transforms of half the side the tree's first halving names. The prediction
3698/// is the same motion compensation either way, so the split trial
3699/// re-transforms the identical residual in four pieces -- it wins where four
3700/// small transforms carry a locally varying residual cheaper than one big
3701/// one. Commits the winner into `luma` and hands back its block-coordinate
3702/// levels, the depth the writer codes and the cost the winner adds to (or
3703/// takes off) the caller's already-computed flat cost.
3704///
3705/// Only for a block wholly inside the frame: past the true edge the reader's
3706/// var-tx recursion skips the units that fall outside
3707/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
3708/// leave the residual units this writes unpaired.
3709#[allow(clippy::too_many_arguments)]
3710fn commit_inter_luma(
3711 luma: &mut Plane,
3712 (x, y): (usize, usize),
3713 side: usize,
3714 mv: (i32, i32),
3715 reference: (&[u16], usize, usize, usize),
3716 search: &Search,
3717 flat: &Trial,
3718 skip: bool,
3719 // A COMPOUND winner's second half: the vector and reference planes the
3720 // trial units are blended from ([`mc_trial_compound`], the decoder's own
3721 // `comp_group_idx == 0` average). `None` is the single-reference block.
3722 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
3723 fctx: &crate::decode::FrameCtx,
3724) -> (Vec<i32>, u8, f64) {
3725 let eligible = tx_select()
3726 && tx_select_inter()
3727 && !skip
3728 && side >= 16
3729 && (second.is_none() || compound_var_tx())
3730 && (side != BLOCK || tx32_depth_search())
3731 && x + side <= luma.true_width
3732 && y + side <= luma.true_height;
3733 if !eligible {
3734 luma.commit(x, y, side, flat);
3735 return (flat.levels.clone(), 0, 0.0);
3736 }
3737 let tx = side / 2;
3738 let set = if tx >= 32 {
3739 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
3740 TxbSet::Luma32Inter
3741 } else if tx >= 16 {
3742 TxbSet::Luma16Inter
3743 } else {
3744 TxbSet::Luma8Inter
3745 };
3746 let mut levels = vec![0i32; side * side];
3747 let (mut sse, mut bits) = (0.0, 0.0);
3748 let mut units = Vec::with_capacity(4);
3749 // The split units are smaller than their block, so their `txb_skip`
3750 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
3751 // each unit's own commit publishes what the next one reads, coding order.
3752 luma.ctx.tu_split = true;
3753 for tu_row in 0..2 {
3754 for tu_col in 0..2 {
3755 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
3756 let trial = match second {
3757 Some((mv1, ref1)) => mc_trial_compound(
3758 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
3759 search.base_q_idx, search.deadzone, set, fctx,
3760 ),
3761 None => mc_trial(
3762 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
3763 reference.3, false, search.base_q_idx, search.deadzone, set, fctx,
3764 ),
3765 };
3766 sse += trial.sse;
3767 bits += trial.bits;
3768 for row in 0..tx {
3769 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
3770 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3771 }
3772 units.push((tu_x, tu_y, trial));
3773 }
3774 }
3775 luma.ctx.tu_split = false;
3776 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));
3777 let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0));
3778 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
3779 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
3780 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
3781 // in the leaf row (class `gate-blind-to-feature`).
3782 let counted = side <= BLOCK;
3783 if split_cost < flat_cost {
3784 for (tu_x, tu_y, trial) in &units {
3785 luma.commit(*tu_x, *tu_y, tx, trial);
3786 }
3787 if counted {
3788 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3789 }
3790 return (levels, 1, split_cost - flat_cost);
3791 }
3792 if counted {
3793 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3794 }
3795 luma.commit(x, y, side, flat);
3796 (flat.levels.clone(), 0, 0.0)
3797}
3798
3799/// The largest distinct-colour count a block may hold and still be offered a
3800/// palette candidate at all: past it the k-means quantisation costs more
3801/// error than the map saves rate, and every trial is wasted wall.
3802///
3803/// Swept on the gate's own screen capture (lane-av1pal2, the
3804/// `unswept-decision-constants` class): 32 (the value this lane inherited)
3805/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
3806/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
3807/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
3808/// binds on nothing this content holds. 128 ships: best BD against both
3809/// references and no wall cost at all (6.1s, the same as at 32, because the
3810/// blocks it newly admits are ones the RD then keeps).
3811/// `EC_AV1_PAL_MAXCOLORS`.
3812fn palette_max_colors() -> usize {
3813 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3814 *N.get_or_init(|| {
3815 std::env::var("EC_AV1_PAL_MAXCOLORS")
3816 .ok()
3817 .and_then(|v| v.parse().ok())
3818 .unwrap_or(128)
3819 })
3820}
3821
3822/// The palettes worth trying for one block's luma, in the shape libaom's
3823/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
3824/// distinct colours takes them ALL (the prediction is then exact and the
3825/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
3826/// one-dimensional Lloyd iteration seeded evenly across its range -- both
3827/// offered, because which wins is an RD question the caller answers.
3828/// `block` is `side*side` source samples, row-major.
3829fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
3830 let mut histogram = [0u32; 256];
3831 for &v in block {
3832 histogram[usize::from(v)] += 1;
3833 }
3834 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
3835 if present.len() < 2 {
3836 return Vec::new();
3837 }
3838 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
3839 let mut base = [0u16; 8];
3840 base[..colors.len()].copy_from_slice(colors);
3841 let map = block
3842 .iter()
3843 .map(|&v| {
3844 colors
3845 .iter()
3846 .enumerate()
3847 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
3848 .map(|(i, _)| i as u8)
3849 .expect("a palette holds at least two colours")
3850 })
3851 .collect();
3852 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
3853 };
3854 if present.len() <= 8 {
3855 return vec![exact(&present)];
3856 }
3857 if present.len() > palette_max_colors() {
3858 return Vec::new();
3859 }
3860 let (lo, hi) = (
3861 i32::from(present[0]),
3862 i32::from(present[present.len() - 1]),
3863 );
3864 let mut out = Vec::with_capacity(2);
3865 for n in [8usize, 4] {
3866 // Even seeding across the block's own range, then four Lloyd passes
3867 // over the histogram (256 bins, not `side*side` pixels).
3868 let mut centres: Vec<f64> = (0..n)
3869 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
3870 .collect();
3871 for _ in 0..4 {
3872 let mut sums = vec![0f64; n];
3873 let mut counts = vec![0u32; n];
3874 for (v, &count) in histogram.iter().enumerate() {
3875 if count == 0 {
3876 continue;
3877 }
3878 let k = (0..n)
3879 .min_by(|&a, &b| {
3880 (centres[a] - v as f64)
3881 .abs()
3882 .total_cmp(&(centres[b] - v as f64).abs())
3883 })
3884 .expect("n >= 2");
3885 sums[k] += (v as u32 * count) as f64;
3886 counts[k] += count;
3887 }
3888 for k in 0..n {
3889 if counts[k] > 0 {
3890 centres[k] = sums[k] / f64::from(counts[k]);
3891 }
3892 }
3893 }
3894 let mut colors: Vec<u16> = centres
3895 .iter()
3896 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
3897 .collect();
3898 colors.sort_unstable();
3899 colors.dedup();
3900 if colors.len() >= 2 {
3901 out.push(exact(&colors));
3902 }
3903 }
3904 out
3905}
3906
3907#[allow(clippy::too_many_arguments)]
3908// ---------------------------------------------------------------------------
3909// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
3910// validity). A key frame that detected screen content and finds enough exact
3911// repeats in its own source sets `allow_intrabc`, which the spec forces every
3912// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
3913// its place when the copied blocks pay back the deblock/CDEF/LR the frame
3914// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
3915// ---------------------------------------------------------------------------
3916
3917/// Whether intra block copy is offered at all. **Off by default** --
3918/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
3919/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
3920/// but on the gate's real screen capture it MEASURED WORSE: setting
3921/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
3922/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
3923/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
3924/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
3925/// that detected no screen content.
3926fn intrabc_enabled() -> bool {
3927 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
3928 return forced;
3929 }
3930 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3931 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
3932}
3933
3934thread_local! {
3935 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
3936 /// probe runs both arms in one process, and the suite is one process, so
3937 /// an environment variable cannot separate them (same reason
3938 /// [`SCREEN_FORCE`] exists).
3939 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
3940}
3941
3942#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3943pub(crate) fn force_intrabc(value: Option<bool>) {
3944 INTRABC_FORCE.with(|c| c.set(value));
3945}
3946
3947/// How many of a screen frame's 16x16 blocks must have an exact repeat
3948/// somewhere else in the source before `allow_intrabc` is worth the in-loop
3949/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
3950/// constant class: `probe_intrabc_threshold` measures the arm at several
3951/// values.
3952fn intrabc_pct() -> usize {
3953 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3954 *N.get_or_init(|| {
3955 std::env::var("EC_AV1_INTRABC_PCT")
3956 .ok()
3957 .and_then(|v| v.parse().ok())
3958 .unwrap_or(10)
3959 })
3960}
3961
3962/// The pixel grid intrabc source positions are hashed on
3963/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
3964/// which keeps the block-hash table (and so the search) linear in the frame
3965/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
3966/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
3967/// bilinear interpolation decode.rs applies but this encoder does not.
3968fn intrabc_step() -> usize {
3969 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3970 *N.get_or_init(|| {
3971 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
3972 .ok()
3973 .and_then(|v| v.parse().ok())
3974 .unwrap_or(4);
3975 if n % 2 == 0 { n.max(2) } else { 4 }
3976 })
3977}
3978
3979/// The side of the luma square the block-hash table is keyed on.
3980const IBC_HASH: usize = 16;
3981
3982/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
3983/// the current one the source's bottom-right corner must already be.
3984const INTRABC_DELAY_SB64: i32 = 4;
3985
3986/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
3987fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
3988 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
3989 for row in 0..IBC_HASH {
3990 let base = (y + row) * width + x;
3991 for &v in &plane[base..base + IBC_HASH] {
3992 h ^= u64::from(v);
3993 h = h.wrapping_mul(0x100_0000_01b3);
3994 }
3995 }
3996 h
3997}
3998
3999/// Every `intrabc_step()`-aligned position of `plane` inside
4000/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
4001fn ibc_index(
4002 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
4003 plane: &[u8],
4004 width: usize,
4005 (x0, y0): (usize, usize),
4006 (x1, y1): (usize, usize),
4007) {
4008 let step = intrabc_step();
4009 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
4010 return;
4011 }
4012 let mut y = y0.next_multiple_of(step);
4013 while y + IBC_HASH <= y1 {
4014 let mut x = x0.next_multiple_of(step);
4015 while x + IBC_HASH <= x1 {
4016 table
4017 .entry(ibc_hash(plane, width, x, y))
4018 .or_default()
4019 .push((x as u32, y as u32));
4020 x += step;
4021 }
4022 y += step;
4023 }
4024}
4025
4026/// Whether `screen`-detected source `y` repeats itself enough to be worth
4027/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
4028/// content appears at some other position, against [`intrabc_pct`]. Returns
4029/// the share as well, for the gate's own print.
4030fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
4031 if true_width < 4 * 64 || true_height < 2 * 64 {
4032 return (false, 0.0);
4033 }
4034 let mut table = std::collections::HashMap::new();
4035 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
4036 let (mut total, mut matched) = (0usize, 0usize);
4037 let mut by = 0;
4038 while by + IBC_HASH <= true_height {
4039 let mut bx = 0;
4040 while bx + IBC_HASH <= true_width {
4041 total += 1;
4042 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
4043 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
4044 matched += 1;
4045 }
4046 }
4047 bx += IBC_HASH;
4048 }
4049 by += IBC_HASH;
4050 }
4051 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
4052 (share * 100.0 >= intrabc_pct() as f64, share)
4053}
4054
4055/// One tile's intrabc search state: a block-hash table over the part of the
4056/// tile's own reconstruction that is already final (whole superblock rows --
4057/// the in-loop filters are off on this frame, so a coded superblock row never
4058/// changes again), plus the last DV chosen, which the RD price uses as its
4059/// predictor estimate.
4060struct Ibc {
4061 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
4062 /// source repeats exactly where a lossily coded reconstruction only
4063 /// nearly does, so an exact-match table over the reconstruction finds
4064 /// almost nothing. The candidate is then SCORED against the
4065 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
4066 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
4067 /// The tile's own luma rect, in samples.
4068 tile: (usize, usize, usize, usize),
4069 /// The DV the previous intrabc block of this tile took -- the *estimate*
4070 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
4071 /// against. The writer computes the true predictor off its own mi grid
4072 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
4073 /// a slightly mispriced candidate, never a wrong bitstream.
4074 last_dv: Option<(i32, i32)>,
4075 /// How many blocks took intrabc, and how many hash lookups found at least
4076 /// one valid candidate -- the gate's own fire counts.
4077 hits: usize,
4078 lookups: usize,
4079 found: usize,
4080}
4081
4082impl Ibc {
4083 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
4084 let mut table = std::collections::HashMap::new();
4085 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
4086 Self {
4087 table,
4088 tile,
4089 last_dv: None,
4090 hits: 0,
4091 lookups: 0,
4092 found: 0,
4093 }
4094 }
4095
4096 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
4097 /// (1/8 pel), with this lane's own extra restriction on top: the source
4098 /// must lie entirely in a COMPLETED superblock row, which is exactly the
4099 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
4100 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
4101 /// wavefront's own diagonal) are legal and not searched; the upgrade path
4102 /// is to index the current row's finished superblocks too.
4103 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
4104 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
4105 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
4106 return false;
4107 }
4108 let (tx0, ty0, tx1, ty1) = (
4109 self.tile.0 as i32,
4110 self.tile.1 as i32,
4111 self.tile.2 as i32,
4112 self.tile.3 as i32,
4113 );
4114 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
4115 let (w, h) = (w as i32, h as i32);
4116 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
4117 return false;
4118 }
4119 let active_sb_row = (y as i32 - ty0) >> 6;
4120 let active_sb_col = (x as i32 - tx0) >> 6;
4121 let src_sb_row = (sy + h - 1 - ty0) >> 6;
4122 let src_sb_col = (sx + w - 1 - tx0) >> 6;
4123 // This lane's own restriction (see the doc comment).
4124 if src_sb_row >= active_sb_row {
4125 return false;
4126 }
4127 let total = ((tx1 - tx0 - 1) >> 6) + 1;
4128 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64
4129 {
4130 return false;
4131 }
4132 // libaom's wavefront: only the top-left cone of the frame is legal.
4133 let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row);
4134 src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf
4135 }
4136}
4137
4138/// How many block searches ran, how many found at least one VALID candidate,
4139/// and how many won on rate-distortion -- the hash hit rate a gate prints
4140/// (class `gate-blind-to-feature`: "the search ran" and "the search found
4141/// something" and "the block took it" are three different claims).
4142static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
4143 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
4144
4145impl Drop for Ibc {
4146 fn drop(&mut self) {
4147 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
4148 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
4149 }
4150 }
4151}
4152
4153/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
4154/// its own encode.
4155#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4156pub(crate) fn take_intrabc_search() -> [usize; 3] {
4157 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4158}
4159
4160/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
4161/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
4162/// infers rather than codes.
4163fn dv_component_bits(diff: i32) -> f64 {
4164 let z = diff.unsigned_abs() as i32 - 1;
4165 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
4166 let class = mv_class_of(z);
4167 bits += symbol_bits(&cdf::MV_CLASS, class);
4168 let local = z - mv_class_base(class);
4169 if class == 0 {
4170 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
4171 } else {
4172 let d = local >> 3;
4173 for i in 0..class {
4174 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
4175 }
4176 }
4177 bits
4178}
4179
4180/// What one block vector costs against `pred`, plus the `skip` and
4181/// `use_intrabc` flags the block carries and the ordinary intra block does
4182/// not pay in this currency.
4183fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
4184 let diff = (dv.0 - pred.0, dv.1 - pred.1);
4185 let joint = match (diff.0 != 0, diff.1 != 0) {
4186 (false, false) => 0,
4187 (false, true) => 1,
4188 (true, false) => 2,
4189 (true, true) => 3,
4190 };
4191 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
4192 if diff.0 != 0 {
4193 bits += dv_component_bits(diff.0);
4194 }
4195 if diff.1 != 0 {
4196 bits += dv_component_bits(diff.1);
4197 }
4198 bits
4199}
4200
4201/// The squared error of copying the `side`-square block at `(sx, sy)` of each
4202/// plane's reconstruction onto the source block at `(x, y)`, luma and both
4203/// chroma planes together -- what an intrabc block's whole (residual-free)
4204/// distortion is.
4205fn ibc_sse(
4206 luma: &Plane,
4207 chroma: &[Plane; 2],
4208 (x, y): (usize, usize),
4209 (sx, sy): (usize, usize),
4210 side: usize,
4211) -> f64 {
4212 // Inside the true frame only, for the reason [`Plane::block_sse`] is
4213 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
4214 // how well it copies the padding.
4215 let mut sse = 0.0f64;
4216 let clip = |whole: usize, inside: usize| match edge_sse() {
4217 true => whole.min(inside),
4218 false => whole,
4219 };
4220 let rows = clip(side, luma.true_height.saturating_sub(y));
4221 let cols = clip(side, luma.true_width.saturating_sub(x));
4222 for row in 0..rows {
4223 let src = &luma.source[(y + row) * luma.width + x..][..cols];
4224 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
4225 for (&s, &r) in src.iter().zip(rec) {
4226 let d = f64::from(i32::from(s) - i32::from(r));
4227 sse += d * d;
4228 }
4229 }
4230 let half = side / 2;
4231 for plane in chroma {
4232 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
4233 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
4234 for row in 0..rows {
4235 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
4236 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
4237 for (&s, &r) in src.iter().zip(rec) {
4238 let d = f64::from(i32::from(s) - i32::from(r));
4239 sse += d * d;
4240 }
4241 }
4242 }
4243 sse
4244}
4245
4246/// Copies the `side`-square block at `(sx, sy)` of each plane's
4247/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
4248/// since it carries no residual (`skip`). Full-pel in both planes by
4249/// construction ([`intrabc_step`] keeps every DV even), which is what makes
4250/// this a plain copy where decode.rs runs the bilinear kernel over the same
4251/// samples.
4252fn ibc_commit(
4253 luma: &mut Plane,
4254 chroma: &mut [Plane; 2],
4255 (x, y): (usize, usize),
4256 (sx, sy): (usize, usize),
4257 side: usize,
4258) {
4259 for row in 0..side {
4260 let from = (sy + row) * luma.width + sx;
4261 let to = (y + row) * luma.width + x;
4262 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
4263 luma.reconstruction[to..to + side].copy_from_slice(&copied);
4264 }
4265 let half = side / 2;
4266 for plane in chroma {
4267 for row in 0..half {
4268 let from = (sy / 2 + row) * plane.width + sx / 2;
4269 let to = (y / 2 + row) * plane.width + x / 2;
4270 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
4271 plane.reconstruction[to..to + half].copy_from_slice(&copied);
4272 }
4273 plane.commit_ctx_zero(x / 2, y / 2, half);
4274 }
4275 luma.commit_ctx_zero(x, y, side);
4276}
4277
4278/// Searches this block's own DV: every hash-table position whose 16x16 luma
4279/// square equals the block's source square, plus the previous block's DV as a
4280/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
4281/// the winning `(dv, cost)`, or `None` when nothing valid was found.
4282fn ibc_search(
4283 ibc: &mut Ibc,
4284 luma: &Plane,
4285 chroma: &[Plane; 2],
4286 (x, y): (usize, usize),
4287 side: usize,
4288 lambda: f64,
4289) -> Option<((i32, i32), f64, (usize, usize))> {
4290 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
4291 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
4292 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
4293 let dv = (
4294 (sy as i32 - y as i32) * 8,
4295 (sx as i32 - x as i32) * 8,
4296 );
4297 if !ibc.dv_valid(x, y, side, side, dv) {
4298 return;
4299 }
4300 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
4301 if best.as_ref().is_none_or(|b| cost < b.1) {
4302 *best = Some((dv, cost, (sx, sy)));
4303 }
4304 };
4305 ibc.lookups += 1;
4306 let key = ibc_hash(luma.source, luma.width, x, y);
4307 // The table is filled in raster order, so the entries BEFORE this block's
4308 // own position are exactly the already-coded ones -- and the nearest of
4309 // them costs the fewest DV bits. Walking backwards from the block's own
4310 // slot is what makes the search look up-and-left; taking the newest
4311 // entries outright only ever finds candidates below and to the right,
4312 // every one of which `dv_valid` rejects.
4313 let hits: Vec<(u32, u32)> = ibc
4314 .table
4315 .get(&key)
4316 .map(|h| {
4317 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
4318 h[..end].iter().rev().take(32).copied().collect()
4319 })
4320 .unwrap_or_default();
4321 for (hx, hy) in hits {
4322 consider(&*ibc, hx as usize, hy as usize, &mut best);
4323 }
4324 if let Some(dv) = ibc.last_dv {
4325 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
4326 if sx >= 0 && sy >= 0 {
4327 consider(&*ibc, sx as usize, sy as usize, &mut best);
4328 }
4329 }
4330 if best.is_some() {
4331 ibc.found += 1;
4332 }
4333 best
4334}
4335
4336fn code_square(
4337 luma: &mut Plane,
4338 chroma: &mut [Plane; 2],
4339 (x, y): (usize, usize),
4340 side: usize,
4341 search: &Search,
4342 mode_bits: &[f64; 13],
4343 // The frame header's `tx_mode == TxMode::Select`: the block then searches
4344 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
4345 // transform over its whole side.
4346 tx_select: bool,
4347 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
4348 // header did not set `allow_intrabc`.
4349 ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx,
4350) -> (BlockCoeffs, f64) {
4351 let (luma_set, chroma_set) = if side == SUPERBLOCK {
4352 // A whole superblock coded as ONE intra block (lane-i64): one
4353 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
4354 // `code_from_prediction` hands back, and one TX_32X32 per chroma
4355 // plane -- the same three sets the key frame writer's
4356 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
4357 // uses (`search_skip_64`).
4358 (TxbSet::Luma64, TxbSet::Chroma32)
4359 } else if side == BLOCK {
4360 (TxbSet::Luma32, TxbSet::Chroma16)
4361 } else if side == 8 {
4362 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
4363 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
4364 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
4365 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
4366 // (this branch is still unreached), so leaving `Chroma8` here would
4367 // silently wire the wrong table the moment one does; `Chroma4` is
4368 // what a real caller needs.
4369 (TxbSet::Luma8, TxbSet::Chroma4)
4370 } else {
4371 (TxbSet::Luma16, TxbSet::Chroma8)
4372 };
4373 let at = At {
4374 x,
4375 y,
4376 side,
4377 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
4378 set: luma_set,
4379 };
4380 let (mut luma_coeffs, mode, angle_delta, mut cost) =
4381 luma.search_block(at, search, mode_bits, fctx);
4382 // The depth search runs on the mode the whole-block transform picked --
4383 // libaom's own ordering, and the reason it costs one extra pass per depth
4384 // rather than one per (mode, depth) pair.
4385 let mut tx_depth = 0u8;
4386 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
4387 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
4388 // pays that zero exactly as a 32x32's depth search makes it pay
4389 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
4390 // below hands the root a symbol for free.
4391 if tx_select && side == SUPERBLOCK {
4392 cost += search.lambda * tx_depth_bits(side, 0);
4393 }
4394 if tx_select && max_tx_depth(side) > 0 {
4395 let mut best = (
4396 cost + search.lambda * tx_depth_bits(side, 0),
4397 0usize,
4398 luma.snapshot(x, y, side),
4399 luma_coeffs,
4400 );
4401 for depth in 1..=max_tx_depth(side) {
4402 let (levels, sse, bits) = luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
4403 let cost_d = sse
4404 + search.lambda
4405 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));
4406 if cost_d < best.0 {
4407 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
4408 }
4409 }
4410 luma.restore(x, y, side, &best.2);
4411 cost = best.0;
4412 tx_depth = best.1 as u8;
4413 luma_coeffs = best.3;
4414 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4415 }
4416 // The palette candidate is priced against the mode the luma search (and
4417 // its transform-depth search) already settled on, so a block only takes
4418 // one when it beats the best ordinary intra coding of the same pixels.
4419 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
4420 // prediction is the colour map, not the DC of its neighbours.
4421 let mut mode = mode;
4422 let mut angle_delta = angle_delta;
4423 let mut palette = None;
4424 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
4425 let source: Vec<u8> = (y..y + side)
4426 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
4427 .collect();
4428 let kept = luma.snapshot(x, y, side);
4429 for pal in palette_candidates(&source) {
4430 let n = usize::from(pal.size);
4431 let prediction: Vec<u8> = pal
4432 .map
4433 .iter()
4434 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
4435 .collect();
4436 let trial = luma.code_from_prediction(
4437 x,
4438 y,
4439 side,
4440 &prediction,
4441 false,
4442 search.base_q_idx,
4443 search.deadzone,
4444 luma_set,
4445 );
4446 let cost_p = trial.sse
4447 + search.lambda
4448 * (trial.bits
4449 + mode_bits[DC_PRED as usize]
4450 + crate::tile::palette_bits(&pal, side)
4451 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
4452 if cost_p < cost {
4453 cost = cost_p;
4454 mode = DC_PRED as u8;
4455 angle_delta = 0;
4456 tx_depth = 0;
4457 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
4458 luma.commit(x, y, side, &trial);
4459 palette = Some(pal);
4460 }
4461 }
4462 if palette.is_none() {
4463 luma.restore(x, y, side, &kept);
4464 }
4465 }
4466
4467 // The five recursive filter-intra modes (spec 5.11.14), priced against
4468 // whatever the mode, transform-depth and palette searches settled on --
4469 // the same "one candidate loop after the incumbent is known" shape the
4470 // palette above uses. A block that takes one is `DC_PRED` with no palette
4471 // by construction (`av1_filter_intra_allowed`), and its luma transform
4472 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
4473 //
4474 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
4475 // depth the ordinary intra search runs, each unit predicting recursively
4476 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
4477 // arm), so a block whose ordinary winner wanted a split transform is
4478 // compared against a filter arm that may split too.
4479 //
4480 // Measured (native BD table, lane-fitu): searching the depths on EVERY
4481 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
4482 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
4483 // locally cheaper reconstruction that the film rows go on to predict from
4484 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
4485 // content is where it pays, and a non-screen frame keeps the depth-0-only
4486 // arm, byte for byte.
4487 let mut filter_intra: Option<u8> = None;
4488 if filter_intra_on()
4489 && palette.is_none()
4490 && let Some(class) = crate::decode::filter_intra_size_class(side)
4491 {
4492 let row = &cdf::FILTER_INTRA[class];
4493 // With the sequence bit on, EVERY `DC_PRED` block without a luma
4494 // palette carries the flag, so the incumbent pays its zero before the
4495 // comparison -- otherwise the candidate is charged a bit the block
4496 // spends either way (class `price-the-narrowing-not-the-table`).
4497 if mode == DC_PRED {
4498 cost += search.lambda * symbol_bits(row, 0);
4499 }
4500 let one_bits = symbol_bits(row, 1);
4501 let kept = luma.snapshot(x, y, side);
4502 let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 };
4503 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
4504 for fi in 0..5u8 {
4505 for depth in 0..=max_depth {
4506 let (levels, sse, bits) =
4507 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
4508 let cost_f = sse
4509 + search.lambda
4510 * (bits
4511 + mode_bits[DC_PRED as usize]
4512 + one_bits
4513 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
4514 + if tx_select { tx_depth_bits(side, depth) } else { 0.0 });
4515 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
4516 best = Some((
4517 cost_f,
4518 fi,
4519 depth,
4520 luma.snapshot(x, y, side),
4521 coeffs(&levels, side),
4522 ));
4523 }
4524 }
4525 }
4526 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
4527 cost = cost_f;
4528 mode = DC_PRED;
4529 angle_delta = 0;
4530 tx_depth = depth as u8;
4531 luma_coeffs = levels;
4532 luma.restore(x, y, side, &snapshot);
4533 filter_intra = Some(fi);
4534 } else {
4535 luma.restore(x, y, side, &kept);
4536 }
4537 }
4538
4539 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
4540 // planes; what it costs still counts towards the partition decision.
4541 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
4542 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
4543 cost += chroma_cost;
4544
4545 // The intrabc arm is priced against the WHOLE block -- luma and both
4546 // chroma planes, residual-free -- so it is compared after the chroma
4547 // search has added its own cost, not against the luma decision alone.
4548 if let Some(ibc) = ibc {
4549 if let Some((dv, cost_ibc, src)) =
4550 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
4551 {
4552 if cost_ibc < cost {
4553 ibc_commit(luma, chroma, (x, y), src, side);
4554 ibc.last_dv = Some(dv);
4555 ibc.hits += 1;
4556 return (
4557 BlockCoeffs {
4558 skip: true,
4559 dv: Some(dv),
4560 ..BlockCoeffs::default()
4561 },
4562 cost_ibc,
4563 );
4564 }
4565 }
4566 }
4567 (
4568 BlockCoeffs {
4569 u,
4570 v,
4571 luma: luma_coeffs,
4572 mode,
4573 uv_mode,
4574 tx_depth,
4575 palette,
4576 palette_uv,
4577 filter_intra,
4578 cfl_alphas,
4579 angle_delta_y: angle_delta as i8,
4580 ..BlockCoeffs::default()
4581 },
4582 cost,
4583 )
4584}
4585
4586/// The chroma modes the search offers, and the only ones it may offer: each
4587/// predicts from the row directly above and the column directly to the left
4588/// and nothing further, so none of them needs the above-right/below-left
4589/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
4590/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
4591/// reconstruction and its own alpha syntax; both are left out here.
4592const CHROMA_MODES: [u8; 7] = [
4593 DC_PRED,
4594 V_PRED,
4595 H_PRED,
4596 SMOOTH_PRED,
4597 SMOOTH_V_PRED,
4598 SMOOTH_H_PRED,
4599 PAETH_PRED,
4600];
4601
4602/// The thirteen intra mode names, for the chroma fire count's print.
4603#[cfg(test)]
4604const UV_MODE_NAMES: [&str; 14] = [
4605 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
4606 "SMOOTH_H", "PAETH", "CFL",
4607];
4608
4609/// How many blocks each chroma mode has won, indexed by the mode itself --
4610/// the fire count that says whether the search below reaches its candidates
4611/// at all (the `gate-blind-to-feature` class), printed once per gate run.
4612static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
4613 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
4614
4615/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
4616/// won, summed over both chroma planes -- the alpha histogram the gate prints
4617/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
4618/// magnitude only is a search that never left its first candidate).
4619static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
4620 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
4621
4622/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
4623/// zero on a CfL block", `1..=16` the magnitudes.
4624#[cfg(test)]
4625pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
4626 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
4627}
4628
4629/// How many directional luma blocks won at each `angle_delta_y`, indexed
4630/// `delta + 3` -- the histogram that says whether the refinement below ever
4631/// leaves zero (`gate-blind-to-feature`).
4632static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
4633 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
4634
4635/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
4636#[cfg(test)]
4637pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
4638 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
4639}
4640
4641/// Whether the luma search refines a directional winner's `angle_delta_y`
4642/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
4643fn angle_delta_on() -> bool {
4644 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4645 crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")
4646 });
4647 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
4648}
4649
4650/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
4651/// switches it off, which is how the lane measured its own on/off pair).
4652fn cfl_on() -> bool {
4653 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4654 crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0")
4655 });
4656 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
4657}
4658
4659/// Whether the intra search offers the five recursive filter-intra modes at
4660/// all, and with them whether the sequence header sets `enable_filter_intra`
4661/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
4662/// its own on/off pair -- and how every byte pin written before it still
4663/// reproduces). It is also a speed lever: on at preset 0, off above it.
4664pub(crate) fn filter_intra_on() -> bool {
4665 #[cfg(test)]
4666 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
4667 return forced;
4668 }
4669 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4670 crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0")
4671 });
4672 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
4673}
4674
4675/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
4676/// to its own encode.
4677#[cfg(test)]
4678pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
4679 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
4680}
4681
4682/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
4683/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
4684/// Returns each plane's levels, the mode, and what the pair cost (squared
4685/// error plus lambda times bits, the same currency the luma search speaks).
4686///
4687/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
4688/// which is what the luma mode decision was taken against, so what a
4689/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
4690/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
4691/// writer then has to code.
4692#[allow(clippy::too_many_arguments)]
4693/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
4694/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
4695/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
4696/// trials all seven, as before this lever.
4697///
4698/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
4699/// the search's largest trial population by far -- seven modes times two
4700/// planes for every intra block, against 3.7 luma trials -- and the RD
4701/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
4702/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
4703fn chroma_top_k() -> Option<usize> {
4704 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
4705 crate::envflags::var("EC_AV1_CHROMA_K")
4706 .ok()
4707 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
4708 });
4709 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
4710}
4711
4712/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
4713/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
4714/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
4715/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
4716/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
4717/// BD swings by about a point in either direction as near-tie chroma modes
4718/// flip, which is the measurement's own sensitivity, not a trend: nothing
4719/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
4720/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
4721/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
4722/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
4723pub(crate) const CHROMA_TOP_K: Option<usize> = None;
4724
4725fn search_chroma(
4726 chroma: &mut [Plane; 2],
4727 // The luma plane's RECONSTRUCTION under this block, already committed by
4728 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
4729 luma: &Plane,
4730 (x, y): (usize, usize),
4731 side: usize,
4732 set: TxbSet,
4733 search: &Search,
4734 luma_mode: u8,
4735 fctx: &crate::decode::FrameCtx,
4736) -> (
4737 [Vec<Coeff>; 2],
4738 u8,
4739 f64,
4740 Option<crate::tile::PaletteUv>,
4741 Option<(i32, i32)>,
4742) {
4743 let at = At {
4744 x: x / 2,
4745 y: y / 2,
4746 side: side / 2,
4747 reach: Reach::none(),
4748 set,
4749 };
4750 // The census's cheap proxy for a chroma mode: the SAD of its prediction
4751 // summed over both planes, ranked by the same rule the luma histogram
4752 // uses. Only built under `EC_AV1_CENSUS`.
4753 // The SAD of each mode's prediction, summed over both planes -- the
4754 // census's ranking rule, and what [`chroma_top_k`] prunes by.
4755 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
4756 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
4757 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
4758 u.iter()
4759 .zip(v.iter())
4760 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
4761 .collect()
4762 };
4763 let modes: Vec<u8> = match chroma_top_k() {
4764 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
4765 _ => CHROMA_MODES.to_vec(),
4766 };
4767 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
4768 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
4769 let ranking: Vec<(f64, u8)> = if census_on() {
4770 sad_scores(chroma)
4771 } else {
4772 Vec::new()
4773 };
4774 census_add(2, 1);
4775 census_add(3, modes.len());
4776 let mut best: Option<(f64, u8, Trial, Trial)> = None;
4777 for mode in modes {
4778 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
4779 if (V_PRED..=D67_PRED).contains(&mode) {
4780 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
4781 }
4782 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
4783 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
4784 // chroma of a 64x64 block is `DCT_DCT` whatever
4785 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
4786 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
4787 // points.
4788 let tx_type = if at.side >= 32 {
4789 TxType::DctDct
4790 } else {
4791 crate::decode::default_intra_tx_type(mode)
4792 };
4793 let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
4794 let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
4795 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
4796 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
4797 best = Some((cost, mode, u, v));
4798 }
4799 }
4800 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
4801 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
4802 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
4803 // what keeps `u_colors` ascending and distinct the way
4804 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
4805 // each cluster's own mean, since the colour-index map is SHARED by the
4806 // two planes. Priced against the best ordinary chroma mode above, so a
4807 // block only takes one when it beats it; a palette block's chroma mode is
4808 // `UV_DC_PRED` by construction.
4809 let mut palette_uv = None;
4810 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
4811 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
4812 let plane_source = |p: &Plane| -> Vec<u8> {
4813 (at.y..at.y + at.side)
4814 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
4815 .collect()
4816 };
4817 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
4818 for pal in palette_candidates(&u_source) {
4819 let n = usize::from(pal.size);
4820 // V's base colour per cluster: the mean of the samples the shared
4821 // map assigns to it (an empty cluster cannot happen -- every
4822 // colour `palette_candidates` returns is some pixel's nearest).
4823 let mut sums = [0u32; 8];
4824 let mut counts = [0u32; 8];
4825 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
4826 let k = usize::from(i).min(n - 1);
4827 sums[k] += u32::from(sample);
4828 counts[k] += 1;
4829 }
4830 let mut v_colors = [0u16; 8];
4831 for k in 0..n {
4832 v_colors[k] = if counts[k] > 0 {
4833 ((sums[k] + counts[k] / 2) / counts[k]) as u16
4834 } else {
4835 0
4836 };
4837 }
4838 let candidate = crate::tile::PaletteUv {
4839 size: pal.size,
4840 u_colors: pal.colors,
4841 v_colors,
4842 map: pal.map,
4843 };
4844 let predict = |colors: &[u16; 8]| -> Vec<u8> {
4845 candidate
4846 .map
4847 .iter()
4848 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
4849 .collect()
4850 };
4851 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
4852 let u_trial = chroma[0].code_from_prediction(
4853 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
4854 );
4855 let v_trial = chroma[1].code_from_prediction(
4856 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
4857 );
4858 let cost_p = u_trial.sse
4859 + v_trial.sse
4860 + search.lambda
4861 * (u_trial.bits
4862 + v_trial.bits
4863 + crate::tile::palette_uv_bits(&candidate, side));
4864 if cost_p < cost {
4865 cost = cost_p;
4866 mode = DC_PRED;
4867 u = u_trial;
4868 v = v_trial;
4869 palette_uv = Some(candidate);
4870 }
4871 }
4872 }
4873 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
4874 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
4875 // nudges every sample by `alpha_q3` times the block's subsampled,
4876 // average-subtracted luma reconstruction. Offered only where
4877 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
4878 // and priced against the best ordinary chroma mode above, palette
4879 // included, so a block only takes it when it beats both.
4880 let mut cfl_alphas = None;
4881 if side <= 32 && cfl_on() {
4882 // The AC signal, through the decoder's own
4883 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
4884 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
4885 i32::from(luma.reconstruction[ly * luma.width + lx])
4886 });
4887 let dc_prediction = |plane: &Plane| -> Vec<u8> {
4888 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
4889 let (above, left, corner) =
4890 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
4891 let mut prediction = vec![0u8; at.side * at.side];
4892 intra_predict_u8(
4893 DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
4894 fctx,
4895 );
4896 prediction
4897 };
4898 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
4899 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
4900 // add the residual -- which is what [`Plane::code_from_prediction`]
4901 // does with what this returns.
4902 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
4903 base.iter()
4904 .zip(ac.iter())
4905 .map(|(&b, &a)| {
4906 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
4907 })
4908 .collect()
4909 };
4910 // The least-squares alpha, then its two neighbours: minimising
4911 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
4912 // dot-product ratio, and the quantised optimum is one of the two
4913 // integers around it (the clamp and the Q6 rounding are what the SSE
4914 // check below re-decides). libaom sweeps all sixteen magnitudes under
4915 // full RD; three predictions per plane buy nearly the same alpha for a
4916 // thirtieth of the search.
4917 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
4918 let (mut num, mut den) = (0.0f64, 0.0f64);
4919 for row in 0..at.side {
4920 for col in 0..at.side {
4921 let i = row * at.side + col;
4922 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
4923 - f64::from(base[i]);
4924 num += d * f64::from(ac[i]);
4925 den += f64::from(ac[i]) * f64::from(ac[i]);
4926 }
4927 }
4928 if den == 0.0 {
4929 return 0;
4930 }
4931 let ideal = 64.0 * num / den;
4932 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
4933 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
4934 let alpha = alpha.clamp(-16, 16) as i32;
4935 if alpha == 0 {
4936 continue;
4937 }
4938 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
4939 if sse < best.0 {
4940 best = (sse, alpha);
4941 }
4942 }
4943 best.1
4944 };
4945 let picked = [
4946 pick_alpha(&chroma[0], &bases[0]),
4947 pick_alpha(&chroma[1], &bases[1]),
4948 ];
4949 if picked != [0, 0] {
4950 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
4951 let trial = |plane_idx: usize, alpha: i32| -> Trial {
4952 let prediction = if alpha == 0 {
4953 bases[plane_idx].clone()
4954 } else {
4955 apply(&bases[plane_idx], alpha)
4956 };
4957 chroma[plane_idx].code_from_prediction(
4958 at.x,
4959 at.y,
4960 at.side,
4961 &prediction,
4962 false,
4963 search.base_q_idx,
4964 search.deadzone,
4965 set,
4966 )
4967 };
4968 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
4969 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
4970 let combos: [(i32, i32); 3] = [
4971 (picked[0], picked[1]),
4972 (picked[0], 0),
4973 (0, picked[1]),
4974 ];
4975 for &(alpha_u, alpha_v) in &combos {
4976 if (alpha_u, alpha_v) == (0, 0) {
4977 continue;
4978 }
4979 let cu = trial(0, alpha_u);
4980 let cv = trial(1, alpha_v);
4981 let bits =
4982 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
4983 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
4984 if cost_cfl < cost {
4985 cost = cost_cfl;
4986 mode = crate::tile::UV_CFL_PRED as u8;
4987 u = cu;
4988 v = cv;
4989 palette_uv = None;
4990 cfl_alphas = Some((alpha_u, alpha_v));
4991 }
4992 }
4993 }
4994 }
4995 if let Some((alpha_u, alpha_v)) = cfl_alphas {
4996 for alpha in [alpha_u, alpha_v] {
4997 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
4998 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4999 }
5000 }
5001 if census_on() {
5002 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
5003 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5004 }
5005 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5006 chroma[0].commit(at.x, at.y, at.side, &u);
5007 chroma[1].commit(at.x, at.y, at.side, &v);
5008 (
5009 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
5010 mode,
5011 cost,
5012 palette_uv,
5013 cfl_alphas,
5014 )
5015}
5016
5017/// Codes one leaf of a straddling quadrant as whichever costs least of intra
5018/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
5019/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
5020/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
5021/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
5022/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
5023/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
5024/// attempted here: these leaves only ever fill the sliver of real content a
5025/// true edge lands in the middle of a larger block, not a leaf worth a full
5026/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
5027/// (see `write_inter_frame_leaf`'s doc comment).
5028#[allow(clippy::too_many_arguments)]
5029/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
5030/// as [`code_square_inter`] wants them: empty on a frame that codes no
5031/// `reference_select`, or when the leaf compound candidates are switched off.
5032/// One helper because THREE leaf call sites need it -- the split quadrants
5033/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
5034/// `&[]` and so coded no compound block anywhere along the frame's true edge.
5035#[allow(clippy::too_many_arguments)]
5036fn leaf_compound_stacks<'a>(
5037 grid: &MiGrid,
5038 mi_row: usize,
5039 mi_col: usize,
5040 bw4: usize,
5041 bh4: usize,
5042 mi_cols: usize,
5043 mi_rows: usize,
5044 reference_select: bool,
5045 golden: Option<&'a Picture>,
5046 altref: Option<&'a Picture>,
5047) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
5048 if !(reference_select && leaf_compound()) {
5049 return Vec::new();
5050 }
5051 [
5052 (crate::mvstack::GOLDEN_FRAME, golden),
5053 (crate::mvstack::ALTREF_FRAME, altref),
5054 ]
5055 .into_iter()
5056 .filter_map(|(r, pic)| {
5057 pic.map(|p| {
5058 (
5059 r,
5060 p,
5061 crate::mvstack::find_mv_stack_compound(
5062 grid, mi_row, mi_col, bw4, bh4,
5063 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
5064 grid.sign_bias_table(), &[(0, 0); 7], None,
5065 ),
5066 )
5067 })
5068 })
5069 .collect()
5070}
5071
5072/// The OBMC prediction of one square single-reference block: this block's own
5073/// translation prediction (`mc::predict`) with every bordering above/left
5074/// neighbour blended into the overlap strips by the DECODER's own plan and
5075/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
5076/// the search prices is what a decoder reconstructs -- never a second
5077/// implementation of the blend. `None` when the block has no overlappable
5078/// neighbour at all (the writer would then code no `motion_mode` symbol) or
5079/// when the plan cannot be built (a neighbour naming a reference this encode
5080/// does not hold).
5081#[allow(clippy::too_many_arguments)]
5082fn obmc_prediction(
5083 grid: &MiGrid,
5084 (mi_row, mi_col): (usize, usize),
5085 (mi_rows, mi_cols): (usize, usize),
5086 (x, y): (usize, usize),
5087 side: usize,
5088 mv: (i32, i32),
5089 refs: &[Option<&Picture>; 8],
5090 // This block's OWN reference planes, luma then both chroma, each as
5091 // (samples, stride, true width, true height).
5092 ref_planes: [(&[u16], usize, usize, usize); 3],
5093 frame_width: usize,
5094 fctx: &crate::decode::FrameCtx,
5095) -> Option<[Vec<u8>; 3]> {
5096 let n4 = side / 4;
5097 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
5098 return None;
5099 }
5100 let refpix = crate::decode::RefPix::ready(*refs);
5101 let plan = crate::decode::obmc_plan(
5102 grid,
5103 &[],
5104 &[],
5105 mi_row,
5106 mi_col,
5107 n4,
5108 n4,
5109 mi_rows,
5110 mi_cols,
5111 side,
5112 side,
5113 side,
5114 side / 2,
5115 x,
5116 y,
5117 x / 2,
5118 y / 2,
5119 &refpix,
5120 Some(mc::InterpFilterKind::Regular),
5121 frame_width,
5122 )
5123 .ok()?;
5124 let mut pred = [
5125 vec![0u16; side * side],
5126 vec![0u16; side * side / 4],
5127 vec![0u16; side * side / 4],
5128 ];
5129 for (i, r) in ref_planes.into_iter().enumerate() {
5130 let luma_plane = i == 0;
5131 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
5132 let s = if luma_plane { side } else { side / 2 };
5133 mc::predict(
5134 r.0,
5135 r.1,
5136 r.2,
5137 r.3,
5138 mv_to_q4(px, mv.1, luma_plane),
5139 mv_to_q4(py, mv.0, luma_plane),
5140 s,
5141 s,
5142 &mut pred[i],
5143 fctx,
5144 );
5145 }
5146 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
5147 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
5148 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
5149 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
5150}
5151
5152fn code_square_inter(
5153 luma: &mut Plane,
5154 chroma: &mut [Plane; 2],
5155 (x, y): (usize, usize),
5156 side: usize,
5157 search: &Search,
5158 mode_bits: &[f64; 13],
5159 reference: &Picture,
5160 stack: &MvStack,
5161 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
5162 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
5163 // `reference_select`, and at the straddling call sites).
5164 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
5165 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
5166 // (`record_mi`, in the writer's own coding order) and this leaf's place in
5167 // it -- what the OBMC candidate's eligibility walk and neighbour plan
5168 // read, the same state the tile writer reads when it codes the leaf's
5169 // `motion_mode` symbol.
5170 grid: &MiGrid,
5171 (mi_row, mi_col): (usize, usize),
5172 (mi_rows, mi_cols): (usize, usize),
5173 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
5174 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
5175 refs: &[Option<&Picture>; 8],
5176 fctx: &crate::decode::FrameCtx,
5177) -> (BlockCoeffs, f64) {
5178 let (intra_block, intra_cost) =
5179 code_square(
5180 luma,
5181 chroma,
5182 (x, y),
5183 side,
5184 search,
5185 mode_bits,
5186 tx_select() && tx_select_inter(),
5187 None,
5188 fctx,
5189 );
5190 let luma_set = if side == 8 {
5191 TxbSet::Luma8Inter
5192 } else {
5193 TxbSet::Luma16Inter
5194 };
5195 let chroma_set = if side == 8 {
5196 TxbSet::Chroma4
5197 } else {
5198 TxbSet::Chroma8
5199 };
5200
5201 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
5202 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
5203 let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
5204 + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
5205 + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
5206 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
5207 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
5208 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
5209
5210 let mv = stack.nearest_mv;
5211 let ref_luma = (
5212 &reference.y,
5213 reference.width,
5214 luma.true_width,
5215 luma.true_height,
5216 );
5217 let ref_u = (
5218 &reference.u,
5219 reference.width / 2,
5220 chroma[0].true_width,
5221 chroma[0].true_height,
5222 );
5223 let ref_v = (
5224 &reference.v,
5225 reference.width / 2,
5226 chroma[1].true_width,
5227 chroma[1].true_height,
5228 );
5229 let luma_trial = mc_trial(
5230 luma,
5231 x,
5232 y,
5233 side,
5234 mv,
5235 true,
5236 ref_luma.0,
5237 ref_luma.1,
5238 ref_luma.2,
5239 ref_luma.3,
5240 false,
5241 search.base_q_idx,
5242 search.deadzone,
5243 luma_set, fctx,
5244 );
5245 let u = mc_trial(
5246 &chroma[0],
5247 x / 2,
5248 y / 2,
5249 side / 2,
5250 mv,
5251 false,
5252 ref_u.0,
5253 ref_u.1,
5254 ref_u.2,
5255 ref_u.3,
5256 false,
5257 search.base_q_idx,
5258 search.deadzone,
5259 chroma_set, fctx,
5260 );
5261 let v = mc_trial(
5262 &chroma[1],
5263 x / 2,
5264 y / 2,
5265 side / 2,
5266 mv,
5267 false,
5268 ref_v.0,
5269 ref_v.1,
5270 ref_v.2,
5271 ref_v.3,
5272 false,
5273 search.base_q_idx,
5274 search.deadzone,
5275 chroma_set, fctx,
5276 );
5277 let skip = luma_trial.levels.iter().all(|&l| l == 0)
5278 && u.levels.iter().all(|&l| l == 0)
5279 && v.levels.iter().all(|&l| l == 0);
5280 let inter_cost = luma_trial.sse
5281 + u.sse
5282 + v.sse
5283 + search.lambda
5284 * (skip_bits(skip)
5285 + intra_inter_bits(true)
5286 + single_ref_bits
5287 + mode_bits_inter
5288 + if skip {
5289 0.0
5290 } else {
5291 luma_trial.bits + u.bits + v.bits
5292 });
5293
5294 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
5295 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
5296 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
5297 // scan's own coverage already reached as far) but a real gap at 4-mi
5298 // leaf geometry. r3 ported the extended scan and, while proving it a
5299 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
5300 // `mvstack.rs`), found and fixed a second bug the extended scan's
5301 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
5302 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
5303 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
5304 // regardless of whether it also casts a ref-frame-matching vote) --
5305 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
5306 // branches), which is what made 8-mi geometry a true no-op instead of
5307 // one that only held when every neighbour happened to be inter.
5308 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
5309 // only ever took the stack's NEARESTMV candidate or went intra, so a
5310 // 32x32 block splitting because its four quarters MOVE differently could
5311 // not code the movement it split for. Same candidate `search_inter_block`
5312 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
5313 // a vector the residual syntax can name -- at this leaf's own side.
5314 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
5315 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
5316 // re-price below can hand it back as the winner's own mode info.
5317 let nearest_info = InterInfo {
5318 ref1: None,
5319 mv1: (0, 0),
5320 ref_frame: crate::mvstack::LAST_FRAME,
5321 mode: InterMode::NearestMv,
5322 mv,
5323 ref_mv_idx: 0,
5324 };
5325 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
5326 // syntax, apart from its residual: the OBMC candidate re-prices the same
5327 // syntax against a different prediction, so both sides of that comparison
5328 // carry it.
5329 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
5330 // This leaf's own `NEWMV` vector, kept whether or not it won the
5331 // single-reference comparison: it seeds the compound half-new candidate
5332 // below, exactly as `search_inter_block` seeds its own from the searches
5333 // it already ran.
5334 let mut searched_new: Option<(i32, i32)> = None;
5335 // What that search cost, kept for the second reference's own early-out
5336 // below (`None` when this leaf ran no search at all).
5337 let mut searched_new_cost: Option<f64> = None;
5338 let source_block = luma.source_block(x, y, side);
5339 if leaf_new_mv() {
5340 let (seeds, seed_n) = mv_seeds(stack);
5341 let found = motion::search(
5342 ref_luma.0,
5343 ref_luma.1,
5344 ref_luma.2,
5345 ref_luma.3,
5346 &source_block,
5347 x,
5348 y,
5349 side,
5350 side,
5351 stack.pred_mv,
5352 &seeds[..seed_n],
5353 search.lambda, fctx,
5354 1,
5355 );
5356 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
5357 searched_new_cost = Some(found.cost);
5358 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {
5359 searched_new = Some(new_mv);
5360 // Same reuse as `search_inter_block`: a NEWMV equal to the
5361 // stack's NEARESTMV is the same three trials, already run above.
5362 let (luma_new, u_new, v_new) = if new_mv == mv {
5363 (luma_trial.clone(), u.clone(), v.clone())
5364 } else {
5365 (
5366 mc_trial(
5367 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
5368 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
5369 ),
5370 mc_trial(
5371 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
5372 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
5373 fctx,
5374 ),
5375 mc_trial(
5376 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
5377 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
5378 fctx,
5379 ),
5380 )
5381 };
5382 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
5383 && u_new.levels.iter().all(|&l| l == 0)
5384 && v_new.levels.iter().all(|&l| l == 0);
5385 let drl_bits = if stack.entries.len() > 1 {
5386 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
5387 } else {
5388 0.0
5389 };
5390 let cost_new = luma_new.sse
5391 + u_new.sse
5392 + v_new.sse
5393 + search.lambda
5394 * (skip_bits(skip_new)
5395 + intra_inter_bits(true)
5396 + single_ref_bits
5397 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
5398 + drl_bits
5399 + mv_bits
5400 + if skip_new {
5401 0.0
5402 } else {
5403 luma_new.bits + u_new.bits + v_new.bits
5404 });
5405 if cost_new < best.0 {
5406 single_syntax = intra_inter_bits(true)
5407 + single_ref_bits
5408 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
5409 + drl_bits
5410 + mv_bits;
5411 best = (
5412 cost_new,
5413 Some((
5414 luma_new,
5415 u_new,
5416 v_new,
5417 skip_new,
5418 InterInfo {
5419 ref1: None,
5420 mv1: (0, 0),
5421 ref_frame: crate::mvstack::LAST_FRAME,
5422 mode: InterMode::NewMv,
5423 mv: new_mv,
5424 ref_mv_idx: 0,
5425 },
5426 )),
5427 );
5428 }
5429 }
5430 }
5431
5432 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
5433 // `search_inter_block` prices for a whole 32x32 block:
5434 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
5435 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
5436 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
5437 // too. Priced with the same static-CDF approximation, plus the
5438 // compound-only syntax the writer emits.
5439 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
5440 let (ref1, g) = (*ref1, *g);
5441 let uni =
5442 (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1);
5443 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
5444 + if uni {
5445 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
5446 + symbol_bits(&cdf::COMP_REF[0][0], 0)
5447 + symbol_bits(&cdf::COMP_REF[0][1], 0)
5448 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
5449 } else {
5450 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
5451 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
5452 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
5453 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
5454 };
5455 let mode_ctx =
5456 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
5457 let mode_bits_of =
5458 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
5459 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
5460 (
5461 cstack.nearest_mv,
5462 mode_bits_of(0),
5463 InterInfo {
5464 ref_frame: crate::mvstack::LAST_FRAME,
5465 mode: InterMode::NearestNearestMv,
5466 mv: cstack.nearest_mv.0,
5467 mv1: cstack.nearest_mv.1,
5468 ref1: Some(ref1),
5469 ref_mv_idx: 0,
5470 },
5471 ),
5472 (
5473 ((0, 0), (0, 0)),
5474 mode_bits_of(6),
5475 InterInfo {
5476 ref_frame: crate::mvstack::LAST_FRAME,
5477 mode: InterMode::GlobalGlobalMv,
5478 mv: (0, 0),
5479 mv1: (0, 0),
5480 ref1: Some(ref1),
5481 ref_mv_idx: 0,
5482 },
5483 ),
5484 ];
5485 // Every compound MV residual here is priced against compound stack
5486 // entry 0, which is what `assign_compound_mv` predicts from at
5487 // `ref_mv_idx = 0` -- so it is also what the second-reference search
5488 // below seeds from and rounds to, and no candidate it finds can then
5489 // fail `mv_residual_bits`.
5490 let cbase = cstack
5491 .entries
5492 .first()
5493 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
5494 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
5495 // it a leaf could only name a stack vector for the second half, and
5496 // screen capture showed the consequence: every leaf compound block
5497 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
5498 // extra-reference `NEWMV`, when this reference's own
5499 // `NEAREST_NEARESTMV` vector already prices `margin` times better
5500 // than the `LAST` search of this same leaf did -- one candidate
5501 // evaluation standing in for a whole search.
5502 let margin = leaf_second_new_margin();
5503 let mut second_new: Option<(i32, i32)> = None;
5504 if leaf_second_new_mv() {
5505 let skip = margin > 0.0
5506 && searched_new_cost.is_some_and(|last| {
5507 motion::cost_at(
5508 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
5509 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
5510 ) * margin
5511 <= last
5512 });
5513 if !skip {
5514 let mut seeds = [(0, 0); 4];
5515 let mut seed_n = 1;
5516 for e in cstack.entries.iter().take(3) {
5517 seeds[seed_n] = e.mv1;
5518 seed_n += 1;
5519 }
5520 let found = motion::search(
5521 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
5522 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
5523 );
5524 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
5525 }
5526 }
5527 if let Some(new_mv) = searched_new {
5528 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
5529 ccands.push((
5530 (new_mv, cstack.nearest_mv.1),
5531 mode_bits_of(3) + b0,
5532 InterInfo {
5533 ref_frame: crate::mvstack::LAST_FRAME,
5534 mode: InterMode::NewNearestMv,
5535 mv: new_mv,
5536 mv1: cstack.nearest_mv.1,
5537 ref1: Some(ref1),
5538 ref_mv_idx: 0,
5539 },
5540 ));
5541 }
5542 }
5543 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
5544 // searches this leaf ran, each residual priced against `cbase`.
5545 if let Some(mv1) = second_new {
5546 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
5547 ccands.push((
5548 (cstack.nearest_mv.0, mv1),
5549 mode_bits_of(2) + b1,
5550 InterInfo {
5551 ref_frame: crate::mvstack::LAST_FRAME,
5552 mode: InterMode::NearestNewMv,
5553 mv: cstack.nearest_mv.0,
5554 mv1,
5555 ref1: Some(ref1),
5556 ref_mv_idx: 0,
5557 },
5558 ));
5559 if let Some((new_mv, b0)) =
5560 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
5561 {
5562 ccands.push((
5563 (new_mv, mv1),
5564 mode_bits_of(7) + b0 + b1,
5565 InterInfo {
5566 ref_frame: crate::mvstack::LAST_FRAME,
5567 mode: InterMode::NewNewMv,
5568 mv: new_mv,
5569 mv1,
5570 ref1: Some(ref1),
5571 ref_mv_idx: 0,
5572 },
5573 ));
5574 }
5575 }
5576 }
5577 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
5578 ccands.dedup_by_key(|c| c.0);
5579 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
5580 let g_u = (
5581 g.u.as_slice(),
5582 g.width / 2,
5583 chroma[0].true_width,
5584 chroma[0].true_height,
5585 );
5586 let g_v = (
5587 g.v.as_slice(),
5588 g.width / 2,
5589 chroma[1].true_width,
5590 chroma[1].true_height,
5591 );
5592 for (mvs, bits, info) in ccands {
5593 let luma_c = mc_trial_compound(
5594 luma, x, y, side, mvs, true,
5595 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
5596 search.base_q_idx, search.deadzone, luma_set, fctx,
5597 );
5598 let u_c = mc_trial_compound(
5599 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
5600 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
5601 search.base_q_idx, search.deadzone, chroma_set, fctx,
5602 );
5603 let v_c = mc_trial_compound(
5604 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
5605 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
5606 search.base_q_idx, search.deadzone, chroma_set, fctx,
5607 );
5608 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
5609 && u_c.levels.iter().all(|&l| l == 0)
5610 && v_c.levels.iter().all(|&l| l == 0);
5611 let cost_c = luma_c.sse
5612 + u_c.sse
5613 + v_c.sse
5614 + search.lambda
5615 * (skip_bits(skip_c)
5616 + intra_inter_bits(true)
5617 + bits
5618 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
5619 if cost_c < best.0 {
5620 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
5621 }
5622 }
5623 }
5624
5625 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
5626 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
5627 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
5628 // the writer codes no symbol for one. The prediction is the decoder's own
5629 // plan and blend over the neighbours this leaf's `grid` already carries
5630 // (published by `record_mi` in the writer's coding order), so the
5631 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
5632 // offered this only at 32x32, which is not where libaom cashes its OBMC
5633 // gain.
5634 let mut motion_won = 0u8;
5635 let single = match &best.1 {
5636 None => Some(nearest_info),
5637 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
5638 Some(_) => None,
5639 };
5640 if let Some(info) = single.filter(|i| {
5641 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
5642 && i.ref_frame == crate::mvstack::LAST_FRAME
5643 }) {
5644 let planes = [
5645 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
5646 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
5647 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
5648 ];
5649 // Which alphabet this block's writer will code the symbol against
5650 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
5651 // 3-symbol one only under `allow_warped_motion` and at least one warp
5652 // sample. Mirrored here so the candidates are priced against the
5653 // table the tile really narrows.
5654 let warp_alphabet = warp_on()
5655 && crate::decode::num_proj_ref(
5656 grid,
5657 mi_row,
5658 mi_col,
5659 side / 4,
5660 side / 4,
5661 mi_cols,
5662 mi_rows,
5663 info.ref_frame,
5664 fctx,
5665 ) >= 1;
5666 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
5667 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
5668 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
5669 if let Some(pred) = obmc_prediction(
5670 grid,
5671 (mi_row, mi_col),
5672 (mi_rows, mi_cols),
5673 (x, y),
5674 side,
5675 info.mv,
5676 refs,
5677 planes,
5678 reference.width,
5679 fctx,
5680 ) {
5681 candidates.push((1, pred));
5682 }
5683 }
5684 if warp_alphabet {
5685 if let Some(pred) = warp_prediction(
5686 grid,
5687 (mi_row, mi_col),
5688 (mi_rows, mi_cols),
5689 (x, y),
5690 side,
5691 info.mv,
5692 info.ref_frame,
5693 planes,
5694 fctx,
5695 ) {
5696 candidates.push((2, pred));
5697 }
5698 }
5699 for (motion, pred) in candidates {
5700 let luma_o = luma.code_from_prediction(
5701 x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
5702 );
5703 let u_o = chroma[0].code_from_prediction(
5704 x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
5705 chroma_set,
5706 );
5707 let v_o = chroma[1].code_from_prediction(
5708 x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
5709 chroma_set,
5710 );
5711 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
5712 && u_o.levels.iter().all(|&l| l == 0)
5713 && v_o.levels.iter().all(|&l| l == 0);
5714 let cost_o = luma_o.sse
5715 + u_o.sse
5716 + v_o.sse
5717 + search.lambda
5718 * (skip_bits(skip_o)
5719 + single_syntax
5720 + mm(motion)
5721 + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
5722 // The incumbent pays the motion_mode symbol IT would code, so
5723 // both sides of the comparison carry that syntax.
5724 if cost_o < best.0 + search.lambda * mm(motion_won) {
5725 motion_won = motion;
5726 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
5727 }
5728 }
5729 }
5730
5731 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
5732 if cost < intra_cost {
5733 // A compound winner commits the flat trial it was priced from:
5734 // `commit_inter_luma`'s var-tx trial set is single-reference
5735 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
5736 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
5737 // predicting each half-side trial from BOTH references, verified
5738 // byte-identical to this when its split is disabled) and MEASURED
5739 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
5740 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
5741 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
5742 // compound block's residual is small enough that the four extra
5743 // per-unit txb_skip/eob symbols cost more ladder bytes than this
5744 // encoder's static-CDF estimate prices them at, so the local RD
5745 // win does not convert. lane-av1txbits REBUILT it on top of a
5746 // search that prices against the tables the frame is really
5747 // written with (`tile::arm_pricing_cdfs`, the estimate error on
5748 // these very blocks measured down from +31% to +3%) and measured
5749 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
5750 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
5751 // same build without it. The static-CDF estimate was NOT what
5752 // held the compound var-tx trial back. The flat trial stays.
5753 // An OBMC winner commits the flat trial too: `commit_inter_luma`
5754 // re-predicts each var-tx unit by plain translation, which is not
5755 // the prediction this candidate was priced from.
5756 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
5757 // 0.05 (both rejections above were measured at 0.1, the weight
5758 // the lambda lane showed was 2x too heavy): a compound winner is
5759 // offered the same var-tx split, its units predicted from BOTH
5760 // references (`mc_trial_compound`). RE-MEASURED native: film
5761 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
5762 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
5763 // one row 0.2 down, two flat, short of the two-down-one-flat keep
5764 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
5765 // rather than change the default on a single 0.2 row. It fires:
5766 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
5767 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
5768 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
5769 // 1.3/1.2 down there, which is where the upgrade path is if this
5770 // is picked up again.
5771 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
5772 refs[r as usize].map(|g| {
5773 (
5774 info.mv1,
5775 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
5776 )
5777 })
5778 });
5779 let (levels, tx_depth, dcost) = if motion_won != 0
5780 || (info.ref1.is_some() && second.is_none())
5781 {
5782 luma.commit(x, y, side, &luma_new);
5783 (luma_new.levels.clone(), 0, 0.0)
5784 } else {
5785 commit_inter_luma(
5786 luma, (x, y), side, info.mv,
5787 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
5788 search, &luma_new, skip_new, second, fctx,
5789 )
5790 };
5791 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
5792 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
5793 return (
5794 BlockCoeffs {
5795 angle_delta_y: 0,
5796 cfl_alphas: None,
5797 filter_intra: None,
5798 luma: coeffs(&levels, side),
5799 u: coeffs(&u_new.levels, side / 2),
5800 v: coeffs(&v_new.levels, side / 2),
5801 mode: DC_PRED as u8,
5802 uv_mode: DC_PRED,
5803 skip: skip_new,
5804 eight: None,
5805 dv: None,
5806 palette: None,
5807 palette_uv: None,
5808 tx_depth,
5809 inter: Some(info),
5810 motion_mode: motion_won,
5811 },
5812 cost + dcost,
5813 );
5814 }
5815 }
5816
5817 census_add(8, 1);
5818 if skip {
5819 census_add(10, 1);
5820 }
5821 if inter_cost >= intra_cost {
5822 census_add(9, 1);
5823 }
5824 if inter_cost < intra_cost {
5825 let (levels, tx_depth, dcost) = commit_inter_luma(
5826 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, None, fctx,
5827 );
5828 chroma[0].commit(x / 2, y / 2, side / 2, &u);
5829 chroma[1].commit(x / 2, y / 2, side / 2, &v);
5830 (BlockCoeffs {
5831 angle_delta_y: 0,
5832 cfl_alphas: None,
5833 filter_intra: None,
5834 luma: coeffs(&levels, side),
5835 u: coeffs(&u.levels, side / 2),
5836 v: coeffs(&v.levels, side / 2),
5837 mode: DC_PRED as u8,
5838 uv_mode: DC_PRED,
5839 skip,
5840 eight: None,
5841 dv: None,
5842 palette: None,
5843 palette_uv: None,
5844 tx_depth,
5845 motion_mode: 0,
5846 inter: Some(InterInfo {
5847 ref1: None,
5848 mv1: (0, 0),
5849 ref_frame: crate::mvstack::LAST_FRAME,
5850 mode: InterMode::NearestMv,
5851 mv,
5852 ref_mv_idx: 0,
5853 }),
5854 }, inter_cost + dcost)
5855 } else {
5856 (intra_block, intra_cost)
5857 }
5858}
5859
5860/// Publishes one coded inter-frame block into the `mi` grid the next block's
5861/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
5862/// block casts no vote but is still a coded cell (see `code_square_inter`'s
5863/// note on `processed_rows`/`processed_cols`).
5864fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option<InterInfo>) {
5865 let info = match inter {
5866 Some(info) => MiInfo {
5867 is_inter: true,
5868 ref_frame: info.ref_frame,
5869 // A COMPOUND block votes with BOTH of its references and both of
5870 // its vectors, exactly as the tile writer publishes it: recording
5871 // a compound block as a single-reference one here left the
5872 // encoder's own grid disagreeing with the writer's from the first
5873 // compound block on, so every later stack it searched against was
5874 // not the stack the decoder derives.
5875 ref_frame1: info.ref1.unwrap_or(NO_REF1),
5876 mv1: mv16(info.mv1),
5877 mv: mv16(info.mv),
5878 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
5879 // side, compound modes 2/3/7 on the other.
5880 is_new_mv: matches!(
5881 info.mode,
5882 InterMode::NewMv
5883 | InterMode::NewNewMv
5884 | InterMode::NearestNewMv
5885 | InterMode::NewNearestMv
5886 ),
5887 size,
5888 size_h: size,
5889 is_global_mv0: false,
5890 is_global_mv1: false,
5891 },
5892 None => MiInfo {
5893 is_inter: false,
5894 ref_frame: -1,
5895 ref_frame1: NO_REF1,
5896 mv1: (0, 0),
5897 mv: (0, 0),
5898 is_new_mv: false,
5899 size,
5900 size_h: size,
5901 is_global_mv0: false,
5902 is_global_mv1: false,
5903 },
5904 };
5905 for dr in 0..usize::from(size) {
5906 for dc in 0..usize::from(size) {
5907 grid.set(mi_row + dr, mi_col + dc, info);
5908 }
5909 }
5910}
5911
5912/// The reconstructed samples one 32x32 square covers in all three planes, so
5913/// that a partition trial can be undone.
5914/// One square of a plane, row-major, the inverse of [`Plane::restore`].
5915///
5916/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
5917/// which allocated and freed a `Vec` per row of every block it copied --
5918/// `Plane::snapshot` runs once per partition trial.
5919fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
5920 let mut out = vec![0u8; side * side];
5921 for row in 0..side {
5922 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
5923 }
5924 out
5925}
5926
5927fn snapshot(
5928 luma: &Plane,
5929 chroma: &[Plane; 2],
5930 (x, y): (usize, usize),
5931 side: usize,
5932) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
5933 [
5934 luma.snapshot(x, y, side),
5935 chroma[0].snapshot(x / 2, y / 2, side / 2),
5936 chroma[1].snapshot(x / 2, y / 2, side / 2),
5937 ]
5938}
5939
5940/// Puts such a snapshot back.
5941fn restore(
5942 luma: &mut Plane,
5943 chroma: &mut [Plane; 2],
5944 (x, y): (usize, usize),
5945 side: usize,
5946 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
5947) {
5948 luma.restore(x, y, side, &saved[0]);
5949 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
5950 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
5951}
5952
5953/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
5954/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
5955/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
5956/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
5957/// rule shared with the key-frame path, not a second one that could diverge.
5958fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
5959 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
5960 let dc_entry = dc_pos.map(|i| scored.remove(i));
5961 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
5962 scored.truncate(if dc_entry.is_some() {
5963 top_k.saturating_sub(1)
5964 } else {
5965 top_k
5966 });
5967 if let Some(dc_entry) = dc_entry {
5968 scored.push(dc_entry);
5969 }
5970 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
5971 modes.iter().copied().filter(|m| keep.contains(m)).collect()
5972}
5973
5974fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
5975 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
5976 [INTRA_MODE_CTX[usize::from(left_mode)]];
5977 std::array::from_fn(|mode| {
5978 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
5979 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
5980 } else {
5981 0.0
5982 };
5983 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
5984 })
5985}
5986
5987/// What the luma mode search picks between, and under what terms.
5988#[derive(Clone, Copy)]
5989struct Search<'a> {
5990 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
5991 /// luma search then offers a palette candidate beside the intra modes.
5992 screen: bool,
5993 base_q_idx: u8,
5994 deadzone: f64,
5995 lambda: f64,
5996 modes: &'a [u8],
5997 /// How many of `modes` the full RD trial (forward transform, quantize,
5998 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
5999 /// pre-pass on the prediction residual alone plus DC (always kept, since
6000 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
6001 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
6002 /// mode through full RD, unchanged from before this lever.
6003 top_k: Option<usize>,
6004}
6005
6006/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged
6007/// (the default, until a lever's quality gate justifies pruning by default);
6008/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers.
6009fn prune_top_k() -> Option<usize> {
6010 #[cfg(test)]
6011 {
6012 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
6013 return k;
6014 }
6015 }
6016 let swept = std::env::var("EC_AV1_PRUNE_K")
6017 .ok()
6018 .and_then(|v| v.parse::<usize>().ok());
6019 match swept {
6020 Some(k) if cfg!(test) => Some(k),
6021 _ => crate::speed::at(&crate::speed::PRUNE_K),
6022 }
6023}
6024
6025// A per-thread override [`prune_top_k`] checks first, so one test can sweep
6026// `top_k` in-process without mutating the environment (forbidden here --
6027// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
6028#[cfg(test)]
6029thread_local! {
6030 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
6031 const { std::cell::Cell::new(None) };
6032}
6033
6034#[cfg(test)]
6035fn set_test_top_k_override(value: Option<usize>) {
6036 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
6037}
6038
6039/// The default: unpruned, thirteen full trials per block, same as before this
6040/// lever. Set from the sweep in the lane report if the quality gate clears it.
6041pub(crate) const PRUNE_TOP_K: Option<usize> = None;
6042
6043/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
6044/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
6045/// quality gates were measured separately and may land on different
6046/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
6047/// [`EC_AV1_PRUNE_K`] or the key-frame path.
6048fn prune_top_k_inter() -> Option<usize> {
6049 #[cfg(test)]
6050 {
6051 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
6052 return k;
6053 }
6054 }
6055 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
6056 .ok()
6057 .and_then(|v| v.parse::<usize>().ok());
6058 match swept {
6059 Some(k) if cfg!(test) => Some(k),
6060 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
6061 }
6062}
6063
6064// A per-thread override [`prune_top_k_inter`] checks first, same reason as
6065// [`TEST_TOP_K_OVERRIDE`].
6066#[cfg(test)]
6067thread_local! {
6068 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
6069 const { std::cell::Cell::new(None) };
6070}
6071
6072#[cfg(test)]
6073fn set_test_top_k_override_inter(value: Option<usize>) {
6074 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
6075}
6076
6077/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
6078/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
6079/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
6080/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
6081/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
6082/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
6083/// pruning them costs less quality here.
6084pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
6085
6086// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
6087// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
6088// inter frame's cost can be attributed to a bucket without changing what
6089// the search actually does. Index: 0 = whole-call time inside
6090// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
6091// [`crate::mc::predict`] (every call, from the motion search's own
6092// candidates and from a committed inter block's final prediction alike),
6093// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
6094#[cfg(test)]
6095thread_local! {
6096 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
6097 std::cell::Cell::new(0),
6098 std::cell::Cell::new(0),
6099 std::cell::Cell::new(0),
6100 std::cell::Cell::new(0),
6101 ];
6102}
6103
6104/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
6105/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
6106/// per transform trial and per `mc::predict` call whether or not anyone was
6107/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
6108/// The clock is now read only when [`crate::par::stage_times`] is on, which
6109/// is what prints the breakdown in the first place.
6110#[cfg(test)]
6111pub(crate) fn stage_start() -> Option<std::time::Instant> {
6112 crate::par::stage_times().then(std::time::Instant::now)
6113}
6114
6115#[cfg(test)]
6116pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
6117 if let Some(t) = t {
6118 stage_add(bucket, t.elapsed());
6119 }
6120}
6121
6122#[cfg(test)]
6123pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
6124 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
6125}
6126
6127#[cfg(test)]
6128fn stage_reset() {
6129 crate::par::set_stage_times(true);
6130 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
6131}
6132
6133#[cfg(test)]
6134fn stage_read() -> [std::time::Duration; 4] {
6135 crate::par::set_stage_times(false);
6136 STAGE_NS.with(|c| {
6137 c.each_ref()
6138 .map(|cell| std::time::Duration::from_nanos(cell.get()))
6139 })
6140}
6141
6142/// One mode's coding of one block, before it is committed.
6143#[derive(Clone)]
6144struct Trial {
6145 levels: Vec<i32>,
6146 reconstruction: Vec<u8>,
6147 sse: f64,
6148 bits: f64,
6149}
6150
6151/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
6152/// of a 64-point transform that is actually coded (everything outside it is
6153/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
6154fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
6155 let mut out = vec![0i32; to * to];
6156 for row in 0..to {
6157 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
6158 }
6159 out
6160}
6161
6162/// The non-zero levels of a block, as the tile writer takes them.
6163fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
6164 levels
6165 .iter()
6166 .enumerate()
6167 .filter(|&(_, &level)| level != 0)
6168 .map(|(i, &level)| Coeff {
6169 row: (i / side) as u8,
6170 col: (i % side) as u8,
6171 level,
6172 })
6173 .collect()
6174}
6175
6176thread_local! {
6177 /// The tile grid the next frame is coded with, as `(TileColsLog2,
6178 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
6179 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
6180 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
6181 /// one tile per frame, what every caller that never arms anything gets
6182 /// and what every stream this crate wrote before tiles existed carries.
6183 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
6184}
6185
6186/// Arms this thread's next frame encodes with a tile grid (log2 counts).
6187pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
6188 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
6189}
6190
6191fn armed_tiles() -> (u32, u32) {
6192 let armed = TILE_LOG2.with(std::cell::Cell::get);
6193 if armed != (0, 0) {
6194 return armed;
6195 }
6196 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
6197 // (which codes through `encode_sequence`, not the facade) can measure what
6198 // a tile grid costs without a knob of its own -- same shape as
6199 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
6200 match std::env::var("EC_AV1_TILES").ok() {
6201 Some(v) if cfg!(test) => {
6202 let mut f = v.split(':');
6203 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
6204 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
6205 (cols, rows)
6206 }
6207 _ => armed,
6208 }
6209}
6210
6211/// Codes a frame's `tiles` tiles, each entirely on its own (see
6212/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
6213/// the crate's own pool, and hands back their payloads in tile order plus
6214/// whatever `code` returned for tile `store` -- the CDF state
6215/// `context_update_tile_id` names. The result cannot depend on the thread
6216/// count: each job writes one tile from the frame's own starting tables into
6217/// its own slot.
6218fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
6219where
6220 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
6221{
6222 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
6223 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
6224 let threads = crate::par::tile_threads().min(tiles);
6225 let mut slots: Vec<Slot> = Vec::new();
6226 if threads <= 1 {
6227 for index in 0..tiles {
6228 slots.push(Some(code(index)));
6229 }
6230 } else {
6231 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
6232 {
6233 let batch = crate::par::Batch::new("ec-av1-tile");
6234 for (from, to) in crate::par::bands(tiles, threads) {
6235 let done = &done;
6236 let code = &code;
6237 batch.submit(move || {
6238 for index in from..to {
6239 let coded = code(index);
6240 done.lock().expect("tile slots")[index] = Some(coded);
6241 }
6242 });
6243 }
6244 }
6245 slots = done.into_inner().expect("tile slots");
6246 }
6247 let mut out = Vec::with_capacity(tiles);
6248 let mut stored = None;
6249 for (index, slot) in slots.into_iter().enumerate() {
6250 let (bytes, cdfs) = slot.expect("every tile was coded")?;
6251 if index == store {
6252 stored = cdfs;
6253 }
6254 out.push(bytes);
6255 }
6256 Ok((out, stored))
6257}
6258
6259/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
6260/// workers, and returns the results in tile order. The counterpart of
6261/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
6262/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
6263/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
6264/// availability is already tile-relative (`clip_planes_to_tile`,
6265/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
6266/// other tiles have run -- gated by
6267/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
6268/// covers the search as well as the write.
6269///
6270/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
6271/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
6272/// does it for the decoder's filter bands.
6273fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
6274where
6275 T: Send,
6276 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
6277{
6278 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
6279 let threads = crate::par::tile_threads().min(tiles);
6280 if threads <= 1 {
6281 return (0..tiles).map(|index| job(index, fctx)).collect();
6282 }
6283 type Slot<T> = Option<Result<T>>;
6284 let done: std::sync::Mutex<Vec<Slot<T>>> =
6285 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
6286 {
6287 let batch = crate::par::Batch::new("ec-av1-tile-search");
6288 for (from, to) in crate::par::bands(tiles, threads) {
6289 let done = &done;
6290 let job = &job;
6291 let ctx = crate::decode::filter_ctx_copy(fctx);
6292 batch.submit(move || {
6293 for index in from..to {
6294 let searched = job(index, &ctx);
6295 done.lock().expect("tile slots")[index] = Some(searched);
6296 }
6297 });
6298 }
6299 }
6300 done.into_inner()
6301 .expect("tile slots")
6302 .into_iter()
6303 .map(|slot| slot.expect("every tile was searched"))
6304 .collect()
6305}
6306
6307/// One tile job's own copy of a plane: the frame's source, a blank
6308/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
6309/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
6310/// of the frame's reconstruction because a tile's prediction never reads a
6311/// sample outside its own rectangle, and every sample inside it is written
6312/// before it is read.
6313fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
6314 Plane {
6315 source,
6316 reconstruction: vec![128; source.len()],
6317 width,
6318 height,
6319 true_width,
6320 true_height,
6321 tile_x0: 0,
6322 tile_y0: 0,
6323 tile_x1: width,
6324 tile_y1: height,
6325 ctx: CoefCtxMap::default(),
6326 }
6327}
6328
6329/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
6330/// the frame's plane, through the [`crate::par::Shared`] every job holds.
6331///
6332/// corner-cut: the disjointness that makes the aliasing sound is the caller's
6333/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
6334/// rectangles partition it -- checked end-to-end by
6335/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
6336/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
6337/// row-range `split_at_mut` plumbing through `Plane`, which would have to
6338/// thread an origin offset through every prediction and transform call site
6339/// for the same bytes.
6340#[allow(unsafe_code)]
6341fn copy_rect(
6342 dst: crate::par::Shared<'_, Vec<u8>>,
6343 src: &[u8],
6344 stride: usize,
6345 x0: usize,
6346 y0: usize,
6347 x1: usize,
6348 y1: usize,
6349) {
6350 // SAFETY: this job touches only its own tile rectangle (see above).
6351 let dst = unsafe { dst.get() };
6352 for y in y0..y1 {
6353 let (a, b) = (y * stride + x0, y * stride + x1);
6354 dst[a..b].copy_from_slice(&src[a..b]);
6355 }
6356}
6357
6358/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
6359/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
6360/// tables the frame stores (spec 7.20), which is what
6361/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
6362/// below publish.
6363fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
6364 ec_av1_syntax::TileInfo {
6365 uniform_spacing: true,
6366 cols: layout.cols(),
6367 rows: layout.rows(),
6368 cols_log2: layout.cols_log2,
6369 rows_log2: layout.rows_log2,
6370 mi_col_starts: layout.mi_col_starts(),
6371 mi_row_starts: layout.mi_row_starts(),
6372 context_update_tile_id: layout.largest_tile() as u32,
6373 tile_size_bytes,
6374 }
6375}
6376
6377/// Clips the three planes' intra edge reads to `rect`, the tile the
6378/// superblock about to be searched belongs to (the encoder side of the
6379/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
6380/// raster order -- which is a linear extension of every tile's own coding
6381/// order, so a block still only ever predicts from samples already
6382/// reconstructed -- and only availability is tile-relative.
6383fn clip_planes_to_tile(
6384 luma: &mut Plane<'_>,
6385 chroma: &mut [Plane<'_>; 2],
6386 rect: crate::tile::TileRect,
6387) {
6388 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
6389 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
6390 luma.set_tile(x0, y0, x1, y1);
6391 for plane in chroma.iter_mut() {
6392 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
6393 }
6394}
6395
6396/// Encodes one picture as a key frame.
6397///
6398/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
6399/// picks its coefficient CDFs from one of four q contexts by that index.
6400/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
6401/// smaller values trade fidelity for rate.
6402///
6403/// The picture may be any even width and height: the encoder pads it by edge
6404/// replication to a whole number of 32x32 blocks internally, and the frame it
6405/// writes crops back to the picture's own size (`render_width`/
6406/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
6407/// own size, never the padded one.
6408///
6409/// # Errors
6410/// Returns an error when the picture's width or height is zero or odd, or
6411/// when its planes are not 4:2:0 of that size.
6412/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
6413/// stream. The per-frame decode state this needs lives for exactly this call.
6414///
6415/// # Errors
6416/// Returns an error under the same conditions
6417/// [`encode_key_frame_with_modes`] does.
6418pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
6419 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
6420}
6421
6422/// [`encode_key_frame`] with the per-block intra modes given rather than
6423/// searched.
6424///
6425/// # Errors
6426/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
6427/// is empty, or when a block's coefficients do not fit the coded frame.
6428pub fn encode_key_frame_with_modes(
6429 picture: &Picture,
6430 base_q_idx: u8,
6431 deadzone: f64,
6432 modes: &[u8],
6433) -> Result<Encoded> {
6434 encode_key_frame_with_modes_with_ctx(
6435 picture,
6436 base_q_idx,
6437 deadzone,
6438 modes,
6439 &crate::decode::FrameCtx::new(),
6440 )
6441}
6442
6443/// Codes `pictures` as one key frame followed by inter frames.
6444///
6445/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
6446/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
6447/// `show_existing_frame` header, so `stream` is in CODING order while
6448/// `frames` stays in display order (`EncodedSequence::coding_order` is the
6449/// map). Screen content codes flat, decided once per sequence by the same
6450/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
6451/// puts every stream back on the flat path for an A/B.
6452///
6453/// # Errors
6454/// Returns an error under the same conditions [`encode_key_frame`] and the
6455/// inter frame path do.
6456pub fn encode_sequence(
6457 pictures: &[Picture],
6458 base_q_idx: u8,
6459 deadzone: f64,
6460) -> Result<EncodedSequence> {
6461 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
6462}
6463
6464pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
6465 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
6466}
6467
6468/// Encodes one picture as a key frame, choosing each block's luma mode from
6469/// `modes` alone.
6470///
6471/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
6472/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
6473/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
6474/// uses.
6475///
6476/// # Errors
6477/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
6478/// names a mode [`crate::intra::predict`] does not predict.
6479pub(crate) fn encode_key_frame_with_modes_with_ctx(
6480 picture: &Picture,
6481 base_q_idx: u8,
6482 deadzone: f64,
6483 modes: &[u8], fctx: &crate::decode::FrameCtx,
6484) -> Result<Encoded> {
6485 picture.check_even()?;
6486 let padded = picture.padded_to(BLOCK);
6487 let encoded = encode_key_frame_inner(
6488 &padded,
6489 base_q_idx,
6490 deadzone,
6491 modes,
6492 split_blocks(),
6493 (picture.width, picture.height),
6494 unspecified_color_config(), fctx,
6495 )?;
6496 Ok(crop_encoded(&encoded, picture.width, picture.height))
6497}
6498
6499/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
6500/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
6501/// already padded to a whole number of 32x32 blocks; `render` is the real
6502/// (pre-pad) size the frame header tells a decoder to crop back to.
6503pub(crate) fn encode_key_frame_inner(
6504 picture: &Picture,
6505 base_q_idx: u8,
6506 deadzone: f64,
6507 modes: &[u8],
6508 split_blocks: bool,
6509 render: (usize, usize),
6510 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
6511) -> Result<Encoded> {
6512 picture.check()?;
6513 if modes.is_empty() {
6514 return Err(Error::unsupported(
6515 "AV1 encode",
6516 "a mode search needs at least one mode to choose from",
6517 ));
6518 }
6519 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
6520 return Err(Error::unsupported(
6521 "AV1 encode",
6522 format!("intra mode {bad} is not one the encoder predicts"),
6523 ));
6524 }
6525 // The header carries the frame's true (unpadded) size as `frame_width`/
6526 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
6527 // `mi_rows` derived from that same true size (spec `compute_image_size`).
6528 // `render_width`/`render_height` come out equal to it too, so
6529 // `render_and_frame_size_different` is false and no render_size bits are
6530 // written, mirroring libaom/rav1e: the padded `picture` below is only the
6531 // internal coding surface, never what the header names.
6532 // Screen-content detection runs on the SOURCE luma, before any header is
6533 // built: it decides this sequence's `seq_force_screen_content_tools` (and
6534 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
6535 // this frame's own `allow_screen_content_tools`.
6536 let screen = screen_content(
6537 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
6538 picture.width,
6539 (picture.width).min(render.0),
6540 (picture.height).min(render.1),
6541 );
6542 arm_seq_screen(screen);
6543 // A key frame's writer really does start from the defaults, and a search
6544 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
6545 // disarm, or a key frame's bits would depend on which thread searched it.
6546 crate::tile::arm_pricing_cdfs(None, false);
6547 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
6548 // forces deblocking, CDEF and loop restoration OFF for this frame
6549 // (frame.rs:194/210/252/272), so it is only set when the source repeats
6550 // itself enough for the copied blocks to pay that back
6551 // ([`intrabc_worth_it`]).
6552 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
6553 // grid across every tile while this writer builds one per tile, so a
6554 // multi-tile allow_intrabc frame would predict its DVs off a different
6555 // grid than the decoder does. corner-cut, ceiling named: the upgrade
6556 // path is a frame-scoped grid shared by the tile writers.
6557 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
6558 intrabc_worth_it(
6559 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
6560 picture.width,
6561 picture.width.min(render.0),
6562 picture.height.min(render.1),
6563 )
6564 } else {
6565 (false, 0.0)
6566 };
6567 IBC_SHARE.with(|c| c.set(ibc_share));
6568 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
6569 header.allow_screen_content_tools = screen;
6570 header.allow_intrabc = allow_intrabc;
6571 header.render_width = render.0 as u32;
6572 header.render_height = render.1 as u32;
6573 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
6574 // its luma transform below its own side (`crate::tile::write_luma_select`).
6575 // Set here rather than in `key_frame_headers_colour` so the header
6576 // builders' other callers -- the hand-built tile writers, which code no
6577 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
6578 let tx_select = tx_select();
6579 if tx_select {
6580 header.tx_mode = TxMode::Select;
6581 }
6582 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
6583
6584 // Prediction reads no further than this, in each plane's own units --
6585 // see `Plane::true_width`/`true_height`.
6586 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
6587 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
6588 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
6589 // design (see `intra_predict_u8`'s doc comment), so narrow the source
6590 // once here.
6591 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
6592 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
6593 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
6594 let mut luma = Plane {
6595 source: &picture_y8,
6596 reconstruction: vec![128; picture_y8.len()],
6597 width: picture.width,
6598 height: picture.height,
6599 true_width,
6600 true_height,
6601 tile_x0: 0,
6602 tile_y0: 0,
6603 tile_x1: picture.width,
6604 tile_y1: picture.height,
6605 ctx: CoefCtxMap::default(),
6606 };
6607 let mut chroma = [
6608 Plane {
6609 source: &picture_u8,
6610 reconstruction: vec![128; picture_u8.len()],
6611 width: picture.width / 2,
6612 height: picture.height / 2,
6613 true_width: true_width / 2,
6614 true_height: true_height / 2,
6615 tile_x0: 0,
6616 tile_y0: 0,
6617 tile_x1: picture.width / 2,
6618 tile_y1: picture.height / 2,
6619 ctx: CoefCtxMap::default(),
6620 },
6621 Plane {
6622 source: &picture_v8,
6623 reconstruction: vec![128; picture_v8.len()],
6624 width: picture.width / 2,
6625 height: picture.height / 2,
6626 true_width: true_width / 2,
6627 true_height: true_height / 2,
6628 tile_x0: 0,
6629 tile_y0: 0,
6630 tile_x1: picture.width / 2,
6631 tile_y1: picture.height / 2,
6632 ctx: CoefCtxMap::default(),
6633 },
6634 ];
6635
6636 // The search trades a bit for the squared error it saves, in the units the
6637 // reconstruction is measured in: one step of the quantizer, squared.
6638 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
6639 let search = Search {
6640 base_q_idx,
6641 deadzone,
6642 lambda: lambda_scale() * key_lambda_factor() * step * step,
6643 modes,
6644 top_k: prune_top_k(),
6645 screen,
6646 };
6647
6648 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
6649 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
6650 // which may be fewer columns/rows than the padded picture has room for
6651 // -- a block whose origin sits past the true bound is not coded at all,
6652 // matching what a decoder derives from `frame_width`/`frame_height` and
6653 // so never visits either.
6654 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
6655 let (cols, rows) = (cols as usize, rows as usize);
6656 // The luma mode of the block above and of the block to the left, which is
6657 // what picks the CDF the next block's mode is coded against -- the same
6658 // bookkeeping the tile writer keeps, so that the search is costing the
6659 // symbol the writer will actually write.
6660 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
6661 // because a 32x32 block may be split into four 16x16 ones.
6662 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
6663 // This frame's tile grid (one tile unless the facade armed more).
6664 let layout =
6665 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
6666 header.tile_info = tile_info_of(&layout, 1);
6667 // The filter search re-decodes this frame's tiles; the decoder derives
6668 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
6669 // `mi_row_starts`), which is what makes the writer's rects and the
6670 // reader's the same rects.
6671 let header_tile_info = header.tile_info.clone();
6672 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
6673 // once over the whole frame. Each tile job builds its own reconstruction
6674 // planes and its own `above_mode`/`left_mode` bands, which is also what
6675 // the tile writer reads -- a tile resets its neighbour contexts (spec
6676 // 5.11.1), so a block at a tile's left edge must cost its mode against
6677 // the default context, not against whatever the tile to its west left in
6678 // that row. At one tile the bands are the frame's, exactly as before.
6679 let (frame_width, frame_height) = (picture.width, picture.height);
6680 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
6681 let [cb, cr] = &mut chroma;
6682 let chroma_out = [
6683 crate::par::Shared::new(&mut cb.reconstruction),
6684 crate::par::Shared::new(&mut cr.reconstruction),
6685 ];
6686 let search_tile = |index: usize,
6687 fctx: &crate::decode::FrameCtx|
6688 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
6689 crate::tile::arm_pricing_cdfs(None, false);
6690 let rect = layout.rect(index);
6691 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
6692 let mut chroma = [
6693 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
6694 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
6695 ];
6696 clip_planes_to_tile(&mut luma, &mut chroma, rect);
6697 let mut above_mode = vec![DC_PRED; cols * 2];
6698 let mut left_mode = vec![DC_PRED; rows * 2];
6699 let mut ibc = allow_intrabc.then(|| {
6700 Ibc::new(
6701 (
6702 rect.mi_col0 as usize * 4,
6703 rect.mi_row0 as usize * 4,
6704 (rect.mi_col1 as usize * 4).min(true_width),
6705 (rect.mi_row1 as usize * 4).min(true_height),
6706 ),
6707 &picture_y8,
6708 frame_width,
6709 )
6710 });
6711 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
6712 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
6713 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
6714 let mut modes = Vec::with_capacity(4);
6715 // The quadrants of a superblock are coded in the order the decoder
6716 // walks them, which for a 64x64 split into 32x32 blocks is raster
6717 // order among the quadrants that are inside the frame.
6718 let mut blocks = Vec::with_capacity(4);
6719 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
6720 // BEFORE its quadrants (so both start from the same
6721 // reconstruction) and compared against the four of them below --
6722 // the shape the inter frame's own 64 root takes
6723 // (`search_skip_64`). Only a superblock wholly inside the true
6724 // frame is offered it: the writer's `Superblock::Whole` arm
6725 // refuses one the edge cuts through, and a frame that allows
6726 // intrabc is refused outright ([`I64_ROOT`]) because the quadrant
6727 // searches below carry DV state a discarded trial would desync.
6728 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
6729 // corner-cut, ceiling named: only a frame whose true size is a
6730 // WHOLE number of superblocks is offered the root at all.
6731 // MEASURED (lane-i64): on a 248x152 frame -- whose bottom-right
6732 // superblock is cut on BOTH axes -- a frame carrying whole 64
6733 // roots elsewhere desyncs that corner's CHROMA three ways (our
6734 // writer's reconstruction, our decoder and ffmpeg all disagree,
6735 // luma stays exact), i.e. a defect in the whole-64 chroma
6736 // neighbour publication that only the doubly-cut tail block
6737 // reads (class `last-block-desync-reads-as-reconstruction`).
6738 // Every clip on the BD gates, and every real film/screen source,
6739 // is superblock aligned, so nothing measured is withheld.
6740 // Ceiling: trace the corner block's chroma `txb_skip`/dc context
6741 // against aomdec and lift this line.
6742 let aligned = header.mi_cols % crate::tile::SB_MI == 0
6743 && header.mi_rows % crate::tile::SB_MI == 0;
6744 let sb64_legal = i64_root()
6745 && aligned
6746 && ibc.is_none()
6747 && sb_row * 2 + 1 < rows
6748 && sb_col * 2 + 1 < cols
6749 && x64 + SUPERBLOCK <= luma.true_width
6750 && y64 + SUPERBLOCK <= luma.true_height;
6751 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
6752 if sb64_legal {
6753 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6754 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
6755 let (c64, r64) = (sb_col * 4, sb_row * 4);
6756 let (block, cost) = code_square(
6757 &mut luma,
6758 &mut chroma,
6759 (x64, y64),
6760 SUPERBLOCK,
6761 &search,
6762 &mode_bits(above_mode[c64], left_mode[r64]),
6763 tx_select,
6764 None,
6765 fctx,
6766 );
6767 let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
6768 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
6769 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
6770 sb64 = Some((cost, block, after));
6771 }
6772 // A superblock whose 64x64 trial already codes almost nothing per
6773 // pixel is taken outright and its quadrants are never searched --
6774 // `split_rd_breakout` one size up, at the threshold the inter
6775 // root clamps to ([`b64_breakout_threshold`]), where this lever
6776 // BUYS wall instead of spending it.
6777 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
6778 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
6779 });
6780 // What the four quadrants cost together, including the split
6781 // partition symbol at the superblock level, so the two arms are
6782 // one comparable number.
6783 let mut sb_cost = match sb64 {
6784 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
6785 None => 0.0,
6786 };
6787 for quadrant in 0..if early64 { 0 } else { 4 } {
6788 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
6789 if col >= cols || row >= rows {
6790 continue;
6791 }
6792 let (x, y) = (col * BLOCK, row * BLOCK);
6793 let (c0, r0) = (col * 2, row * 2);
6794 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
6795
6796 // spec `decode_partition`'s hasRows/hasCols recomputed at this
6797 // 32x32 block's own half (see `crate::tile::has_half`): the
6798 // true frame edge can fall inside a quadrant a superblock-level
6799 // check already let through. A quadrant that fails either may
6800 // not be left whole; a 16x16 sub-block that fails either (once
6801 // split) is a leaf this writer has no rectangular transform
6802 // for, so the search must not pick a split that would need one.
6803 let (has_cols32, has_rows32) = (
6804 crate::tile::has_half(
6805 col as u32 * crate::tile::BLOCK_MI,
6806 crate::tile::BLOCK_MI,
6807 header.mi_cols,
6808 ),
6809 crate::tile::has_half(
6810 row as u32 * crate::tile::BLOCK_MI,
6811 crate::tile::BLOCK_MI,
6812 header.mi_rows,
6813 ),
6814 );
6815 let whole_legal = has_cols32 && has_rows32;
6816 // A 16x16 sub-block's own hasCols/hasRows (spec
6817 // `decode_partition`, recomputed at this leaf's own half):
6818 // either axis false is a straddling leaf this writer codes as
6819 // the 8x8 leaves that are inside it
6820 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
6821 // false is the same split with the partition symbol inferred
6822 // rather than coded -- no rectangular transform is needed
6823 // (lane-av1rect).
6824 let sub_half = |sr: usize, sc: usize| {
6825 (
6826 crate::tile::has_half(
6827 sc as u32 * crate::tile::SUB_MI,
6828 crate::tile::SUB_MI,
6829 header.mi_cols,
6830 ),
6831 crate::tile::has_half(
6832 sr as u32 * crate::tile::SUB_MI,
6833 crate::tile::SUB_MI,
6834 header.mi_rows,
6835 ),
6836 )
6837 };
6838 // What the whole 32x32 costs, including the partition symbol
6839 // that says it is not split.
6840 let (whole, mut cost_whole) = code_square(
6841 &mut luma,
6842 &mut chroma,
6843 (x, y),
6844 BLOCK,
6845 &search,
6846 &mode_bits(above_mode[c0], left_mode[r0]),
6847 tx_select,
6848 ibc.as_mut(), fctx,
6849 );
6850 cost_whole += search.lambda * partition_bits(BLOCK, false);
6851 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
6852
6853 // What four 16x16 blocks cost instead, each searched against
6854 // the reconstruction the ones before it left.
6855 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
6856 let mut split = Vec::with_capacity(4);
6857 let mut cost_split = search.lambda
6858 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
6859 let mut split_modes = Vec::with_capacity(4);
6860 for sub in 0..4 {
6861 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
6862 // Same filter as the writer's `sub_positions` (spec
6863 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
6864 // return): a sub-block whose own origin sits past the
6865 // true frame is never coded, so it must not be searched
6866 // or pushed onto `split` either, or the writer's block
6867 // count will not match what it is prepared to name.
6868 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
6869 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
6870 {
6871 continue;
6872 }
6873 let (has_cols16, has_rows16) = sub_half(sr, sc);
6874 if has_cols16 && has_rows16 {
6875 let (block, cost) = code_square(
6876 &mut luma,
6877 &mut chroma,
6878 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
6879 SUB,
6880 &search,
6881 &mode_bits(above_mode[sc], left_mode[sr]),
6882 tx_select,
6883 ibc.as_mut(), fctx,
6884 );
6885 cost_split += cost;
6886 split_modes.push(block.mode);
6887 above_mode[sc] = block.mode;
6888 left_mode[sr] = block.mode;
6889 split.push(block);
6890 } else {
6891 // A straddling 16x16: two (or, at a true corner, one)
6892 // 8x8 leaves, in the raster order `write_leaf8`'s
6893 // caller expects. Both leaves cost against the SAME
6894 // enclosing-slot mode context (see
6895 // `crate::tile::write_leaf8`'s doc), and neither
6896 // updates `above_mode`/`left_mode` at this SUB slot --
6897 // the writer never does either, so the search must
6898 // not diverge from what it will actually read next.
6899 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
6900 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
6901 let mut leaves = Vec::with_capacity(2);
6902 for i in 0..4 {
6903 let leaf_x = x_sub + (i % 2) * 8;
6904 let leaf_y = y_sub + (i / 2) * 8;
6905 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
6906 continue;
6907 }
6908 let (leaf, cost) = code_square(
6909 &mut luma,
6910 &mut chroma,
6911 (leaf_x, leaf_y),
6912 8,
6913 &search,
6914 &leaf_mode_bits,
6915 tx_select,
6916 None, fctx,
6917 );
6918 cost_split += cost;
6919 split_modes.push(leaf.mode);
6920 leaves.push(leaf);
6921 }
6922 split.push(BlockCoeffs {
6923 eight: Some(leaves),
6924 ..BlockCoeffs::default()
6925 });
6926 }
6927 }
6928
6929 // A split whose subs are all whole 16x16 is a real quality
6930 // alternative to `whole`, exactly as before. Through r14, a
6931 // split carrying an 8x8-leaf sub was only ever forced
6932 // (`!whole_legal`), never chosen on cost, because the leaf
6933 // path was not yet proven against a real decoder; r15 proved
6934 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
6935 // the read path (`decode_leaf8`), so leaf8 can now win on
6936 // cost anywhere, same as any other split.
6937 if !whole_legal || (split_blocks && cost_split < cost_whole) {
6938 sb_cost += cost_split;
6939 modes.extend_from_slice(&split_modes);
6940 blocks.push(Quadrant::Split(split));
6941 } else {
6942 sb_cost += cost_whole;
6943 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
6944 for cell in 0..2 {
6945 above_mode[c0 + cell] = whole.mode;
6946 left_mode[r0 + cell] = whole.mode;
6947 }
6948 modes.push(whole.mode);
6949 blocks.push(Quadrant::Whole(whole));
6950 }
6951 }
6952 let index = sb_row * sb_cols + sb_col;
6953 match sb64 {
6954 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
6955 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
6956 for cell in 0..4 {
6957 above_mode[sb_col * 4 + cell] = block.mode;
6958 left_mode[sb_row * 4 + cell] = block.mode;
6959 }
6960 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6961 let mode = block.mode;
6962 coded.push((index, Superblock::Whole(block), vec![mode]));
6963 }
6964 _ => coded.push((index, Superblock::Split(blocks), modes)),
6965 }
6966 }
6967 }
6968 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
6969 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
6970 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
6971 for (&out, tile) in chroma_out.iter().zip(&chroma) {
6972 copy_rect(
6973 out,
6974 &tile.reconstruction,
6975 frame_width / 2,
6976 x0 / 2,
6977 y0 / 2,
6978 x1.div_ceil(2),
6979 y1.div_ceil(2),
6980 );
6981 }
6982 Ok(coded)
6983 };
6984 let searched = search_tiles(layout.count(), fctx, search_tile)?;
6985 // Back into frame raster order: the tile writer indexes `superblocks` by
6986 // the frame's own superblock index, and `modes` is the coding order the
6987 // ablation drivers read.
6988 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
6989 for (at, superblock, block_modes) in searched.into_iter().flatten() {
6990 in_order[at] = Some((superblock, block_modes));
6991 }
6992 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
6993 let mut modes = Vec::with_capacity(cols * rows);
6994 for slot in in_order {
6995 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
6996 superblocks.push(superblock);
6997 modes.extend_from_slice(&block_modes);
6998 }
6999
7000 #[cfg(test)]
7001 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
7002 // A key frame always starts from the defaults (`primary_ref_frame` is
7003 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
7004 // set, so what it stores into the slots it refreshes is exactly those
7005 // defaults again (spec 7.20's `started_from` arm) -- the first inter
7006 // frame after it therefore starts from the defaults too.
7007 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
7008 let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
7009 let start_cdfs = CdfSnapshot(cdfs);
7010 // The luma restoration-unit grid this frame's `lr_params` implies
7011 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
7012 // swallowed by the one before it), for the tile writer's own per-unit
7013 // walk.
7014 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
7015 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
7016 // Every tile is coded from this frame's OWN starting tables and leaves
7017 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
7018 // loop-restoration reference and its neighbour contexts), so the tiles
7019 // are independent of each other and of the order they are written in.
7020 let code_tiles = |bits: u8,
7021 sb_cols: usize,
7022 grid: &[u8],
7023 units: &[Option<crate::restoration::WienerInfo>]|
7024 -> Result<Vec<Vec<u8>>> {
7025 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
7026 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
7027 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
7028 let mut cdfs = start_cdfs.0.clone();
7029 crate::tile::arm_screen(screen);
7030 crate::tile::arm_filter_intra(filter_intra_on());
7031 crate::tile::arm_intrabc(allow_intrabc);
7032 crate::tile::arm_pricing_cdfs(None, false);
7033 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
7034 mi_cols,
7035 mi_rows,
7036 base_q_idx,
7037 &superblocks,
7038 tx_select,
7039 &mut cdfs,
7040 layout.rect(index),
7041 )?;
7042 Ok((bytes, None))
7043 })?;
7044 Ok(out)
7045 };
7046 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
7047 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
7048 // the tile just coded back to the decoder under each candidate (see
7049 // `crate::filter_search`), and keep the filtered picture that wins as
7050 // the reconstruction -- what a decoder outputs, and what the next
7051 // frame predicts from.
7052 pick_and_apply_filters(
7053 &mut header,
7054 &mut luma,
7055 &mut chroma,
7056 [&picture_y8, &picture_u8, &picture_v8],
7057 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
7058 // and loop restoration off and codes none of their parameters
7059 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
7060 // the encoder's reconstruction is already what a decoder produces.
7061 !allow_intrabc,
7062 &mut tiles,
7063 search.lambda,
7064 fctx,
7065 // Every re-code starts from this frame's OWN starting tables, never
7066 // from where the first write left them: the second tile is the same
7067 // symbol sequence plus new ones, so it must adapt from the same
7068 // point the decoder will.
7069 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
7070 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
7071 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
7072 crate::decode::decode_key_frame_tiles_lr(
7073 &payloads,
7074 &header_tile_info,
7075 h.mi_cols,
7076 h.mi_rows,
7077 base_q_idx,
7078 h.frame_width,
7079 h.frame_height,
7080 seq.enable_filter_intra,
7081 cdef,
7082 lf,
7083 tx_select,
7084 h.reduced_tx_set,
7085 h.allow_screen_content_tools,
7086 h.allow_intrabc,
7087 lr,
7088 fctx,
7089 )
7090 },
7091 )?;
7092 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
7093 header.tile_info.tile_size_bytes = tile_size_bytes;
7094 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
7095 let mut stream = temporal_delimiter();
7096 stream.extend_from_slice(&sequence_header_obu(&seq)?);
7097 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
7098
7099 let [u, v] = chroma;
7100 Ok(Encoded {
7101 stream,
7102 modes,
7103 inter_block_share: 0.0,
7104 reconstruction: Picture {
7105 width: luma.width,
7106 height: luma.height,
7107 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
7108 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
7109 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
7110 },
7111 tile,
7112 mi_cols: header.mi_cols,
7113 mi_rows: header.mi_rows,
7114 base_q_idx,
7115 tx_select,
7116 // A key frame codes no inter block, so no motion_mode symbol.
7117 switchable_motion_mode: false,
7118 screen,
7119 next_cdfs: start_cdfs.clone(),
7120 start_cdfs,
7121 loop_filter: header.loop_filter,
7122 cdef: header.cdef,
7123 loop_restoration: header.loop_restoration,
7124 allow_intrabc,
7125 delta: header.delta.clone(),
7126 })
7127}
7128
7129/// Chooses this frame's deblocking levels and CDEF strengths, writes them
7130/// into `header` and
7131/// replaces the frame's own region of the encoder's reconstruction with the
7132/// filtered picture the decoder produced under them
7133/// ([`crate::filter_search::pick_deblock`]).
7134///
7135/// `search == false` leaves the header at level 0 (deblocking off) and the
7136/// reconstruction untouched: the caller's stream is one this crate's own
7137/// decoder cannot read back, so there is nothing to search against.
7138///
7139/// # Errors
7140/// The decoder's own error, when it refuses the tile the encoder just wrote
7141/// -- that is an encoder defect, not a filter one, so it is propagated
7142/// rather than swallowed into "no deblocking".
7143fn pick_and_apply_filters(
7144 header: &mut FrameHeader,
7145 luma: &mut Plane<'_>,
7146 chroma: &mut [Plane<'_>; 2],
7147 source: [&[u8]; 3],
7148 search: bool,
7149 // The coded tiles, one payload per tile of the frame's grid, replaced in
7150 // place when the search chooses a per-64x64 `cdef_idx` list
7151 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
7152 // tile is written a second time under `recode` and the winner
7153 // re-decoded from them.
7154 tiles: &mut Vec<Vec<u8>>,
7155 lambda: f64,
7156 fctx: &crate::decode::FrameCtx,
7157 recode: impl Fn(
7158 u8,
7159 usize,
7160 &[u8],
7161 &[Option<crate::restoration::WienerInfo>],
7162 ) -> Result<Vec<Vec<u8>>>,
7163 decode: impl Fn(
7164 &LoopFilterParams,
7165 &CdefParams,
7166 &FrameHeader,
7167 &[Vec<u8>],
7168 &LoopRestorationParams,
7169 ) -> Result<Picture>,
7170) -> Result<()> {
7171 if !search {
7172 return Ok(());
7173 }
7174 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
7175 let hdr = header.clone();
7176 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
7177 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
7178 let damping = 3 + (header.quantization.base_q_idx >> 6);
7179 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
7180 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
7181 let none_lr = LoopRestorationParams::default();
7182 // Every candidate scores the same coded tile: decode it once and re-run
7183 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
7184 // the encoder's profile before this). The per-64x64 error the CDEF
7185 // preset search reads comes off the REPLAYED picture, which is the same
7186 // picture a decode produces -- that is what the replay is pinned on.
7187 crate::decode::clear_filter_replay();
7188 // lane-av1fpar: the per-tile search is over, so every core is idle from
7189 // here to the end of the frame -- band each candidate's deblock/CDEF
7190 // replay, the capture decode's own filter chain and the loop-restoration
7191 // passes across the same workers the search used.
7192 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
7193 let ft = crate::par::timer(crate::par::S_FILTER);
7194 let search_result = crate::filter_search::pick_filters(
7195 |lf, cdef| {
7196 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
7197 return Ok(picture);
7198 }
7199 crate::decode::arm_filter_replay();
7200 let _t = crate::par::timer(crate::par::S_FIRST);
7201 decode(lf, cdef, &hdr, tiles, &none_lr)
7202 },
7203 source,
7204 luma.width,
7205 (fw, fh),
7206 damping,
7207 (sb_cols, sb_rows),
7208 lambda,
7209 );
7210 drop(ft);
7211 let (lf, cdef, idx_grid, picture) = search_result?;
7212 header.loop_filter = lf;
7213 header.cdef = cdef;
7214 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
7215 // in the frame header, so a re-decode under candidate parameters cannot
7216 // search them the way deblocking and CDEF are searched above. What the
7217 // decoder hands back instead is its own filter chain's intermediates
7218 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
7219 // those, through the decoder's own Wiener kernel.
7220 //
7221 // The capture rides the decode this stage was already going to do: the
7222 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
7223 // decode of the tile as it stands. That decode's header still says
7224 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
7225 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
7226 // an approximation inside the SEARCH only; the reconstruction this
7227 // function ends up splicing is always a real decode of the real tile.
7228 let lr_on = restoration_enabled();
7229 // The `cdef_idx` literals live in the tile payload, so a frame that
7230 // chose a per-64x64 preset list codes its tiles a second time.
7231 if !idx_grid.is_empty() {
7232 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
7233 }
7234 // lane-av1cap: that re-coded tile used to be DECODED here as well --
7235 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
7236 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
7237 // and the picture this function splices. Both come out of ONE more
7238 // replay of the winning parameters on the same captured pre-filter
7239 // planes every candidate was scored on: the same two filter kernels, on
7240 // the same input, in the same order, so the same bytes. Re-coding the
7241 // tile does not move the reconstruction the replay holds -- `cdef_idx`
7242 // is an equiprobable literal, so it adapts no CDF and changes no
7243 // residual.
7244 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
7245 #[cfg(test)]
7246 let replay_was_used = replayed.is_some();
7247 let (mut filtered, mut stages) = match replayed {
7248 Some((picture, stages)) => (picture, stages),
7249 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
7250 // refuses): every candidate was a full decode, so the winner's own
7251 // picture stands, and the stages still need a capturing decode.
7252 None => {
7253 fctx.capture_stages.set(lr_on);
7254 let picture = if idx_grid.is_empty() && !lr_on {
7255 picture
7256 } else {
7257 let _t = crate::par::timer(crate::par::S_CAPTURE);
7258 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
7259 };
7260 fctx.capture_stages.set(false);
7261 (picture, crate::decode::take_filter_stages(fctx))
7262 }
7263 };
7264 #[cfg(test)]
7265 if crate::decode::verify_final_replay() && replay_was_used {
7266 fctx.capture_stages.set(lr_on);
7267 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
7268 fctx.capture_stages.set(false);
7269 let want_stages = crate::decode::take_filter_stages(fctx);
7270 assert!(
7271 (want.width, want.height) == (filtered.width, filtered.height)
7272 && want.y == filtered.y
7273 && want.u == filtered.u
7274 && want.v == filtered.v,
7275 "the final filter replay is not the capture decode it stands in for",
7276 );
7277 // Only the frame's own cropped region: the plane is padded to the
7278 // superblock grid and the columns past the mi extent are written by
7279 // nothing (the decoder's plane pool leaves whatever the last frame
7280 // put there), while the restoration search reads strictly inside
7281 // `fw x fh` -- `restoration::lr_sample` clamps its column to
7282 // `plane_w - 1` and its row to the frame's, and
7283 // `filter_search::pick_restoration`'s own SSE walk never leaves the
7284 // crop either.
7285 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
7286 for row in 0..h {
7287 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
7288 assert!(
7289 x == y,
7290 "{what}: the replayed filter stages are not the ones the capture \
7291 decode returns (row {row} of {h}, width {w}, stride {stride})",
7292 );
7293 }
7294 };
7295 match (&want_stages, &stages) {
7296 (Some(a), Some(b)) => {
7297 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
7298 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
7299 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
7300 region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked");
7301 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
7302 }
7303 }
7304 (None, None) => {}
7305 _ => panic!("one path captured filter stages and the other did not"),
7306 }
7307 }
7308 // lane-av1cap2: the capture stays live past the restoration search --
7309 // `crate::decode::replay_restoration` filters the same post-CDEF plane
7310 // rather than decoding the re-coded tile. Cleared at the end instead.
7311 let mut lr = LoopRestorationParams::default();
7312 if lr_on {
7313 let mut want = LoopRestorationParams {
7314 loop_restoration_size: [64, 64, 64],
7315 uses_lr: true,
7316 ..LoopRestorationParams::default()
7317 };
7318 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
7319 let lrt = crate::par::timer(crate::par::S_LR);
7320 let units = match stages.take() {
7321 Some(stages) => crate::filter_search::pick_restoration(
7322 &stages,
7323 source[0],
7324 luma.width,
7325 (fw, fh),
7326 &want,
7327 lambda,
7328 fctx,
7329 ),
7330 None => Vec::new(),
7331 };
7332 // A frame no unit restores keeps `RESTORE_NONE` on every plane
7333 // rather than paying ~1 bit per 64x64 for a tile full of
7334 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
7335 // clip whose units never take a filter).
7336 drop(lrt);
7337 if units.iter().any(Option::is_some) {
7338 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
7339 let _t = crate::par::timer(crate::par::S_CAPTURE);
7340 // lane-av1cap2: that re-coded tile used to be DECODED here to
7341 // reach the restored reference frame -- 5.6% of a 4K frame,
7342 // for a filter that reads nothing of the tile but the per-unit
7343 // Wiener filters this stage just chose. Run the decoder's own
7344 // restoration kernel on the replay's post-CDEF plane instead
7345 // (`crate::decode::replay_restoration`), with the real
7346 // post-deblock stripe borders.
7347 match crate::decode::replay_restoration(&want, &units, fctx) {
7348 Some(y) => {
7349 #[cfg(test)]
7350 let margin = fctx
7351 .last_frame_wide_margin
7352 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
7353 #[cfg(test)]
7354 if crate::decode::verify_final_replay() {
7355 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
7356 assert!(
7357 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
7358 && want_pic.u == filtered.u
7359 && want_pic.v == filtered.v,
7360 "the restoration replay moved a chroma plane or the picture size",
7361 );
7362 assert!(
7363 want_pic.y == y,
7364 "the restoration replay is not the decode of the re-coded tile",
7365 );
7366 assert!(
7367 fctx.last_frame_wide_margin
7368 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
7369 == margin,
7370 "the restoration replay's wide-margin luma is not the decode's",
7371 );
7372 }
7373 filtered.y = y;
7374 }
7375 // Nothing captured: the winner came out of a full decode,
7376 // so this one does too.
7377 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
7378 }
7379 *tiles = coded;
7380 lr = want;
7381 }
7382 }
7383 crate::decode::clear_filter_replay();
7384 header.loop_restoration = lr;
7385 let dec_cw = filtered.width.div_ceil(2);
7386 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
7387 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
7388 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
7389 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
7390 Ok(())
7391}
7392
7393/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
7394/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
7395/// since every block this crate's inter tile writer codes is 32x32.
7396const SIZE_GROUP_32: usize = 3;
7397
7398/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
7399/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
7400/// stack this encoder builds is ever asked to predict against.
7401const LAST_FRAME: i8 = 1;
7402
7403/// What an inter frame's intra branch spends to name each of the thirteen
7404/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
7405/// context, since an inter frame's intra blocks do not read their
7406/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
7407/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
7408/// state, so it is built once per frame.
7409fn inter_mode_bits() -> [f64; 13] {
7410 std::array::from_fn(|mode| {
7411 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
7412 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
7413 } else {
7414 0.0
7415 };
7416 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
7417 + angle
7418 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
7419 })
7420}
7421
7422/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
7423/// [`mc::predict`] takes, in the units of the plane it predicts into.
7424///
7425/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
7426/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
7427/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
7428/// domain. `luma` picks which.
7429fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
7430 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
7431}
7432
7433/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
7434/// that module): the magnitude an `MV_CLASS_n` component's own bits start
7435/// counting from.
7436fn mv_class_base(class: usize) -> i32 {
7437 if class == 0 { 0 } else { 2i32 << (class + 2) }
7438}
7439
7440/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
7441/// `tile::mv_class_of`.
7442fn mv_class_of(z: i32) -> usize {
7443 let mut class = 0;
7444 while class < 10 && mv_class_base(class + 1) <= z {
7445 class += 1;
7446 }
7447 class
7448}
7449
7450/// What [`crate::tile::write_mv_component`] (private to that module) would
7451/// spend coding one non-zero motion vector component, against the same
7452/// static default CDFs the writer starts a frame from — the same
7453/// static-table approximation [`mode_bits`] costs the luma mode symbol
7454/// through, not the tile writer's own adapting state, which this encoder has
7455/// no way to read without duplicating it block for block.
7456///
7457/// Returns `None` when `diff` needs the eighth-pel precision this crate's
7458/// frames never carry (`allow_high_precision_mv` is always off), which is
7459/// what [`round_to_valid_mv`] exists to avoid ever happening.
7460fn mv_component_bits(diff: i32) -> Option<f64> {
7461 let mag = diff.unsigned_abs() as i32;
7462 let z = mag - 1;
7463 if z & 1 == 0 {
7464 return None;
7465 }
7466 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
7467 let class = mv_class_of(z);
7468 bits += symbol_bits(&cdf::MV_CLASS, class);
7469 let local = z - mv_class_base(class);
7470 if class == 0 {
7471 let bit = (local >> 3) & 1;
7472 let fr = (local >> 1) & 3;
7473 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
7474 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
7475 } else {
7476 let d = local >> 3;
7477 let fr = (local >> 1) & 3;
7478 for i in 0..class {
7479 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
7480 }
7481 bits += symbol_bits(&cdf::MV_FR, fr as usize);
7482 }
7483 Some(bits)
7484}
7485
7486/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
7487/// own -- a second motion search per block against that reference's picture,
7488/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
7489/// off in a test build (what the lane measured both arms with).
7490fn extra_ref_new_mv() -> bool {
7491 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
7492 Some(v) if cfg!(test) => v != "0",
7493 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
7494 }
7495}
7496
7497/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
7498/// flat slot plan (`inter_frame_headers_slots`): every reference but
7499/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
7500/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
7501/// frame two back when there is one (otherwise it, too, names the key frame's
7502/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
7503pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
7504 let last = order_hint.wrapping_sub(1) & 0x7f;
7505 let alt = if has_altref {
7506 order_hint.wrapping_sub(2) & 0x7f
7507 } else {
7508 key_hint
7509 };
7510 [last, last, last, key_hint, last, last, alt]
7511}
7512
7513/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
7514/// header bit that lets each block choose between a single and a compound
7515/// reference. Off by default until compound prediction is measured to pay;
7516/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
7517/// runs as), and every block still codes SINGLE, so the only cost is one
7518/// `comp_mode` symbol per inter block.
7519pub(crate) const REFERENCE_SELECT: bool = true;
7520
7521/// [`REFERENCE_SELECT`], with the test-build environment override.
7522pub(crate) fn reference_select() -> bool {
7523 match std::env::var("EC_AV1_COMPOUND").ok() {
7524 Some(v) if cfg!(test) => v != "0",
7525 _ => crate::speed::at(&crate::speed::COMPOUND),
7526 }
7527}
7528
7529/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
7530/// per entry past `start`, `1` to advance and `0` to stop, at most two.
7531fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
7532 let mut bits = 0.0;
7533 let mut idx = start;
7534 while idx < start + 2 && stack.entries.len() > idx + 1 {
7535 let advance = idx < target;
7536 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
7537 if !advance {
7538 break;
7539 }
7540 idx += 1;
7541 }
7542 bits
7543}
7544
7545/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
7546/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
7547/// `assign_mv`), so the same vector costs a different residual from each.
7548fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
7549 let mut best: Option<(f64, u8)> = None;
7550 for idx in 0..3usize {
7551 if idx > 0 && stack.entries.len() <= idx {
7552 break;
7553 }
7554 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
7555 if let Some(b) = mv_residual_bits(mv, base) {
7556 let total = b + drl_bits_for(stack, 0, idx);
7557 if best.is_none_or(|(t, _)| total < t) {
7558 best = Some((total, idx as u8));
7559 }
7560 }
7561 }
7562 best
7563}
7564
7565/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
7566/// zero vector and the stack's own candidates. A neighbour block's vector is
7567/// where this block's motion most often already is, which is what pays for
7568/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
7569/// vs libaom for 0.2 s off a 6 s ladder).
7570fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
7571 let mut seeds = [(0, 0); 4];
7572 let mut n = 1;
7573 for e in stack.entries.iter().take(3) {
7574 seeds[n] = e.mv;
7575 n += 1;
7576 }
7577 (seeds, n)
7578}
7579
7580/// What [`crate::tile::write_mv`] (private to that module) would spend
7581/// coding `mv` as a residual against `pred`: the joint symbol naming which
7582/// components differ, then each differing component. `None` under the same
7583/// condition [`mv_component_bits`] returns `None`.
7584/// How many frames back `ref_frame` sits from the frame being coded, off the
7585/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
7586/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
7587/// what [`crate::motion::search`] scales its starting step by.
7588fn ref_distance(ref_frame: i8) -> u32 {
7589 let (bits, order_hint, hints) = crate::tile::order_hints();
7590 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
7591 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
7592 .unsigned_abs()
7593 .max(1);
7594 if crate::envflags::env_flag!("EC_TRACE_DIST") {
7595 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
7596 }
7597 d
7598}
7599
7600fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
7601 let diff = (mv.0 - pred.0, mv.1 - pred.1);
7602 let joint = match (diff.0 != 0, diff.1 != 0) {
7603 (false, false) => 0,
7604 (false, true) => 1,
7605 (true, false) => 2,
7606 (true, true) => 3,
7607 };
7608 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
7609 for d in [diff.0, diff.1] {
7610 if d != 0 {
7611 bits += mv_component_bits(d)?;
7612 }
7613 }
7614 Some(bits)
7615}
7616
7617/// Rounds `mv` so that its residual against `pred` is one
7618/// [`crate::tile::write_mv_component`] can actually code: each component's
7619/// difference is either zero or has an even magnitude (the eighth-pel bit
7620/// `allow_high_precision_mv` off always infers as one forces the coded
7621/// magnitude odd one step further in, which comes out even here since this
7622/// crate's motion search works in whole units of that same step). Rounding
7623/// down keeps every coded MV — and so every `nearest_mv` a later block's
7624/// stack votes with — built from an even displacement from `(0, 0)`, so the
7625/// invariant holds without this function seeing the whole stack.
7626fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
7627 let round = |m: i32, p: i32| {
7628 let diff = m - p;
7629 let mag = diff.unsigned_abs() as i32;
7630 let even = mag - mag % 2;
7631 if even == 0 {
7632 p
7633 } else {
7634 p + even * diff.signum()
7635 }
7636 };
7637 (round(mv.0, pred.0), round(mv.1, pred.1))
7638}
7639
7640/// Predicts one `side`-square block by motion compensation from `reference`
7641/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
7642#[allow(clippy::too_many_arguments)]
7643fn mc_trial(
7644 plane: &Plane,
7645 x: usize,
7646 y: usize,
7647 side: usize,
7648 mv: (i32, i32),
7649 luma: bool,
7650 reference: &[u16],
7651 stride: usize,
7652 ref_width: usize,
7653 ref_height: usize,
7654 skip: bool,
7655 base_q_idx: u8,
7656 deadzone: f64,
7657 set: TxbSet, fctx: &crate::decode::FrameCtx,
7658) -> Trial {
7659 let x_q4 = mv_to_q4(x, mv.1, luma);
7660 let y_q4 = mv_to_q4(y, mv.0, luma);
7661 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
7662 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
7663 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
7664 // lane-av1speed: both buffers are per-candidate scratch on the hottest
7665 // path in the encoder, so they live on the stack -- `side` is at most
7666 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
7667 // per motion-compensated trial otherwise.
7668 let mut prediction16 = [0u16; BLOCK * BLOCK];
7669 let prediction16 = &mut prediction16[..side * side];
7670 mc::predict(
7671 reference,
7672 stride,
7673 ref_width,
7674 ref_height,
7675 x_q4,
7676 y_q4,
7677 side,
7678 side,
7679 prediction16, fctx,
7680 );
7681 let mut prediction = [0u8; BLOCK * BLOCK];
7682 let prediction = &mut prediction[..side * side];
7683 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
7684 *dst = src as u8;
7685 }
7686 plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)
7687}
7688
7689/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
7690/// references predict into the `CONV_BUF` intermediate domain
7691/// ([`mc::predict_compound_intermediate`]) and are blended by
7692/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
7693/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
7694/// block, so the encoder's reconstruction is the decoder's.
7695#[allow(clippy::too_many_arguments)]
7696fn mc_trial_compound(
7697 plane: &Plane,
7698 x: usize,
7699 y: usize,
7700 side: usize,
7701 (mv0, mv1): ((i32, i32), (i32, i32)),
7702 luma: bool,
7703 ref0: (&[u16], usize, usize, usize),
7704 ref1: (&[u16], usize, usize, usize),
7705 base_q_idx: u8,
7706 deadzone: f64,
7707 set: TxbSet, fctx: &crate::decode::FrameCtx,
7708) -> Trial {
7709 let mut inter0 = [0i32; BLOCK * BLOCK];
7710 let mut inter1 = [0i32; BLOCK * BLOCK];
7711 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
7712 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
7713 mc::predict_compound_intermediate(
7714 r.0,
7715 r.1,
7716 r.2,
7717 r.3,
7718 mv_to_q4(x, mv.1, luma),
7719 mv_to_q4(y, mv.0, luma),
7720 mc::REF_NO_SCALE,
7721 side,
7722 side,
7723 mc::InterpFilterKind::Regular,
7724 mc::InterpFilterKind::Regular,
7725 dst,
7726 );
7727 }
7728 let mut blended16 = [0u16; BLOCK * BLOCK];
7729 let blended16 = &mut blended16[..side * side];
7730 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
7731 let mut prediction = [0u8; BLOCK * BLOCK];
7732 let prediction = &mut prediction[..side * side];
7733 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
7734 *dst = src as u8;
7735 }
7736 plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set)
7737}
7738
7739/// Codes one 32x32 block of an inter frame as whichever costs least of: each
7740/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
7741/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
7742/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
7743/// coding a real residual (`skip: false`) whenever one prices out cheaper
7744/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
7745/// missing inter `tx_type` symbol (the desync this function's candidates
7746/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
7747/// fixed.
7748///
7749/// The symbol costs this ranks candidates by use fixed contexts (0) for
7750/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
7751/// contexts for those come from its own neighbour bookkeeping
7752/// (`tile::Neighbours`), which is private to that module and not worth
7753/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
7754/// `drl_mode` contexts come straight from `stack`, which is exact, because
7755/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
7756/// the tile writer derives from the same grid state.
7757#[allow(clippy::too_many_arguments)]
7758/// One prediction of `side` x `side` samples from `reference`, as `u8` --
7759/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
7760/// four times the stack scratch that function sizes for [`BLOCK`].
7761fn predict_u8(
7762 reference: &[u16],
7763 stride: usize,
7764 ref_width: usize,
7765 ref_height: usize,
7766 (x, y): (usize, usize),
7767 side: usize,
7768 mv: (i32, i32),
7769 luma: bool,
7770 fctx: &crate::decode::FrameCtx,
7771) -> Vec<u8> {
7772 let mut prediction = vec![0u16; side * side];
7773 mc::predict(
7774 reference,
7775 stride,
7776 ref_width,
7777 ref_height,
7778 mv_to_q4(x, mv.1, luma),
7779 mv_to_q4(y, mv.0, luma),
7780 side,
7781 side,
7782 &mut prediction,
7783 fctx,
7784 );
7785 prediction.iter().map(|&v| v as u8).collect()
7786}
7787
7788/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
7789/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
7790/// references predict into the `CONV_BUF` intermediate domain and are blended
7791/// at the simple-average split `(8, 8)`, the same path (and so the same
7792/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
7793fn predict_compound_u8(
7794 ref0: (&[u16], usize, usize, usize),
7795 ref1: (&[u16], usize, usize, usize),
7796 (x, y): (usize, usize),
7797 side: usize,
7798 (mv0, mv1): ((i32, i32), (i32, i32)),
7799 luma: bool,
7800 fctx: &crate::decode::FrameCtx,
7801) -> Vec<u8> {
7802 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
7803 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
7804 mc::predict_compound_intermediate(
7805 r.0,
7806 r.1,
7807 r.2,
7808 r.3,
7809 mv_to_q4(x, mv.1, luma),
7810 mv_to_q4(y, mv.0, luma),
7811 mc::REF_NO_SCALE,
7812 side,
7813 side,
7814 mc::InterpFilterKind::Regular,
7815 mc::InterpFilterKind::Regular,
7816 dst,
7817 );
7818 }
7819 let mut blended = vec![0u16; side * side];
7820 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
7821 blended.iter().map(|&v| v as u8).collect()
7822}
7823
7824/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
7825/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
7826/// SKIP, priced through the same `symbol_bits` path every other candidate
7827/// uses. The winner's prediction is committed to the planes (it IS the
7828/// reconstruction -- a skip block has no residual); the caller restores them
7829/// if the four quadrants come out cheaper.
7830///
7831/// `None` when no candidate could be coded at all (a `NEWMV` residual the
7832/// writer cannot name is simply not offered, and the other modes always are,
7833/// so this only happens if every candidate is refused).
7834fn search_skip_64(
7835 luma: &mut Plane,
7836 chroma: &mut [Plane; 2],
7837 (x, y): (usize, usize),
7838 search: &Search,
7839 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
7840 // screen content -- see that function's doc).
7841 residual: bool,
7842 reference: &Picture,
7843 stack: &MvStack,
7844 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
7845 // superblock's 16x16-mi window, built off the same grid the tile writer
7846 // rebuilds it from (empty unless the frame carries `reference_select`).
7847 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
7848 fctx: &crate::decode::FrameCtx,
7849) -> Option<(f64, BlockCoeffs)> {
7850 let side = SUPERBLOCK;
7851 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
7852 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
7853 let ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
7854 + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
7855 + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
7856 // What every candidate pays whatever its vector: `skip` coded 1, then
7857 // `is_inter` coded 1, then the LAST chain above.
7858 let fixed = symbol_bits(&cdf::SKIP[0], 1) + symbol_bits(&cdf::INTRA_INTER[0], 1) + ref_bits;
7859 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
7860 ref1: None,
7861 mv1: (0, 0),
7862 ref_frame: crate::mvstack::LAST_FRAME,
7863 mode,
7864 mv,
7865 ref_mv_idx,
7866 };
7867 let mut cands: Vec<(f64, InterInfo)> = vec![
7868 (
7869 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
7870 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
7871 ),
7872 (
7873 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
7874 info_of(InterMode::GlobalMv, (0, 0), 0),
7875 ),
7876 ];
7877 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
7878 for idx in 1..=2usize {
7879 if let Some(e) = stack.entries.get(idx) {
7880 cands.push((
7881 near_bits + drl_bits_for(stack, 1, idx),
7882 info_of(InterMode::NearMv, e.mv, idx as u8),
7883 ));
7884 }
7885 }
7886 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
7887 // candidate below to pair with the second reference's NEAREST half.
7888 let mut last_new_mv: Option<(i32, i32)> = None;
7889 if leaf_new_mv() {
7890 let source_block = luma.source_block(x, y, side);
7891 let (seeds, seed_n) = mv_seeds(stack);
7892 let found = motion::search(
7893 &reference.y,
7894 reference.width,
7895 luma.true_width,
7896 luma.true_height,
7897 &source_block,
7898 x,
7899 y,
7900 side,
7901 side,
7902 stack.pred_mv,
7903 &seeds[..seed_n],
7904 search.lambda,
7905 fctx,
7906 1,
7907 );
7908 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
7909 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
7910 last_new_mv = Some(mv);
7911 cands.push((
7912 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
7913 info_of(InterMode::NewMv, mv, ref_mv_idx),
7914 ));
7915 }
7916 }
7917
7918 let mut best: Option<(f64, f64, InterInfo, [Trial; 3])> = None;
7919 for (bits, info) in cands {
7920 let trials = [
7921 (0usize, x, y, side, true),
7922 (1, x / 2, y / 2, side / 2, false),
7923 (2, x / 2, y / 2, side / 2, false),
7924 ]
7925 .map(|(plane, px, py, s, is_luma)| {
7926 let (samples, stride, w, h) = match plane {
7927 0 => (&reference.y, reference.width, luma.true_width, luma.true_height),
7928 1 => (
7929 &reference.u,
7930 reference.width / 2,
7931 chroma[0].true_width,
7932 chroma[0].true_height,
7933 ),
7934 _ => (
7935 &reference.v,
7936 reference.width / 2,
7937 chroma[1].true_width,
7938 chroma[1].true_height,
7939 ),
7940 };
7941 let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
7942 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
7943 // `skip` true: the trial is the prediction itself plus its SSE,
7944 // so no transform of any size is involved (the reason a 64x64
7945 // root can be coded at all before a forward TX_64X64 exists).
7946 target.code_from_prediction(
7947 px,
7948 py,
7949 s,
7950 &prediction,
7951 true,
7952 search.base_q_idx,
7953 search.deadzone,
7954 TxbSet::Luma32Inter,
7955 )
7956 });
7957 let cost = trials[0].sse
7958 + trials[1].sse
7959 + trials[2].sse
7960 + search.lambda * (fixed + bits);
7961 if best.as_ref().is_none_or(|b| cost < b.0) {
7962 best = Some((cost, fixed + bits, info, trials));
7963 }
7964 }
7965
7966 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
7967 // superblock can form without a second motion search ([`b64_compound`]),
7968 // priced through the same `symbol_bits` path -- `fixed` minus the single
7969 // reference's tree, plus the pair tree and the compound mode.
7970 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
7971 let (ref1, g) = (*ref1, *g);
7972 let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1);
7973 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
7974 + if uni {
7975 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
7976 + symbol_bits(&cdf::COMP_REF[0][0], 0)
7977 + symbol_bits(&cdf::COMP_REF[0][1], 0)
7978 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
7979 } else {
7980 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
7981 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
7982 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
7983 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
7984 };
7985 let mode_ctx =
7986 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7987 let mode_bits_of =
7988 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7989 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
7990 ref1: Some(ref1),
7991 mv1: mvs.1,
7992 ref_frame: crate::mvstack::LAST_FRAME,
7993 mode,
7994 mv: mvs.0,
7995 ref_mv_idx: 0,
7996 };
7997 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7998 (
7999 cstack.nearest_mv,
8000 mode_bits_of(0),
8001 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
8002 ),
8003 (
8004 ((0, 0), (0, 0)),
8005 mode_bits_of(6),
8006 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
8007 ),
8008 ];
8009 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
8010 // above, its residual priced against compound stack entry 0 -- what
8011 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
8012 let cbase = cstack
8013 .entries
8014 .first()
8015 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
8016 if let Some(new_mv) = last_new_mv
8017 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
8018 {
8019 let mvs = (new_mv, cstack.nearest_mv.1);
8020 ccands.push((
8021 mvs,
8022 mode_bits_of(3) + b0,
8023 compound_info(InterMode::NewNearestMv, mvs),
8024 ));
8025 }
8026 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
8027 ccands.dedup_by_key(|c| c.0);
8028 for (mvs, bits, info) in ccands {
8029 let trials = [
8030 (0usize, x, y, side, true),
8031 (1, x / 2, y / 2, side / 2, false),
8032 (2, x / 2, y / 2, side / 2, false),
8033 ]
8034 .map(|(plane, px, py, s, is_luma)| {
8035 let (r0, r1) = match plane {
8036 0 => (
8037 (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height),
8038 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
8039 ),
8040 1 => (
8041 (
8042 reference.u.as_slice(),
8043 reference.width / 2,
8044 chroma[0].true_width,
8045 chroma[0].true_height,
8046 ),
8047 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
8048 ),
8049 _ => (
8050 (
8051 reference.v.as_slice(),
8052 reference.width / 2,
8053 chroma[1].true_width,
8054 chroma[1].true_height,
8055 ),
8056 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
8057 ),
8058 };
8059 let prediction =
8060 predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
8061 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
8062 target.code_from_prediction(
8063 px,
8064 py,
8065 s,
8066 &prediction,
8067 true,
8068 search.base_q_idx,
8069 search.deadzone,
8070 TxbSet::Luma32Inter,
8071 )
8072 });
8073 let syntax = fixed - ref_bits + bits;
8074 let cost =
8075 trials[0].sse + trials[1].sse + trials[2].sse + search.lambda * syntax;
8076 if best.as_ref().is_none_or(|b| cost < b.0) {
8077 best = Some((cost, syntax, info, trials));
8078 }
8079 }
8080 }
8081
8082 let (skip_cost, syntax, info, skip_trials) = best?;
8083
8084 // The winner's prediction coded with a REAL residual (lane-tx64): one
8085 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
8086 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
8087 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
8088 // the skip arm already chose is re-coded: the prediction with the lowest
8089 // SSE is also the cheapest residual to code, and a second 64x64 motion
8090 // search per superblock is the wall this root was taken to SAVE.
8091 //
8092 // Priced against the skip arm through the same `symbol_bits` path, so the
8093 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
8094 // arm charges 0 instead and adds its three planes' coefficient bits.
8095 let mut chosen = (skip_cost, true, skip_trials);
8096 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
8097 // into the plane, so the tail below does not commit over its units.
8098 let mut luma_committed = false;
8099 // The residual arm's luma levels and the `txfm_split` depth the writer
8100 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
8101 // four TX_32X32 units in 64x64 ones.
8102 let mut luma_levels: Option<(Vec<i32>, u8)> = None;
8103 if residual {
8104 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
8105 let residual_trials = [0usize, 1, 2].map(|plane| {
8106 let (target, px, py, s) = if plane == 0 {
8107 (&*luma, x, y, side)
8108 } else {
8109 (&chroma[plane - 1], x / 2, y / 2, side / 2)
8110 };
8111 target.code_from_prediction(
8112 px,
8113 py,
8114 s,
8115 &chosen.2[plane].reconstruction,
8116 false,
8117 search.base_q_idx,
8118 search.deadzone,
8119 sets[plane],
8120 )
8121 });
8122 let unskip = symbol_bits(&cdf::SKIP[0], 0) - symbol_bits(&cdf::SKIP[0], 1);
8123 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
8124 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
8125 // four TX_32X32 units of `txfm_split = 1`, taken by the same
8126 // `commit_inter_luma` every other inter block's is (it commits the
8127 // winner and hands back the cost it took off the flat arm).
8128 let (levels, depth, gain) = if b64_var_tx() {
8129 let second = info.ref1.and_then(|r1| {
8130 compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| {
8131 (
8132 info.mv1,
8133 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
8134 )
8135 })
8136 });
8137 luma_committed = true;
8138 commit_inter_luma(
8139 luma,
8140 (x, y),
8141 side,
8142 info.mv,
8143 (&reference.y, reference.width, luma.true_width, luma.true_height),
8144 search,
8145 &residual_trials[0],
8146 false,
8147 second,
8148 fctx,
8149 )
8150 } else {
8151 (residual_trials[0].levels.clone(), 0, 0.0)
8152 };
8153 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
8154 + search.lambda * (syntax + unskip + coeff_bits)
8155 + gain;
8156 if cost < skip_cost {
8157 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8158 if depth == 1 {
8159 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8160 }
8161 luma_levels = Some((levels, depth));
8162 chosen = (cost, false, residual_trials);
8163 }
8164 }
8165
8166 let (cost, skip, trials) = chosen;
8167 // `commit_inter_luma` already wrote the residual arm's luma (its four
8168 // split units are not one 64-sided trial); a skip winner overwrites it.
8169 if skip || !luma_committed {
8170 luma.commit(x, y, side, &trials[0]);
8171 }
8172 chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]);
8173 chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]);
8174 Some((
8175 cost,
8176 BlockCoeffs {
8177 skip,
8178 inter: Some(info),
8179 // The chroma grids are whole TX_32X32; the luma one is the
8180 // 64-point transform's coded 32x32 corner at depth 0 and the
8181 // whole 64-sided block at depth 1 (lane-b64b).
8182 tx_depth: luma_levels.as_ref().map_or(0, |&(_, d)| d),
8183 luma: match (skip, &luma_levels) {
8184 (true, _) => Vec::new(),
8185 (false, Some((levels, 1))) => coeffs(levels, SUPERBLOCK),
8186 (false, Some((levels, _))) => coeffs(levels, BLOCK),
8187 (false, None) => coeffs(&trials[0].levels, BLOCK),
8188 },
8189 u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) },
8190 v: if skip { Vec::new() } else { coeffs(&trials[2].levels, side / 2) },
8191 ..BlockCoeffs::default()
8192 },
8193 ))
8194}
8195
8196fn search_inter_block(
8197 luma: &mut Plane,
8198 chroma: &mut [Plane; 2],
8199 (x, y): (usize, usize),
8200 search: &Search,
8201 mode_bits: &[f64; 13],
8202 reference: &Picture,
8203 stack: &MvStack,
8204 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
8205 // for the whole GOP, with the stack this block derives against it. Only
8206 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
8207 // second motion search would double the wall of the stage that already
8208 // owns most of it.
8209 extra: &[(i8, &Picture, &MvStack)],
8210 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
8211 // the caller off the same MI grid the tile writer will (empty unless the
8212 // frame carries `reference_select`).
8213 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
8214 // lane-av1obmc: the mi grid this search's neighbours were published into
8215 // (`record_mi`) and this block's own place in it -- what the OBMC
8216 // candidate's eligibility walk and neighbour plan read, the same state
8217 // the tile writer will read when it codes the `motion_mode` symbol.
8218 grid: &MiGrid,
8219 (mi_row, mi_col): (usize, usize),
8220 (mi_rows, mi_cols): (usize, usize),
8221 fctx: &crate::decode::FrameCtx,
8222) -> (BlockCoeffs, f64) {
8223 // `luma_set` is the INTRA candidates' table; the two inter candidates
8224 // below price their coefficients through `TxbSet::Luma32Inter`, which is
8225 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
8226 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
8227 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
8228 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
8229
8230 // skip / intra_inter symbol costs at a fixed context -- see this
8231 // function's doc comment.
8232 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
8233 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
8234 // `write_single_ref`'s own tree, at the fixed context this pricer uses
8235 // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN
8236 // p1=0,p3=1,p5=1.
8237 let single_ref_bits = |ref_frame: i8| {
8238 symbol_bits(&cdf::SINGLE_REF[0][0], 0)
8239 + if ref_frame == crate::mvstack::GOLDEN_FRAME {
8240 symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1)
8241 } else {
8242 symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0)
8243 }
8244 };
8245
8246 struct Candidate {
8247 cost: f64,
8248 luma: Trial,
8249 u: Trial,
8250 v: Trial,
8251 mode: u8,
8252 skip: bool,
8253 inter: Option<InterInfo>,
8254 /// The mode/mv syntax this candidate pays for, apart from its
8255 /// residual -- what the OBMC candidate below has to re-pay when it
8256 /// re-prices the winner's prediction.
8257 mode_bits: f64,
8258 }
8259 let mut best: Option<Candidate> = None;
8260 let mut consider = |candidate: Candidate| {
8261 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
8262 best = Some(candidate);
8263 }
8264 };
8265
8266 // The chroma trial an intra candidate prices does not depend on `mode`
8267 // at all -- both planes always code `DC_PRED` here (a coding choice this
8268 // search inherited, not this loop's to second-guess) at the same `reach:
8269 // Reach::none()` -- so it is the same call with the same inputs on every
8270 // one of the thirteen iterations below; run it once and reuse the result
8271 // rather than repeat an already-priced transform/quantize/entropy call
8272 // twelve times for nothing (bit-identical: the value each iteration
8273 // reads back is exactly what it used to recompute).
8274 let u_trial = chroma[0].trial(
8275 At {
8276 x: x / 2,
8277 y: y / 2,
8278 side: BLOCK / 2,
8279 reach: Reach::none(),
8280 set: chroma_set,
8281 },
8282 DC_PRED,
8283 0,
8284 search.base_q_idx,
8285 search.deadzone, fctx,
8286 );
8287 let v_trial = chroma[1].trial(
8288 At {
8289 x: x / 2,
8290 y: y / 2,
8291 side: BLOCK / 2,
8292 reach: Reach::none(),
8293 set: chroma_set,
8294 },
8295 DC_PRED,
8296 0,
8297 search.base_q_idx,
8298 search.deadzone, fctx,
8299 );
8300
8301 let intra_modes: Vec<u8> = match search.top_k {
8302 Some(k) if k < search.modes.len() => {
8303 let scored = luma.intra_scores(
8304 At {
8305 x,
8306 y,
8307 side: BLOCK,
8308 reach,
8309 set: luma_set,
8310 },
8311 search.modes,
8312 mode_bits,
8313 search.lambda, fctx,
8314 );
8315 prune_by_sad(search.modes, scored, k)
8316 }
8317 _ => search.modes.to_vec(),
8318 };
8319 census_add(5, 1);
8320 census_add(6, intra_modes.len());
8321 for &mode in &intra_modes {
8322 let luma_trial = luma.trial(
8323 At {
8324 x,
8325 y,
8326 side: BLOCK,
8327 reach,
8328 set: luma_set,
8329 },
8330 mode,
8331 0,
8332 search.base_q_idx,
8333 search.deadzone, fctx,
8334 );
8335 let u = u_trial.clone();
8336 let v = v_trial.clone();
8337 let cost = luma_trial.sse
8338 + u.sse
8339 + v.sse
8340 + search.lambda
8341 * (luma_trial.bits
8342 + u.bits
8343 + v.bits
8344 + mode_bits[usize::from(mode)]
8345 + skip_bits(false)
8346 + intra_inter_bits(false));
8347 consider(Candidate {
8348 cost,
8349 luma: luma_trial,
8350 u,
8351 v,
8352 mode,
8353 skip: false,
8354 inter: None,
8355 mode_bits: mode_bits[usize::from(mode)],
8356 });
8357 }
8358
8359 // The reference frame buffer a spec decoder holds is exactly the true
8360 // (unpadded) coded extent -- a superblock whose partition stops early at
8361 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
8362 // beyond it, so those samples are never part of the decoded picture.
8363 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
8364 // reference sample position clamp), not to this crate's own
8365 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
8366 // here would let a fractional-pel read past the true edge pick up this
8367 // encoder's own uncoded padding instead of the true edge's replicated
8368 // value a decoder computes.
8369 let ref_luma = (
8370 &reference.y,
8371 reference.width,
8372 luma.true_width,
8373 luma.true_height,
8374 );
8375 let ref_u = (
8376 &reference.u,
8377 reference.width / 2,
8378 chroma[0].true_width,
8379 chroma[0].true_height,
8380 );
8381 let ref_v = (
8382 &reference.v,
8383 reference.width / 2,
8384 chroma[1].true_width,
8385 chroma[1].true_height,
8386 );
8387 // Every single-reference mode the writer can code (spec 5.11.24's symbol
8388 // chain, mirrored by `tile::write_inter_mode`), priced with the static
8389 // CDFs at this block's own stack contexts. A candidate is a motion
8390 // vector plus the cheapest syntax that reaches it, so two modes landing
8391 // on the same vector share one set of trials: the added modes cost
8392 // mode-bit arithmetic, not another motion compensation.
8393 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
8394 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
8395 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
8396 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
8397 // the loop cannot reach is never offered below -- every candidate's
8398 // index is one this same loop walks to.
8399 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
8400 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME);
8401 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
8402 (
8403 stack.nearest_mv,
8404 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
8405 InterInfo {
8406 ref1: None,
8407 mv1: (0, 0),
8408 ref_frame: crate::mvstack::LAST_FRAME,
8409 mode: InterMode::NearestMv,
8410 mv: stack.nearest_mv,
8411 ref_mv_idx: 0,
8412 },
8413 ),
8414 // GLOBALMV is the identity model's zero vector -- this encoder writes
8415 // no `gm_params` -- and the cheapest syntax of the four on the static
8416 // content where that vector is also the right one.
8417 (
8418 (0, 0),
8419 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
8420 InterInfo {
8421 ref1: None,
8422 mv1: (0, 0),
8423 ref_frame: crate::mvstack::LAST_FRAME,
8424 mode: InterMode::GlobalMv,
8425 mv: (0, 0),
8426 ref_mv_idx: 0,
8427 },
8428 ),
8429 ];
8430 let near_bits =
8431 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
8432 for idx in 1..=2usize {
8433 if let Some(e) = stack.entries.get(idx) {
8434 cands.push((
8435 e.mv,
8436 near_bits + drl_bits(1, idx),
8437 InterInfo {
8438 ref1: None,
8439 mv1: (0, 0),
8440 ref_frame: crate::mvstack::LAST_FRAME,
8441 mode: InterMode::NearMv,
8442 mv: e.mv,
8443 ref_mv_idx: idx as u8,
8444 },
8445 ));
8446 }
8447 }
8448
8449 let source_block = luma.source_block(x, y, BLOCK);
8450 let (seeds, seed_n) = mv_seeds(stack);
8451 #[cfg(test)]
8452 let t = stage_start();
8453 let found = motion::search(
8454 ref_luma.0,
8455 ref_luma.1,
8456 ref_luma.2,
8457 ref_luma.3,
8458 &source_block,
8459 x,
8460 y,
8461 BLOCK,
8462 BLOCK,
8463 stack.pred_mv,
8464 &seeds[..seed_n],
8465 search.lambda, fctx,
8466 1,
8467 );
8468 #[cfg(test)]
8469 stage_since(0, t);
8470 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
8471 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
8472 // the same vector costs a different residual from each: take the index
8473 // whose residual plus DRL bits is cheapest, not entry 0 by default.
8474 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
8475 cands.push((
8476 mv,
8477 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
8478 InterInfo {
8479 ref1: None,
8480 mv1: (0, 0),
8481 ref_frame: crate::mvstack::LAST_FRAME,
8482 mode: InterMode::NewMv,
8483 mv,
8484 ref_mv_idx,
8485 },
8486 ));
8487 }
8488
8489 // Each extra reference's own `NEWMV` vector, for the compound
8490 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
8491 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
8492 for &(ref_frame, g, gstack) in extra {
8493 let g_ref_bits = single_ref_bits(ref_frame);
8494 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
8495 cands.push((
8496 gstack.nearest_mv,
8497 g_ref_bits
8498 + g_not_new
8499 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
8500 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
8501 InterInfo {
8502 ref1: None,
8503 mv1: (0, 0),
8504 ref_frame,
8505 mode: InterMode::NearestMv,
8506 mv: gstack.nearest_mv,
8507 ref_mv_idx: 0,
8508 },
8509 ));
8510 cands.push((
8511 (0, 0),
8512 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
8513 InterInfo {
8514 ref1: None,
8515 mv1: (0, 0),
8516 ref_frame,
8517 mode: InterMode::GlobalMv,
8518 mv: (0, 0),
8519 ref_mv_idx: 0,
8520 },
8521 ));
8522 // A motion search of this reference's own: without it, GOLDEN/ALTREF
8523 // can only be coded at a vector some neighbour already found, which
8524 // is why they carried a third of the inter blocks at their two
8525 // search-free modes alone.
8526 // The search is skipped when this reference's own NEARESTMV already
8527 // prices out `margin` times better than LAST's best vector does --
8528 // one candidate evaluation (`motion::cost_at`) standing in for a
8529 // whole search of ~50.
8530 let margin = extra_new_skip_margin();
8531 let skip_search = extra_ref_new_mv()
8532 && margin > 0.0
8533 && motion::cost_at(
8534 &g.y,
8535 g.width,
8536 luma.true_width,
8537 luma.true_height,
8538 &source_block,
8539 x,
8540 y,
8541 BLOCK,
8542 BLOCK,
8543 gstack.nearest_mv,
8544 gstack.pred_mv,
8545 search.lambda,
8546 fctx,
8547 ) * margin
8548 <= found.cost;
8549 if extra_ref_new_mv() && !skip_search {
8550 let (gseeds, gn) = mv_seeds(gstack);
8551 #[cfg(test)]
8552 let t = stage_start();
8553 let gfound = motion::search(
8554 &g.y,
8555 g.width,
8556 luma.true_width,
8557 luma.true_height,
8558 &source_block,
8559 x,
8560 y,
8561 BLOCK,
8562 BLOCK,
8563 gstack.pred_mv,
8564 &gseeds[..gn],
8565 search.lambda, fctx,
8566 ref_distance(ref_frame),
8567 );
8568 #[cfg(test)]
8569 stage_since(0, t);
8570 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
8571 extra_new_mvs.push((ref_frame, gmv));
8572 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
8573 cands.push((
8574 gmv,
8575 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
8576 InterInfo {
8577 ref1: None,
8578 mv1: (0, 0),
8579 ref_frame,
8580 mode: InterMode::NewMv,
8581 mv: gmv,
8582 ref_mv_idx,
8583 },
8584 ));
8585 }
8586 }
8587 }
8588
8589 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
8590 // trial set each: both references predict the block and the two
8591 // predictions are averaged, which is what pays on content where neither
8592 // reference alone is right. Priced with the same static-CDF approximation
8593 // the single-reference candidates use, plus the compound-only symbols
8594 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
8595 // The two compound-mode arms, each measured alone on the BD gate before
8596 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
8597 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
8598 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
8599 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
8600 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
8601 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
8602 // the keep rule. Still behind the knob.
8603 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
8604 let half_new = true;
8605 for (ref1, g, cstack) in compound {
8606 let (ref1, g) = (*ref1, *g);
8607 let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME)
8608 .contains(&ref1);
8609 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
8610 + if uni {
8611 // LAST + a backward reference: `comp_ref_type` = bidirectional,
8612 // `comp_ref` LAST, `comp_bwdref` ALTREF.
8613 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
8614 + symbol_bits(&cdf::COMP_REF[0][0], 0)
8615 + symbol_bits(&cdf::COMP_REF[0][1], 0)
8616 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
8617 } else {
8618 // LAST + GOLDEN: unidirectional, `uni_comp_ref` p0/p1/p2.
8619 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
8620 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
8621 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
8622 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
8623 };
8624 let mode_ctx =
8625 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
8626 let mode_bits_of =
8627 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
8628 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
8629 (
8630 cstack.nearest_mv,
8631 mode_bits_of(0),
8632 InterInfo {
8633 ref_frame: crate::mvstack::LAST_FRAME,
8634 mode: InterMode::NearestNearestMv,
8635 mv: cstack.nearest_mv.0,
8636 mv1: cstack.nearest_mv.1,
8637 ref1: Some(ref1),
8638 ref_mv_idx: 0,
8639 },
8640 ),
8641 (
8642 ((0, 0), (0, 0)),
8643 mode_bits_of(6),
8644 InterInfo {
8645 ref_frame: crate::mvstack::LAST_FRAME,
8646 mode: InterMode::GlobalGlobalMv,
8647 mv: (0, 0),
8648 mv1: (0, 0),
8649 ref1: Some(ref1),
8650 ref_mv_idx: 0,
8651 },
8652 ),
8653 ];
8654 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
8655 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
8656 // the stack is deep enough for that walk to read one.
8657 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
8658 let drl = if cstack.entries.len() > 2 {
8659 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
8660 } else {
8661 0.0
8662 };
8663 ccands.push((
8664 (e.mv0, e.mv1),
8665 mode_bits_of(1) + drl,
8666 InterInfo {
8667 ref_frame: crate::mvstack::LAST_FRAME,
8668 mode: InterMode::NearNearMv,
8669 mv: e.mv0,
8670 mv1: e.mv1,
8671 ref1: Some(ref1),
8672 ref_mv_idx: 0,
8673 },
8674 ));
8675 }
8676 // The half-new modes and `NEW_NEWMV`, all seeded from the two
8677 // single-reference searches this block already ran -- no joint search
8678 // of its own. Every residual is priced against stack entry 0, which
8679 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
8680 let cbase = cstack
8681 .entries
8682 .first()
8683 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
8684 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
8685 ccands.push((
8686 (mv, cstack.nearest_mv.1),
8687 mode_bits_of(3) + b0,
8688 InterInfo {
8689 ref_frame: crate::mvstack::LAST_FRAME,
8690 mode: InterMode::NewNearestMv,
8691 mv,
8692 mv1: cstack.nearest_mv.1,
8693 ref1: Some(ref1),
8694 ref_mv_idx: 0,
8695 },
8696 ));
8697 }
8698 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
8699 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
8700 ccands.push((
8701 (cstack.nearest_mv.0, mv1),
8702 mode_bits_of(2) + b1,
8703 InterInfo {
8704 ref_frame: crate::mvstack::LAST_FRAME,
8705 mode: InterMode::NearestNewMv,
8706 mv: cstack.nearest_mv.0,
8707 mv1,
8708 ref1: Some(ref1),
8709 ref_mv_idx: 0,
8710 },
8711 ));
8712 }
8713 let base = cbase;
8714 if let (Some(b0), Some(b1)) = (
8715 mv_residual_bits(mv, base.0),
8716 mv_residual_bits(mv1, base.1),
8717 ) {
8718 ccands.push((
8719 (mv, mv1),
8720 mode_bits_of(7) + b0 + b1,
8721 InterInfo {
8722 ref_frame: crate::mvstack::LAST_FRAME,
8723 mode: InterMode::NewNewMv,
8724 mv,
8725 mv1,
8726 ref1: Some(ref1),
8727 ref_mv_idx: 0,
8728 },
8729 ));
8730 }
8731 }
8732 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
8733 ccands.dedup_by_key(|c| c.0);
8734 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
8735 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
8736 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
8737 for (mvs, bits, info) in ccands {
8738 let luma_trial = mc_trial_compound(
8739 luma, x, y, BLOCK, mvs, true,
8740 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
8741 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
8742 );
8743 let u = mc_trial_compound(
8744 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
8745 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
8746 search.base_q_idx, search.deadzone, chroma_set, fctx,
8747 );
8748 let v = mc_trial_compound(
8749 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
8750 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
8751 search.base_q_idx, search.deadzone, chroma_set, fctx,
8752 );
8753 let skip = luma_trial.levels.iter().all(|&l| l == 0)
8754 && u.levels.iter().all(|&l| l == 0)
8755 && v.levels.iter().all(|&l| l == 0);
8756 let cost = luma_trial.sse
8757 + u.sse
8758 + v.sse
8759 + search.lambda
8760 * (skip_bits(skip)
8761 + intra_inter_bits(true)
8762 + bits
8763 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
8764 consider(Candidate {
8765 cost,
8766 luma: luma_trial,
8767 u,
8768 v,
8769 mode: DC_PRED,
8770 skip,
8771 mode_bits: bits,
8772 inter: Some(info),
8773 });
8774 }
8775 }
8776
8777 // One trial set per distinct (reference, vector) pair: sort, cheapest
8778 // syntax first, and drop the rest of each pair's run.
8779 cands.sort_by(|a, b| {
8780 (a.2.ref_frame, a.0)
8781 .cmp(&(b.2.ref_frame, b.0))
8782 .then(a.1.total_cmp(&b.1))
8783 });
8784 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
8785 census_add(7, cands.len());
8786 {
8787 for (mv, mode_bits_inter, info) in cands {
8788 let (ref_luma, ref_u, ref_v) = match extra
8789 .iter()
8790 .find(|(r, _, _)| *r == info.ref_frame)
8791 {
8792 Some(&(_, g, _)) => (
8793 (&g.y, g.width, luma.true_width, luma.true_height),
8794 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
8795 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
8796 ),
8797 None => (ref_luma, ref_u, ref_v),
8798 };
8799 let luma_trial = mc_trial(
8800 luma,
8801 x,
8802 y,
8803 BLOCK,
8804 mv,
8805 true,
8806 ref_luma.0,
8807 ref_luma.1,
8808 ref_luma.2,
8809 ref_luma.3,
8810 false,
8811 search.base_q_idx,
8812 search.deadzone,
8813 TxbSet::Luma32Inter, fctx,
8814 );
8815 let u = mc_trial(
8816 &chroma[0],
8817 x / 2,
8818 y / 2,
8819 BLOCK / 2,
8820 mv,
8821 false,
8822 ref_u.0,
8823 ref_u.1,
8824 ref_u.2,
8825 ref_u.3,
8826 false,
8827 search.base_q_idx,
8828 search.deadzone,
8829 chroma_set, fctx,
8830 );
8831 let v = mc_trial(
8832 &chroma[1],
8833 x / 2,
8834 y / 2,
8835 BLOCK / 2,
8836 mv,
8837 false,
8838 ref_v.0,
8839 ref_v.1,
8840 ref_v.2,
8841 ref_v.3,
8842 false,
8843 search.base_q_idx,
8844 search.deadzone,
8845 chroma_set, fctx,
8846 );
8847 let skip = luma_trial.levels.iter().all(|&l| l == 0)
8848 && u.levels.iter().all(|&l| l == 0)
8849 && v.levels.iter().all(|&l| l == 0);
8850 let cost = luma_trial.sse
8851 + u.sse
8852 + v.sse
8853 + search.lambda
8854 * (skip_bits(skip)
8855 + intra_inter_bits(true)
8856 + mode_bits_inter
8857 + if skip {
8858 0.0
8859 } else {
8860 luma_trial.bits + u.bits + v.bits
8861 });
8862 consider(Candidate {
8863 cost,
8864 luma: luma_trial,
8865 u,
8866 v,
8867 mode: DC_PRED,
8868 skip,
8869 mode_bits: mode_bits_inter,
8870 inter: Some(info),
8871 });
8872 }
8873 }
8874
8875 let best = best.expect("the search offers at least the intra modes");
8876 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
8877 // offered to the SINGLE-REFERENCE winner only -- libaom's
8878 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
8879 // compound block, so the writer codes no symbol for one. The prediction
8880 // is built by the DECODER's own plan and blend
8881 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
8882 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
8883 // this search's `grid` already carries, so what is priced here is what a
8884 // decoder reconstructs -- never a second implementation of the blend.
8885 //
8886 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
8887 // on). Native crop BD, the standing recipe, with it on against the same
8888 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
8889 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
8890 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
8891 // one UP -- the keep rule wants two down and one flat, so it stays off.
8892 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
8893 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
8894 // things bound it and are the upgrade path: only the 32x32 winner is
8895 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
8896 // that is where libaom cashes most of its OBMC gain), and the symbol/
8897 // residual price here is the static-CDF estimate.
8898 let mut best = best;
8899 let mut motion_won = 0u8;
8900 if let Some(info) = best.inter.filter(|i| {
8901 i.ref1.is_none()
8902 && (crate::envflags::env_flag!("EC_AV1_OBMC")
8903 || warp_on())
8904 }) {
8905 let mut refs: [Option<&Picture>; 8] = [None; 8];
8906 refs[LAST_FRAME as usize] = Some(reference);
8907 for &(r, p, _) in extra {
8908 refs[r as usize] = Some(p);
8909 }
8910 // This block's OWN reference planes: the single-reference winner may
8911 // be one of the extra references, not LAST.
8912 let planes: [(&[u16], usize, usize, usize); 3] =
8913 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
8914 Some(&(_, g, _)) => [
8915 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
8916 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
8917 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
8918 ],
8919 None => [
8920 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8921 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
8922 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
8923 ],
8924 };
8925 // The alphabet `tile::write_motion_mode` will code this block's
8926 // symbol against, mirrored term for term (libaom
8927 // `motion_mode_allowed`).
8928 let warp_alphabet = warp_on()
8929 && crate::decode::num_proj_ref(
8930 grid,
8931 mi_row,
8932 mi_col,
8933 8,
8934 8,
8935 mi_cols,
8936 mi_rows,
8937 info.ref_frame,
8938 fctx,
8939 ) >= 1;
8940 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
8941 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
8942 if crate::envflags::env_flag!("EC_AV1_OBMC") {
8943 if let Some(pred) = obmc_prediction(
8944 grid,
8945 (mi_row, mi_col),
8946 (mi_rows, mi_cols),
8947 (x, y),
8948 BLOCK,
8949 info.mv,
8950 &refs,
8951 planes,
8952 reference.width,
8953 fctx,
8954 ) {
8955 candidates.push((1, pred));
8956 }
8957 }
8958 if warp_alphabet {
8959 if let Some(pred) = warp_prediction(
8960 grid,
8961 (mi_row, mi_col),
8962 (mi_rows, mi_cols),
8963 (x, y),
8964 BLOCK,
8965 info.mv,
8966 info.ref_frame,
8967 planes,
8968 fctx,
8969 ) {
8970 candidates.push((2, pred));
8971 }
8972 }
8973 for (motion, pred) in candidates {
8974 let luma_trial = luma.code_from_prediction(
8975 x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
8976 TxbSet::Luma32Inter,
8977 );
8978 let u = chroma[0].code_from_prediction(
8979 x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
8980 chroma_set,
8981 );
8982 let v = chroma[1].code_from_prediction(
8983 x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
8984 chroma_set,
8985 );
8986 let skip = luma_trial.levels.iter().all(|&l| l == 0)
8987 && u.levels.iter().all(|&l| l == 0)
8988 && v.levels.iter().all(|&l| l == 0);
8989 let cost = luma_trial.sse
8990 + u.sse
8991 + v.sse
8992 + search.lambda
8993 * (skip_bits(skip)
8994 + intra_inter_bits(true)
8995 + best.mode_bits
8996 + mm(motion)
8997 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
8998 if cost < best.cost + search.lambda * mm(motion_won) {
8999 motion_won = motion;
9000 best = Candidate {
9001 cost,
9002 luma: luma_trial,
9003 u,
9004 v,
9005 mode: DC_PRED,
9006 skip,
9007 mode_bits: best.mode_bits,
9008 inter: best.inter,
9009 };
9010 }
9011 }
9012 }
9013 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
9014 // default OFF): the four 16x16 units of `commit_inter_luma` against the
9015 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
9016 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
9017 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
9018 // it, and it is worse again on the deciding native table: film 1080p
9019 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
9020 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
9021 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
9022 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
9023 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
9024 // +28.4/+47.4/-4.0 -- the native table decides.)
9025 //
9026 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
9027 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
9028 // either, and the census names the row: the split units' own set
9029 // `Luma16Inter` is priced within 1.4% of what it is written at in every
9030 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
9031 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
9032 // so a perfect pricer would split even more, and more splitting is what
9033 // measured worse. The four extra txb_skip/eob symbols simply cost more
9034 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
9035 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
9036 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
9037 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
9038 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
9039 // plain translation, which is not the prediction it was priced from.
9040 let (levels, tx_depth, dcost) = match best.inter.filter(|_| motion_won == 0) {
9041 Some(info) => {
9042 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
9043 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
9044 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
9045 };
9046 let second = info.ref1.and_then(|r| {
9047 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
9048 (
9049 info.mv1,
9050 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
9051 )
9052 })
9053 });
9054 match info.ref1.is_some() && second.is_none() {
9055 true => {
9056 luma.commit(x, y, BLOCK, &best.luma);
9057 (best.luma.levels.clone(), 0, 0.0)
9058 }
9059 false => commit_inter_luma(
9060 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,
9061 fctx,
9062 ),
9063 }
9064 }
9065 None => {
9066 luma.commit(x, y, BLOCK, &best.luma);
9067 (best.luma.levels.clone(), 0, 0.0)
9068 }
9069 };
9070 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
9071 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
9072 (
9073 BlockCoeffs {
9074 angle_delta_y: 0,
9075 cfl_alphas: None,
9076 filter_intra: None,
9077 luma: coeffs(&levels, BLOCK),
9078 u: coeffs(&best.u.levels, BLOCK / 2),
9079 v: coeffs(&best.v.levels, BLOCK / 2),
9080 mode: best.mode,
9081 uv_mode: DC_PRED,
9082 skip: best.skip,
9083 inter: best.inter,
9084 motion_mode: motion_won,
9085 eight: None,
9086 dv: None,
9087 palette: None,
9088 palette_uv: None,
9089 tx_depth,
9090 },
9091 best.cost + dcost,
9092 )
9093}
9094
9095/// lane-av1tpl: the strength `k` of the temporal lambda weighting
9096/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
9097/// is what every measurement before this lane was taken on. Swept by
9098/// `EC_AV1_TPL=<k>`.
9099///
9100/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
9101/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
9102/// baseline exactly, which is the control the rest of the table is read
9103/// against:
9104///
9105/// | k | film 1080p | film 2160p | screen |
9106/// |---|---|---|---|
9107/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
9108/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
9109/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
9110/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
9111/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
9112///
9113/// 0.5 is the only arm that is at least flat on every row and down on five of
9114/// the six columns, so it ships as the default. The lookahead pass that feeds
9115/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
9116const TPL_STRENGTH: f64 = 0.5;
9117
9118/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
9119/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
9120/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
9121/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
9122///
9123/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
9124/// nothing to vary the quantizer BY and codes no delta syntax at all.
9125fn deltaq_res_log2() -> Option<u8> {
9126 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
9127 u8::MAX => {}
9128 4 => return None,
9129 r => return Some(r),
9130 }
9131 match crate::envflags::var("EC_AV1_DELTAQ").ok().as_deref().map(str::trim) {
9132 Some("0") => None,
9133 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
9134 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
9135 }
9136}
9137
9138/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
9139/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
9140/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
9141/// speed presets take, because the streams every other test pins move under
9142/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
9143static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 =
9144 std::sync::atomic::AtomicU8::new(u8::MAX);
9145
9146/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
9147#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
9148pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
9149 DELTAQ_OVERRIDE.store(
9150 res_log2.unwrap_or(u8::MAX),
9151 std::sync::atomic::Ordering::Relaxed,
9152 );
9153}
9154
9155/// How much of the derived qindex step is actually taken
9156/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
9157fn deltaq_k() -> f64 {
9158 crate::envflags::var("EC_AV1_DELTAQ_K")
9159 .ok()
9160 .and_then(|v| v.trim().parse::<f64>().ok())
9161 .filter(|k| k.is_finite() && *k >= 0.0)
9162 .unwrap_or(1.0)
9163}
9164
9165/// The largest qindex the map may move a superblock by, either way
9166/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
9167/// deltaq around a quarter of the base qindex).
9168fn deltaq_clamp() -> i32 {
9169 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
9170 .ok()
9171 .and_then(|v| v.trim().parse::<i32>().ok())
9172 .filter(|c| (0..=63).contains(c))
9173 .unwrap_or(16)
9174}
9175
9176/// The qindex a lambda factor `f` asks for, derived rather than fitted.
9177///
9178/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
9179/// square of the quantizer step (`encode_inter_frame`'s own
9180/// `lambda = .. * step * step`), so the step this superblock wants is
9181/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
9182/// step ratio is inverted through the table itself -- the index whose `ac_q`
9183/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
9184/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
9185/// bounds it, and the answer is snapped onto the `res` grid so that every
9186/// superblock's qindex is congruent to `base` and the coded delta is a whole
9187/// number of steps.
9188fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
9189 let base_ac = f64::from(ac_q(8, i32::from(base)));
9190 let target = base_ac * f.max(1e-6).sqrt();
9191 let exact = (1..=255)
9192 .min_by(|&a, &b| {
9193 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
9194 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
9195 })
9196 .expect("the qindex range is not empty")
9197 - i32::from(base);
9198 let want = (exact as f64 * k).round() as i32;
9199 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
9200 // and need not be a whole number of steps, and clamping afterwards would
9201 // hand back a qindex that is not congruent to `base`.
9202 let max_steps = clamp / res;
9203 let steps = (want as f64 / f64::from(res)).round() as i32;
9204 let delta = steps.clamp(-max_steps, max_steps) * res;
9205 (i32::from(base) + delta).clamp(1, 255) as u8
9206}
9207
9208/// How many DISTINCT per-superblock quantizer levels the last inter frame's
9209/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
9210/// (class `gate-blind-to-feature`: every exactness assert below passes on a
9211/// grid that is one flat value, i.e. on no delta_q at all). Process-global
9212/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
9213/// keeps the LARGEST count seen since the last read.
9214static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
9215
9216/// [`DELTAQ_LEVELS`], reset to 0.
9217#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9218pub(crate) fn take_deltaq_levels() -> usize {
9219 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
9220}
9221
9222/// This superblock's search state: the quantizer it is coded at, and the
9223/// lambda that quantizer implies. RD lambda goes as the square of the step,
9224/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
9225/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
9226/// before lane-deltaq).
9227fn sb_q_search<'m>(
9228 sb_q: &[u8],
9229 sb_cols: usize,
9230 base_q_idx: u8,
9231 (sb_r, sb_c): (usize, usize),
9232 base: Search<'m>,
9233) -> Search<'m> {
9234 let q = sb_q[sb_r * sb_cols + sb_c];
9235 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
9236 Search { base_q_idx: q, lambda: base.lambda * ratio * ratio, ..base }
9237}
9238
9239fn tpl_strength() -> f64 {
9240 std::env::var("EC_AV1_TPL")
9241 .ok()
9242 .and_then(|v| v.parse::<f64>().ok())
9243 .filter(|k| k.is_finite() && *k >= 0.0)
9244 .unwrap_or(TPL_STRENGTH)
9245}
9246
9247/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
9248/// the frame being coded. 1 turns the weighting off; 2 is the shipped
9249/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
9250/// [`tpl_propagating`], which is the map that can actually use them and is
9251/// the default since lane-av1tpl3, so the default window is 8. Swept by
9252/// `EC_AV1_TPL_D=<d>`.
9253///
9254/// The streaming facade holds `depth - 1` pictures back so it feeds
9255/// `encode_inter_frame` the same window `encode_sequence` does; both read
9256/// THIS function, so the two paths cannot disagree about the window.
9257pub(crate) const TPL_DEPTH: usize = 8;
9258
9259/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
9260/// 0.5 is libaom's own square-root compression of its dependence ratio.
9261const TPL_POWER: f64 = 0.5;
9262
9263/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
9264/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
9265///
9266/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
9267/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
9268/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
9269///
9270/// | k | D | p | film 1080p | film 2160p | screen |
9271/// |---|---|---|---|---|---|
9272/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
9273/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
9274/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
9275/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
9276/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
9277/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
9278/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
9279/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
9280/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
9281/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
9282/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
9283/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
9284///
9285/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
9286/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
9287/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
9288/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
9289/// 0.1..0.4 UP on film 2160p, so it shipped off.
9290///
9291/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
9292/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
9293/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
9294/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
9295/// wherever the window leans on a flat bar, which is exactly where coding is
9296/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
9297/// (libaom's own granularity) puts a busy cell's denominator next to the flat
9298/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
9299/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
9300/// the same native gate (baseline = the shipped one-frame map):
9301///
9302/// | arm | film 1080p | film 2160p | screen |
9303/// |---|---|---|---|
9304/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
9305/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
9306/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
9307/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
9308/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
9309/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
9310/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
9311/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
9312/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
9313/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
9314///
9315/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
9316/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
9317/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
9318/// floor is a real effect on the ratio and never a win once the aggregation
9319/// is in -- the aggregation is the same fix, done where libaom does it.
9320fn tpl_propagating() -> bool {
9321 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
9322}
9323
9324pub(crate) fn tpl_depth() -> usize {
9325 std::env::var("EC_AV1_TPL_D")
9326 .ok()
9327 .and_then(|v| v.parse::<usize>().ok())
9328 .filter(|d| *d >= 1)
9329 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
9330 .max(1)
9331}
9332
9333/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
9334/// process, so the gate can price it against the encode it rides on.
9335static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
9336
9337/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
9338/// the winning displacement and its SAD.
9339///
9340/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
9341/// the left/above winners, first-best tie-break. Built once on the frame's
9342/// own thread and read-only afterwards, so it cannot make a tile's bytes
9343/// depend on the thread count.
9344fn tpl_coarse_pass(
9345 cur: &[u8],
9346 next: &[u8],
9347 width: usize,
9348 height: usize,
9349) -> Vec<((i32, i32), u32)> {
9350 let (cells_x, cells_y) = (width / 16, height / 16);
9351 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
9352 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
9353 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
9354 return u32::MAX;
9355 }
9356 let (sx, sy) = (sx as usize, sy as usize);
9357 let mut sum = 0u32;
9358 for r in 0..16 {
9359 let a = &next[(by + r) * width + bx..][..16];
9360 let b = &cur[(sy + r) * width + sx..][..16];
9361 sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>();
9362 }
9363 sum
9364 };
9365 let mut out = Vec::with_capacity(cells_x * cells_y);
9366 let mut above = vec![(0i32, 0i32); cells_x];
9367 for cy in 0..cells_y {
9368 let mut left = (0i32, 0i32);
9369 for cx in 0..cells_x {
9370 let (bx, by) = (cx * 16, cy * 16);
9371 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
9372 for cand in [left, above[cx]] {
9373 if cand != (0, 0) {
9374 let s = sad(bx, by, cand);
9375 if s < best.0 {
9376 best = (s, cand);
9377 }
9378 }
9379 }
9380 for step in [8i32, 4, 2, 1] {
9381 let centre = best.1;
9382 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
9383 let mv = (centre.0 + dx, centre.1 + dy);
9384 if mv.0.abs() > 32 || mv.1.abs() > 32 {
9385 continue;
9386 }
9387 let s = sad(bx, by, mv);
9388 if s < best.0 {
9389 best = (s, mv);
9390 }
9391 }
9392 }
9393 left = best.1;
9394 above[cx] = best.1;
9395 out.push((best.1, best.0));
9396 }
9397 }
9398 out
9399}
9400
9401/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
9402/// transform: here, the mean absolute deviation of the cell from its own DC.
9403/// It is the denominator every propagated cost is read against, so only its
9404/// SHAPE across the frame matters, not its scale.
9405fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
9406 let (cells_x, cells_y) = (width / 16, height / 16);
9407 let mut out = Vec::with_capacity(cells_x * cells_y);
9408 for cy in 0..cells_y {
9409 for cx in 0..cells_x {
9410 let (bx, by) = (cx * 16, cy * 16);
9411 let mut sum = 0u32;
9412 for r in 0..16 {
9413 sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>();
9414 }
9415 let dc = ((sum + 128) / 256) as u8;
9416 let mut cost = 0u32;
9417 for r in 0..16 {
9418 cost += frame[(by + r) * width + bx..][..16]
9419 .iter()
9420 .map(|&p| u32::from(p.abs_diff(dc)))
9421 .sum::<u32>();
9422 }
9423 out.push(cost);
9424 }
9425 }
9426 out
9427}
9428
9429/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
9430/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
9431/// splats its own area, at its winning displacement, onto the (at most four)
9432/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
9433fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
9434 let start = std::time::Instant::now();
9435 let (cells_x, cells_y) = (width / 16, height / 16);
9436 let pass = tpl_coarse_pass(cur, next, width, height);
9437 let mut area = vec![0.0f64; cells_x * cells_y];
9438 for cy in 0..cells_y {
9439 for cx in 0..cells_x {
9440 let (mv, _) = pass[cy * cells_x + cx];
9441 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
9442 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
9443 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
9444 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
9445 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
9446 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
9447 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
9448 }
9449 }
9450 }
9451 }
9452 TPL_NANOS.fetch_add(
9453 start.elapsed().as_nanos() as u64,
9454 std::sync::atomic::Ordering::Relaxed,
9455 );
9456 area
9457}
9458
9459/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
9460/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
9461/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
9462/// Decreasing in referenced-ness (a block the next frame leans on is coded
9463/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
9464/// total lambda scale is only redistributed, never moved -- a global move is
9465/// the thing lane-av1lambda already measured inert.
9466fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
9467 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
9468 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
9469 let mut out = Vec::with_capacity(sb_cols * sb_rows);
9470 for sr in 0..sb_rows {
9471 for sc in 0..sb_cols {
9472 let mut sum = 0.0;
9473 for r in 0..4 {
9474 for c in 0..4 {
9475 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
9476 }
9477 }
9478 let w_rel = sum / 16.0 / mean;
9479 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
9480 }
9481 }
9482 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
9483 let mut hist = [0usize; 8];
9484 for w in map {
9485 hist[((w / mean * 2.0) as usize).min(7)] += 1;
9486 }
9487 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
9488 eprintln!(
9489 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
9490 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
9491 map.len(),
9492 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
9493 );
9494 }
9495 out
9496}
9497
9498/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
9499/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
9500/// much of the WHOLE lookahead window leans on that cell.
9501///
9502/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
9503/// coarse pass gives a displacement and an inter cost; a cell's own
9504/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
9505/// cell well saves the frames that predict from it -- and it is splatted,
9506/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
9507/// displacement lands on. Walking `f` from the far end of the window back to
9508/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
9509/// area map could not do at all.
9510///
9511/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
9512/// factor over the frame is exactly 1: a cell the window leans on is coded
9513/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
9514/// scale only moves around, never up or down -- a global move is what
9515/// lane-av1lambda already measured inert.
9516fn tpl_lambda_factors(frames: &[&[u8]], width: usize, height: usize, k: f64) -> Vec<f64> {
9517 let start = std::time::Instant::now();
9518 let (cells_x, cells_y) = (width / 16, height / 16);
9519 let cells = cells_x * cells_y;
9520 let levels = frames.len();
9521 let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect();
9522 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
9523 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
9524 .collect();
9525 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
9526 for f in (1..levels).rev() {
9527 for cy in 0..cells_y {
9528 for cx in 0..cells_x {
9529 let ci = cy * cells_x + cx;
9530 let (mv, inter) = passes[f - 1][ci];
9531 let saved = f64::from(intra[f][ci].saturating_sub(inter));
9532 let propagate = saved + mc_dep[f][ci];
9533 if propagate <= 0.0 {
9534 continue;
9535 }
9536 // The 16x16 window of the PREVIOUS frame this cell predicted
9537 // from, spread over the cells it overlaps.
9538 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
9539 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
9540 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
9541 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
9542 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
9543 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
9544 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
9545 }
9546 }
9547 }
9548 }
9549 }
9550 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
9551 // tail (a nearly flat cell the window leans on has a tiny denominator),
9552 // and at p = 1 that tail slams into the clamp. libaom reads its own
9553 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
9554 // sweeps the exponent, 1 being the raw ratio.
9555 let power = std::env::var("EC_AV1_TPL_P")
9556 .ok()
9557 .and_then(|v| v.parse::<f64>().ok())
9558 .filter(|p| p.is_finite() && *p > 0.0)
9559 .unwrap_or(TPL_POWER);
9560 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
9561 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
9562 // `0` to take either back out); `FLOOR` defaults to off.
9563 //
9564 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
9565 // frame's own mean intra cost. A cell of flat content has a near-zero
9566 // MAD, so its ratio explodes exactly where coding is cheap.
9567 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
9568 // and mc_dep are summed over the 64x64 superblock first -- libaom's
9569 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
9570 // per-16x16 numbers), which is also what makes the ratio survive one
9571 // flat cell next to a busy one.
9572 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
9573 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
9574 // harder than the `p` exponent alone can.
9575 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
9576 .ok()
9577 .and_then(|v| v.parse::<f64>().ok())
9578 .filter(|f| f.is_finite() && *f >= 0.0)
9579 .unwrap_or(0.0);
9580 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
9581 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
9582 let intra_mean =
9583 intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
9584 let floor = floor_frac * intra_mean;
9585 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
9586 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
9587 // every cell under it. The edge groups are partial and summed as they are.
9588 let ratio: Vec<f64> = if sb_agg {
9589 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
9590 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
9591 for cy in 0..cells_y {
9592 for cx in 0..cells_x {
9593 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
9594 e.0 += mc_dep[0][cy * cells_x + cx];
9595 e.1 += denom(cy * cells_x + cx);
9596 }
9597 }
9598 (0..cells)
9599 .map(|c| {
9600 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
9601 dep / den.max(1.0)
9602 })
9603 .collect()
9604 } else {
9605 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
9606 };
9607 let mut out: Vec<f64> = ratio
9608 .iter()
9609 .map(|&r| {
9610 let r = if log_beta { (1.0 + r).log2() } else { r };
9611 (1.0 + k * r).powf(-power)
9612 })
9613 .collect();
9614 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
9615 for f in &mut out {
9616 *f = (*f / mean).clamp(0.25, 4.0);
9617 }
9618 TPL_NANOS.fetch_add(
9619 start.elapsed().as_nanos() as u64,
9620 std::sync::atomic::Ordering::Relaxed,
9621 );
9622 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
9623 let mut hist = [0usize; 8];
9624 for &f in &out {
9625 hist[((f * 4.0) as usize).min(7)] += 1;
9626 }
9627 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
9628 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
9629 eprintln!(
9630 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
9631 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
9632 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
9633 );
9634 }
9635 out
9636}
9637
9638/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
9639/// references name, which slot it refreshes, whether it is shown when it is
9640/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
9641/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
9642/// 0/2 alternation, every frame shown, every reference in the past).
9643///
9644/// The sign bias is carried rather than derived here because only the caller
9645/// knows what order hint each slot holds; it is armed onto the tile writer
9646/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
9647/// the writer scans the same stacks the decoder will.
9648#[derive(Debug, Clone, Copy)]
9649pub(crate) struct PyramidFrame {
9650 /// The slot `LAST_FRAME` (and every reference this encoder does not name
9651 /// apart) reads.
9652 pub last_slot: u8,
9653 /// The single slot `refresh_frame_flags` sets.
9654 pub self_slot: u8,
9655 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
9656 /// pyramid, which is what makes `sign_bias`'s last entry true.
9657 pub altref_slot: u8,
9658 /// `show_frame`: false for a hidden frame, output later by a
9659 /// `show_existing_frame` header.
9660 pub show_frame: bool,
9661 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
9662 pub sign_bias: crate::mvstack::SignBiasTable,
9663}
9664
9665/// Encodes one picture as an inter frame predicting from `reference`'s
9666/// reconstruction, which the caller decoded (or, for the frame right after
9667/// the key frame, is the key frame's own reconstruction).
9668pub(crate) fn encode_inter_frame(
9669 picture: &Picture,
9670 reference: &Picture,
9671 base_q_idx: u8,
9672 deadzone: f64,
9673 order_hint: u32,
9674 // The order hint each of the seven `ref_frame_idx` entries names, which a
9675 // decoder reads out of its own reference state -- only spec 5.9.22's
9676 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
9677 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
9678 // callers that follow this crate's own flat slot plan.
9679 order_hints: [u32; 7],
9680 render: (usize, usize),
9681 // The tables this frame's writer starts from: what the previous frame
9682 // stored into the slot this one's `primary_ref_frame` names. `None`
9683 // starts from the defaults, which is right only for the frame straight
9684 // after a key frame.
9685 start_cdfs: Option<&crate::cdf_state::Cdfs>,
9686 // The key frame's own (padded) reconstruction, which every frame of the
9687 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
9688 // with `LAST_FRAME` alone, exactly as before.
9689 golden: Option<&Picture>,
9690 // The frame two back, held in the slot this frame is about to refresh
9691 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
9692 // inter frames of a GOP, where the frame two back IS the key frame.
9693 altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,
9694 // Where this frame sits in the coding-order pyramid; `None` is the flat
9695 // one-shown-frame-per-picture stream this encoder wrote before.
9696 pyramid: Option<PyramidFrame>,
9697 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
9698 // them), padded like this one -- the lookahead window the per-block
9699 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
9700 // EMPTY slice codes the frame at one lambda, as before.
9701 lookahead: &[Picture],
9702) -> Result<Encoded> {
9703 picture.check()?;
9704 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
9705 return Err(Error::unsupported(
9706 "AV1 encode",
9707 "an inter frame is coded only for a picture that is a whole number \
9708 of 64x64 superblocks -- the inter tile writer never splits a \
9709 superblock's partition below that",
9710 ));
9711 }
9712 if reference.width != picture.width || reference.height != picture.height {
9713 return Err(Error::unsupported(
9714 "AV1 encode",
9715 "the reference picture must be the same size as the one being coded",
9716 ));
9717 }
9718
9719 // The single slot this crate's inter frames ever predict from or
9720 // refresh (`inter_frame_headers`'s contract): every frame both reads and
9721 // overwrites slot 0, so the frame just coded is always what the next one
9722 // predicts against.
9723 const LAST_SLOT: u8 = 0;
9724 // Slot 0 and slot 2 alternate so the frame two back survives one more
9725 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
9726 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
9727 // in the very slot it will overwrite.
9728 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
9729 let last_slot = pyramid.map_or(
9730 if order_hint <= 1 {
9731 LAST_SLOT
9732 } else if (order_hint - 1) % 2 == 1 {
9733 0
9734 } else {
9735 2
9736 },
9737 |p| p.last_slot,
9738 );
9739 // `render`, not `picture.width`/`picture.height`: `picture` here is
9740 // already padded to a whole number of superblocks (`encode_sequence`'s
9741 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
9742 // every true-edge clamp downstream) must come from the frame's real,
9743 // unpadded size, same as `key_frame_headers_colour` takes `render` and
9744 // not the padded picture in `encode_key_frame_inner`.
9745 let (seq, mut header) = inter_frame_headers_slots(
9746 render.0,
9747 render.1,
9748 base_q_idx,
9749 order_hint,
9750 last_slot,
9751 self_slot,
9752 match pyramid {
9753 Some(p) => p.altref_slot,
9754 None if altref.is_some() => self_slot,
9755 None => GOLDEN_SLOT,
9756 },
9757 )?;
9758 header.render_width = render.0 as u32;
9759 header.render_height = render.1 as u32;
9760 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
9761 // The order hint behind each `ref_frame_idx` entry. The flat path's own
9762 // slot plan (`inter_frame_headers_slots`) is: every reference but
9763 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
9764 // `ALTREF_FRAME`, which reads the frame two back when there is one;
9765 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
9766 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
9767 header.order_hints = order_hints;
9768 header.reference_select = reference_select();
9769 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
9770 // per-reference order-hint distance is read by the block SEARCH, which
9771 // runs long before the writer arms these (the distance-scaled search step
9772 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
9773 // never reached the tool).
9774 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
9775 if let Some(p) = pyramid {
9776 header.show_frame = p.show_frame;
9777 header.showable_frame = !p.show_frame;
9778 header.ref_frame_sign_bias = p.sign_bias;
9779 }
9780 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
9781 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
9782 // block inside this frame codes and searches its own `tx_depth`, the same
9783 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
9784 let tx_select = tx_select() && tx_select_inter();
9785 if tx_select {
9786 header.tx_mode = TxMode::Select;
9787 }
9788
9789 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
9790 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
9791 // here (see `encode_key_frame_inner`).
9792 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
9793 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
9794 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
9795 // This frame's own `allow_screen_content_tools`. It can only be set when
9796 // the SEQUENCE offers the bit at all, which is the key frame's decision
9797 // ([`SEQ_SCREEN`]): a frame header that contradicts
9798 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
9799 // encode.
9800 let screen = seq_screen()
9801 && screen_content(&picture_y8, picture.width, true_width, true_height);
9802 header.allow_screen_content_tools = screen;
9803 // The search prices coefficients against the tables this frame's writer
9804 // starts from, not against the defaults (lane-av1txbits) -- but only on a
9805 // frame the screen detector said no to (lane-av1price2): armed HERE, after
9806 // `screen` exists, and again on every search/tile worker below.
9807 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
9808 let mut luma = Plane {
9809 source: &picture_y8,
9810 reconstruction: vec![128; picture_y8.len()],
9811 width: picture.width,
9812 height: picture.height,
9813 true_width,
9814 true_height,
9815 tile_x0: 0,
9816 tile_y0: 0,
9817 tile_x1: picture.width,
9818 tile_y1: picture.height,
9819 ctx: CoefCtxMap::default(),
9820 };
9821 let mut chroma = [
9822 Plane {
9823 source: &picture_u8,
9824 reconstruction: vec![128; picture_u8.len()],
9825 width: picture.width / 2,
9826 height: picture.height / 2,
9827 true_width: true_width / 2,
9828 true_height: true_height / 2,
9829 tile_x0: 0,
9830 tile_y0: 0,
9831 tile_x1: picture.width / 2,
9832 tile_y1: picture.height / 2,
9833 ctx: CoefCtxMap::default(),
9834 },
9835 Plane {
9836 source: &picture_v8,
9837 reconstruction: vec![128; picture_v8.len()],
9838 width: picture.width / 2,
9839 height: picture.height / 2,
9840 true_width: true_width / 2,
9841 true_height: true_height / 2,
9842 tile_x0: 0,
9843 tile_y0: 0,
9844 tile_x1: picture.width / 2,
9845 tile_y1: picture.height / 2,
9846 ctx: CoefCtxMap::default(),
9847 },
9848 ];
9849
9850 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
9851 let search = Search {
9852 base_q_idx,
9853 deadzone,
9854 lambda: lambda_scale()
9855 * match pyramid {
9856 Some(p) if !p.show_frame => hidden_lambda_factor(),
9857 _ => 1.0,
9858 }
9859 * step
9860 * step,
9861 modes: &KEY_FRAME_MODES,
9862 top_k: prune_top_k_inter(),
9863 screen,
9864 };
9865 let mode_bits_table = inter_mode_bits();
9866 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
9867 // this frame the NEXT one predicts from. Off (`None`) without a
9868 // lookahead picture or at strength 0.
9869 let tpl_k = tpl_strength();
9870 let window: Vec<&Picture> = lookahead
9871 .iter()
9872 .take_while(|n| n.width == picture.width && n.height == picture.height)
9873 .collect();
9874 let tpl_sources: Vec<Vec<u8>> =
9875 window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect();
9876 let tpl_cells_x = picture.width / 16;
9877 let tpl_factors: Option<Vec<f64>> = (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| {
9878 if tpl_propagating() {
9879 let mut frames: Vec<&[u8]> = vec![&picture_y8];
9880 frames.extend(tpl_sources.iter().map(Vec::as_slice));
9881 tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k)
9882 } else {
9883 // The shipped map is one factor per 64x64; it is spread over that
9884 // superblock's own 16 cells so the application site below (which
9885 // averages the four cells of a 32x32 block) reads exactly the
9886 // superblock factor, whichever map fed it.
9887 let map =
9888 tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
9889 let cells_y = picture.height / 16;
9890 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
9891 (0..tpl_cells_x * cells_y)
9892 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
9893 .collect()
9894 }
9895 });
9896
9897 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
9898 // coding surface's: `blocks` carries one entry per 32x32 block the tile
9899 // writer will actually visit, same count it checks `blocks.len()`
9900 // against, which is fewer than the padded surface's own block count
9901 // whenever the true size is not a 64x64 multiple.
9902 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9903 let (cols, rows) = (cols as usize, rows as usize);
9904 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9905 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
9906 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
9907 // only when the map is, and `delta_q_res` follows straight into the frame
9908 // header (`write_delta_q_params`) and into the tile writer's own plan.
9909 let deltaq_res: Option<i32> = tpl_factors
9910 .as_ref()
9911 .and(deltaq_res_log2().map(|r| 1i32 << r));
9912 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
9913 (Some(f), Some(res)) => {
9914 let (k, clamp) = (deltaq_k(), deltaq_clamp());
9915 Some(
9916 (0..sb_cols * _sb_rows)
9917 .map(|sb| {
9918 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
9919 // The same 16-cell mean the superblock's own lambda
9920 // takes, clamped to the map the frame actually has.
9921 let mean = (0..16)
9922 .map(|i| {
9923 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
9924 f[(cy.min(f.len() / tpl_cells_x - 1)) * tpl_cells_x
9925 + cx.min(tpl_cells_x - 1)]
9926 })
9927 .sum::<f64>()
9928 / 16.0;
9929 deltaq_for_factor(base_q_idx, mean, k, clamp, res)
9930 })
9931 .collect(),
9932 )
9933 }
9934 _ => None,
9935 };
9936 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
9937 header.delta.q_present = true;
9938 header.delta.q_res = res.trailing_zeros() as u8;
9939 }
9940 if let Some(g) = &sb_q {
9941 let mut levels: Vec<u8> = g.clone();
9942 levels.sort_unstable();
9943 levels.dedup();
9944 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
9945 }
9946 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
9947 // This frame's tile grid, as in `encode_key_frame_inner`.
9948 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
9949 let layout =
9950 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
9951 header.tile_info = tile_info_of(&layout, 1);
9952 let header_tile_info = header.tile_info.clone();
9953 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
9954 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
9955 // once per frame (lane-av1rd2), not once per block, which is a whole
9956 // plane's map per 32x32 block and now per leaf too.
9957 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
9958 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
9959 // availability -- intra edges and the MV stack's scans alike -- already
9960 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
9961 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
9962 // giving each job its own planes and its own `MiGrid` therefore leaves
9963 // every decision, and so every coded bit, exactly where the whole-frame
9964 // loop left it, at any tile count and any thread count.
9965 let (frame_width, frame_height) = (picture.width, picture.height);
9966 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
9967 let [cb, cr] = &mut chroma;
9968 let chroma_out = [
9969 crate::par::Shared::new(&mut cb.reconstruction),
9970 crate::par::Shared::new(&mut cr.reconstruction),
9971 ];
9972 let search_tile = |index: usize,
9973 fctx: &crate::decode::FrameCtx|
9974 -> Result<Vec<(usize, Quadrant)>> {
9975 // Thread-local, and this job may be running on a `search_tiles`
9976 // worker: `ref_distance`'s order-hint distance (the scaled motion
9977 // search step) is read by the SEARCH, so every worker arms it or the
9978 // tile's bits depend on the thread count.
9979 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
9980 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
9981 let rect = layout.rect(index);
9982 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
9983 let mut chroma = [
9984 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
9985 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
9986 ];
9987 clip_planes_to_tile(&mut luma, &mut chroma, rect);
9988 let mut grid = MiGrid::new(mi_cols, mi_rows);
9989 grid.set_sign_bias(sign_bias);
9990 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
9991 // built once per tile job (`obmc_prediction`).
9992 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
9993 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
9994 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
9995 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
9996 grid.set_tile_bounds(
9997 rect.mi_row0 as usize,
9998 rect.mi_col0 as usize,
9999 rect.mi_row1 as usize,
10000 rect.mi_col1 as usize,
10001 );
10002 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
10003 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
10004 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
10005 // lane-b64: the whole superblock as ONE 64x64 block, tried before
10006 // its quadrants are (`search_skip_64`) and compared against the
10007 // four of them below. Only a superblock wholly inside the true
10008 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
10009 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
10010 // only that the block's half is inside, and the trial is ranked
10011 // over the inside part alone ([`Plane::block_sse`]).
10012 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
10013 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
10014 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
10015 && x64 + SUPERBLOCK <= luma.true_width
10016 && y64 + SUPERBLOCK <= luma.true_height;
10017 let edge_inside = b64_edge()
10018 && crate::tile::has_half(
10019 sb_c as u32 * crate::tile::SB_MI,
10020 crate::tile::SB_MI,
10021 header.mi_cols,
10022 )
10023 && crate::tile::has_half(
10024 sb_r as u32 * crate::tile::SB_MI,
10025 crate::tile::SB_MI,
10026 header.mi_rows,
10027 );
10028 let sb64_legal = b64_root()
10029 && sb_r * 2 + 1 < rows
10030 && sb_c * 2 + 1 < cols
10031 && (whole_inside || edge_inside);
10032 // One lambda for the whole superblock, the same mean the 32x32
10033 // level takes over its own four tpl cells: the 64-vs-four-32
10034 // comparison below weighs one cost against four, so both sides
10035 // have to be priced at the same lambda.
10036 let sb_search = match &tpl_factors {
10037 // lane-deltaq: with a per-superblock quantizer the lambda
10038 // comes from that quantizer, not from the raw map factor --
10039 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
10040 Some(_) if sb_q.is_some() => sb_q_search(sb_q.as_ref().expect("armed"), sb_cols, base_q_idx, (sb_r, sb_c), search),
10041 Some(f) if sb64_legal => {
10042 let mean = (0..16)
10043 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10044 .sum::<f64>()
10045 / 16.0;
10046 Search { lambda: search.lambda * mean, ..search }
10047 }
10048 _ => search,
10049 };
10050 let mark = blocks.len();
10051 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
10052 let mut sb_cost = 0.0f64;
10053 if sb64_legal {
10054 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
10055 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
10056 let stack =
10057 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
10058 // lane-b64b: the `LAST` + extra-reference pairs at this
10059 // superblock's own 16x16-mi window, the same stacks the tile
10060 // writer's `Whole64` arm rebuilds. Empty unless the frame
10061 // codes `reference_select`, which is what gates the syntax.
10062 // `!screen` for the same reason the residual arm is gated
10063 // there ([`b64_residual`]): a desktop capture's superblocks
10064 // are flat runs the skip arm already codes for nothing, and
10065 // MEASURED, compound at the root cost it +33.4/-23.8 ->
10066 // +33.7/-23.6 while both film rows gained (step 1's table).
10067 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
10068 if header.reference_select && b64_compound() && !screen {
10069 [
10070 (crate::mvstack::GOLDEN_FRAME, golden),
10071 (crate::mvstack::ALTREF_FRAME, altref),
10072 ]
10073 .into_iter()
10074 .filter_map(|(r, pic)| {
10075 pic.map(|p| {
10076 (
10077 r,
10078 p,
10079 crate::mvstack::find_mv_stack_compound(
10080 &grid,
10081 mi_row,
10082 mi_col,
10083 16,
10084 16,
10085 (crate::mvstack::LAST_FRAME, r),
10086 mi_cols,
10087 mi_rows,
10088 grid.sign_bias_table(),
10089 &[(0, 0); 7],
10090 None,
10091 ),
10092 )
10093 })
10094 })
10095 .collect()
10096 } else {
10097 Vec::new()
10098 };
10099 if let Some((cost, block)) = search_skip_64(
10100 &mut luma,
10101 &mut chroma,
10102 (x64, y64),
10103 &sb_search,
10104 b64_residual() && !screen,
10105 reference,
10106 &stack,
10107 &sb_compound,
10108 fctx,
10109 ) {
10110 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
10111 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
10112 let cost = cost
10113 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
10114 sb64 = Some((cost, block, after));
10115 }
10116 }
10117 // A superblock whose 64x64 trial already codes almost nothing per
10118 // pixel is taken outright and its quadrants are never searched --
10119 // the same `split_rd_breakout` shape the 32x32 level uses one
10120 // size up, and where this lever BUYS wall instead of spending it.
10121 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
10122 split_rd_breakout_at(
10123 b64_breakout_threshold(),
10124 *c,
10125 SUPERBLOCK,
10126 sb_search.lambda,
10127 )
10128 });
10129 for quadrant in 0..if early64 { 0 } else { 4 } {
10130 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
10131 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
10132 // decision under it (partition, mode, tx, motion) reads
10133 // `search.lambda`, so scaling the one field here scales all
10134 // of them. 32x32 and not the 16x16 the map is built at
10135 // because the whole-vs-split comparison right below weighs
10136 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
10137 // would make those two numbers incomparable.
10138 let search = match &tpl_factors {
10139 // lane-deltaq: the quantizer is a SUPERBLOCK-level
10140 // symbol, so all four quadrants take their superblock's
10141 // own qindex and the lambda it implies. No granularity is
10142 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
10143 // factor per superblock, shared by its sixteen cells.
10144 Some(_) if sb_q.is_some() => sb_q_search(sb_q.as_ref().expect("armed"), sb_cols, base_q_idx, (sb_r, sb_c), search),
10145 Some(f) => {
10146 let mean = (0..4)
10147 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
10148 .sum::<f64>()
10149 / 4.0;
10150 Search { lambda: search.lambda * mean, ..search }
10151 }
10152 None => search,
10153 };
10154 // Same filter as the tile writer's: a quadrant whose own mi
10155 // origin is not inside the true frame is never coded.
10156 if r32 >= rows || c32 >= cols {
10157 continue;
10158 }
10159 // spec `decode_partition`'s hasRows/hasCols recomputed at this
10160 // 32x32 block's own half (`crate::tile::has_half`), same as
10161 // the key frame search: the true frame edge can fall inside a
10162 // quadrant a superblock-level check already let through, and
10163 // such a quadrant cannot be left whole -- it must split into
10164 // the 16x16 leaves that are actually inside the true frame
10165 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
10166 // arm).
10167 let (has_cols32, has_rows32) = (
10168 crate::tile::has_half(
10169 c32 as u32 * crate::tile::BLOCK_MI,
10170 crate::tile::BLOCK_MI,
10171 header.mi_cols,
10172 ),
10173 crate::tile::has_half(
10174 r32 as u32 * crate::tile::BLOCK_MI,
10175 crate::tile::BLOCK_MI,
10176 header.mi_rows,
10177 ),
10178 );
10179 if has_cols32 && has_rows32 {
10180 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
10181 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
10182 let stack =
10183 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
10184 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
10185 (crate::mvstack::GOLDEN_FRAME, golden),
10186 (crate::mvstack::ALTREF_FRAME, altref),
10187 ]
10188 .into_iter()
10189 .filter_map(|(r, pic)| {
10190 pic.map(|p| {
10191 (
10192 r,
10193 p,
10194 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
10195 )
10196 })
10197 })
10198 .collect();
10199 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
10200 .iter()
10201 .map(|(r, p, st)| (*r, *p, st))
10202 .collect();
10203 // The COMPOUND stack of each `LAST` + extra pair, off the
10204 // same grid (and the same armed sign bias) the tile writer
10205 // rebuilds it from. Empty unless this frame codes
10206 // `reference_select`, which is what gates the syntax.
10207 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
10208 if header.reference_select {
10209 extra_stacks
10210 .iter()
10211 .map(|&(r, p, _)| {
10212 (
10213 r,
10214 p,
10215 crate::mvstack::find_mv_stack_compound(
10216 &grid,
10217 mi_row,
10218 mi_col,
10219 8,
10220 8,
10221 (crate::mvstack::LAST_FRAME, r),
10222 mi_cols,
10223 mi_rows,
10224 grid.sign_bias_table(),
10225 &[(0, 0); 7],
10226 None,
10227 ),
10228 )
10229 })
10230 .collect()
10231 } else {
10232 Vec::new()
10233 };
10234
10235 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
10236 let (block, mut cost_whole) = search_inter_block(
10237 &mut luma,
10238 &mut chroma,
10239 (x, y),
10240 &search,
10241 &mode_bits_table,
10242 reference,
10243 &stack,
10244 &extra,
10245 &compound,
10246 &grid,
10247 (mi_row, mi_col),
10248 (mi_rows, mi_cols),
10249 fctx,
10250 );
10251 cost_whole += search.lambda * partition_bits(BLOCK, false);
10252 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
10253
10254 // What four 16x16 leaves cost instead (spec
10255 // PARTITION_SPLIT at BLOCK_32X32, which
10256 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
10257 // already writes for a straddling quadrant). Each leaf is
10258 // searched against the reconstruction -- and the `mi`
10259 // grid -- the ones before it left, exactly as the writer
10260 // and the decoder will read them.
10261 //
10262 // A block the whole-32 search left skipped (no residual
10263 // at all) is not offered the split: libaom prunes the
10264 // same way at cpu-used 6, and it is where the wall would
10265 // otherwise go on static content.
10266 let leaf_positions: Vec<(usize, usize)> = (0..4)
10267 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
10268 .collect();
10269 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
10270 crate::tile::has_half(
10271 sc as u32 * crate::tile::SUB_MI,
10272 crate::tile::SUB_MI,
10273 header.mi_cols,
10274 ) && crate::tile::has_half(
10275 sr as u32 * crate::tile::SUB_MI,
10276 crate::tile::SUB_MI,
10277 header.mi_rows,
10278 )
10279 });
10280 // The breakout above: a 32x32 block that codes almost
10281 // nothing is not offered the split at all.
10282 let breakout = split_breakout_coeffs();
10283 let split = (!block.skip
10284 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
10285 && (breakout == 0 || block.luma.len() > 4 * breakout)
10286 && leaves_legal
10287 && split_inter_blocks())
10288 .then(|| {
10289 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
10290 let mut cost = search.lambda * partition_bits(BLOCK, true);
10291 let mut leaves = Vec::with_capacity(4);
10292 for &(sr, sc) in &leaf_positions {
10293 let (mi_row, mi_col) = (sr * 4, sc * 4);
10294 let (lx, ly) = (sc * SUB, sr * SUB);
10295 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
10296 let stack = find_mv_stack(
10297 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
10298 );
10299 let cstacks = leaf_compound_stacks(
10300 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
10301 header.reference_select, golden, altref,
10302 );
10303 let (leaf, leaf_cost) = code_square_inter(
10304 &mut luma,
10305 &mut chroma,
10306 (lx, ly),
10307 SUB,
10308 &search,
10309 &mode_bits_table,
10310 reference,
10311 &stack,
10312 &cstacks,
10313 &grid,
10314 (mi_row, mi_col),
10315 (mi_rows, mi_cols),
10316 &obmc_refs,
10317 fctx,
10318 );
10319 let leaf_cost = leaf_cost
10320 + search.lambda * partition_bits(SUB, false);
10321 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
10322
10323 // And what four 8x8 leaves cost instead --
10324 // the same tree one step further down, which
10325 // the writer codes as a real PARTITION_SPLIT
10326 // at BLOCK_16X16 (lane-av1rd2). Same
10327 // skipped-block prune as the level above.
10328 let eight = (!leaf.skip
10329 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
10330 && (breakout == 0 || leaf.luma.len() > breakout)
10331 && split_inter_8())
10332 .then(|| {
10333 restore(
10334 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
10335 );
10336 let mut cost8 = search.lambda
10337 * (partition_bits(SUB, true)
10338 + 4.0 * partition_bits(8, false));
10339 let mut eight = Vec::with_capacity(4);
10340 for i in 0..4 {
10341 let (mr, mc) =
10342 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
10343 let stack8 = find_mv_stack(
10344 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
10345 );
10346 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
10347 if header.reference_select && leaf_compound() {
10348 [
10349 (crate::mvstack::GOLDEN_FRAME, golden),
10350 (crate::mvstack::ALTREF_FRAME, altref),
10351 ]
10352 .into_iter()
10353 .filter_map(|(r, pic)| {
10354 pic.map(|p| {
10355 (
10356 r,
10357 p,
10358 crate::mvstack::find_mv_stack_compound(
10359 &grid, mr, mc, 2, 2,
10360 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
10361 grid.sign_bias_table(), &[(0, 0); 7], None,
10362 ),
10363 )
10364 })
10365 })
10366 .collect()
10367 } else {
10368 Vec::new()
10369 };
10370 let (leaf8, cost) = code_square_inter(
10371 &mut luma,
10372 &mut chroma,
10373 (lx + (i % 2) * 8, ly + (i / 2) * 8),
10374 8,
10375 &search,
10376 &mode_bits_table,
10377 reference,
10378 &stack8,
10379 &cstacks8,
10380 &grid,
10381 (mr, mc),
10382 (mi_rows, mi_cols),
10383 &obmc_refs,
10384 fctx,
10385 );
10386 cost8 += cost;
10387 record_mi(&mut grid, mr, mc, 2, leaf8.inter);
10388 eight.push(leaf8);
10389 }
10390 (eight, cost8)
10391 });
10392 match eight {
10393 Some((eight, cost8)) if cost8 < leaf_cost => {
10394 partition_hit(3);
10395 cost += cost8;
10396 leaves.push(BlockCoeffs {
10397 eight: Some(eight),
10398 ..BlockCoeffs::default()
10399 });
10400 continue;
10401 }
10402 Some(_) => restore(
10403 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
10404 ),
10405 None => {}
10406 }
10407 partition_hit(2);
10408 cost += leaf_cost;
10409 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter);
10410 leaves.push(leaf);
10411 }
10412 (leaves, cost)
10413 });
10414 if let Some((leaves, cost)) = split {
10415 if cost < cost_whole {
10416 // The leaves' own `mi` cells are already in the
10417 // grid, and their reconstruction is what the
10418 // planes hold.
10419 partition_hit(1);
10420 sb_cost += cost;
10421 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
10422 continue;
10423 }
10424 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
10425 }
10426 partition_hit(0);
10427 sb_cost += cost_whole;
10428 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);
10429 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
10430 } else {
10431 // The sub-positions actually inside the true frame, same
10432 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
10433 let sub_positions: Vec<(usize, usize)> = (0..4)
10434 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
10435 .filter(|&(sr, sc)| {
10436 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
10437 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
10438 })
10439 .collect();
10440 // Each leaf searches intra against its own `NEARESTMV`
10441 // candidate (`code_square_inter`), same real-inter choice
10442 // `search_inter_block` makes for a whole 32x32 block, at
10443 // this leaf's own 4x4-mi mv-stack window -- unless the
10444 // leaf's own half itself straddles the true edge, which
10445 // it codes as two (or one, at a true corner) 8x8 leaves
10446 // (`crate::tile::write_leaf8`'s inter counterpart),
10447 // mirroring the key frame search's straddling-16x16
10448 // handling above (lane-av1inter8).
10449 let mut leaves = Vec::with_capacity(sub_positions.len());
10450 for (sr, sc) in sub_positions {
10451 let (has_cols16, has_rows16) = (
10452 crate::tile::has_half(
10453 sc as u32 * crate::tile::SUB_MI,
10454 crate::tile::SUB_MI,
10455 header.mi_cols,
10456 ),
10457 crate::tile::has_half(
10458 sr as u32 * crate::tile::SUB_MI,
10459 crate::tile::SUB_MI,
10460 header.mi_rows,
10461 ),
10462 );
10463 if has_cols16 && has_rows16 {
10464 let (x, y) = (sc * SUB, sr * SUB);
10465 let (mi_row, mi_col) = (sr * 4, sc * 4);
10466 let stack = find_mv_stack(
10467 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
10468 );
10469 let cstacks = leaf_compound_stacks(
10470 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
10471 header.reference_select, golden, altref,
10472 );
10473 let (block, _) = code_square_inter(
10474 &mut luma,
10475 &mut chroma,
10476 (x, y),
10477 SUB,
10478 &search,
10479 &mode_bits_table,
10480 reference,
10481 &stack,
10482 &cstacks,
10483 &grid,
10484 (mi_row, mi_col),
10485 (mi_rows, mi_cols),
10486 &obmc_refs,
10487 fctx,
10488 );
10489 // One publication point for every coded leaf
10490 // (`record_mi`): this site used to spell the vote
10491 // out with `ref_frame` pinned to LAST and `mv1`
10492 // to (0,0), which is the encoder-grid-drift class
10493 // -- correct only for as long as a leaf can never
10494 // be compound.
10495 record_mi(&mut grid, mi_row, mi_col, 4, block.inter);
10496 leaves.push(block);
10497 } else {
10498 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
10499 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
10500 let mut eight = Vec::with_capacity(2);
10501 for i in 0..4 {
10502 let leaf_x = x_sub + (i % 2) * 8;
10503 let leaf_y = y_sub + (i / 2) * 8;
10504 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
10505 continue;
10506 }
10507 let (mi_row, mi_col) =
10508 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
10509 let stack = find_mv_stack(
10510 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
10511 );
10512 let cstacks = leaf_compound_stacks(
10513 &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows,
10514 header.reference_select, golden, altref,
10515 );
10516 let (leaf, _) = code_square_inter(
10517 &mut luma,
10518 &mut chroma,
10519 (leaf_x, leaf_y),
10520 8,
10521 &search,
10522 &mode_bits_table,
10523 reference,
10524 &stack,
10525 &cstacks,
10526 &grid,
10527 (mi_row, mi_col),
10528 (mi_rows, mi_cols),
10529 &obmc_refs,
10530 fctx,
10531 );
10532 // Same publication point as the 16x16
10533 // straddling leaf above (`record_mi`).
10534 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter);
10535 eight.push(leaf);
10536 }
10537 leaves.push(BlockCoeffs {
10538 eight: Some(eight),
10539 ..BlockCoeffs::default()
10540 });
10541 }
10542 }
10543 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
10544 }
10545 }
10546 // The 64x64 root against what its four quadrants really cost.
10547 if let Some((cost64, block, after)) = sb64
10548 && (early64
10549 || cost64
10550 < sb_cost
10551 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
10552 {
10553 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10554 if block.inter.is_some_and(|i| i.ref1.is_some()) {
10555 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10556 }
10557 if !whole_inside {
10558 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10559 }
10560 blocks.truncate(mark);
10561 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
10562 // Overwrites every 16x16 mi cell the quadrant searches
10563 // published under this superblock, so the next block's stack
10564 // is built off the block that was really coded.
10565 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter);
10566 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
10567 for q in 1..4 {
10568 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
10569 blocks.push((r32 * cols + c32, Quadrant::Covered));
10570 }
10571 }
10572 }
10573 }
10574 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
10575 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
10576 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
10577 for (&out, tile) in chroma_out.iter().zip(&chroma) {
10578 copy_rect(
10579 out,
10580 &tile.reconstruction,
10581 frame_width / 2,
10582 x0 / 2,
10583 y0 / 2,
10584 x1.div_ceil(2),
10585 y1.div_ceil(2),
10586 );
10587 }
10588 Ok(blocks)
10589 };
10590 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
10591 .into_iter()
10592 .flatten()
10593 {
10594 blocks[at] = quadrant;
10595 }
10596
10597 let modes = blocks
10598 .iter()
10599 .flat_map(Quadrant::blocks)
10600 .map(|b| b.mode)
10601 .collect::<Vec<_>>();
10602 let inter_block_share = blocks
10603 .iter()
10604 .flat_map(Quadrant::blocks)
10605 .filter(|b| b.inter.is_some())
10606 .count() as f64
10607 / modes.len() as f64;
10608 for block in blocks.iter().flat_map(Quadrant::blocks) {
10609 if let Some(info) = block.inter {
10610 let r = (info.ref_frame as usize).min(7);
10611 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10612 }
10613 }
10614 #[cfg(test)]
10615 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
10616 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
10617 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
10618 // next frame's writer starts from them -- exactly what
10619 // `crate::stream::stored_cdfs_for` hands the decoder.
10620 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
10621 let cdfs = start_cdfs
10622 .cloned()
10623 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
10624 let start_cdfs = CdfSnapshot(cdfs);
10625 let reference_select_bit = header.reference_select;
10626 let switchable_motion_mode = header.is_motion_mode_switchable;
10627 let warped_motion = header.allow_warped_motion;
10628 let order_hint_bits = seq.order_hint_bits;
10629 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
10630 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
10631 // What this frame stores is the LARGEST tile's end-of-tile tables --
10632 // its own header's `context_update_tile_id` (spec 7.20), which
10633 // `tile_info_of` set to exactly that tile.
10634 let store_tile = layout.largest_tile();
10635 let end_cdfs = std::cell::RefCell::new(None);
10636 // As in `encode_key_frame_inner`: every tile starts from this frame's
10637 // own tables, so no tile depends on any other.
10638 let code_tiles = |bits: u8,
10639 sb_cols: usize,
10640 cdef_grid: &[u8],
10641 units: &[Option<crate::restoration::WienerInfo>]|
10642 -> Result<Vec<Vec<u8>>> {
10643 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
10644 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
10645 crate::tile::arm_delta_q(
10646 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
10647 sb_cols,
10648 sb_q.clone().unwrap_or_default(),
10649 base_q_idx,
10650 );
10651 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
10652 crate::tile::arm_sign_bias(sign_bias);
10653 // Thread-locals: every tile job arms its own worker.
10654 crate::tile::arm_reference_select(reference_select_bit);
10655 crate::tile::arm_motion_mode(switchable_motion_mode);
10656 crate::tile::arm_warped_motion(warped_motion);
10657 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
10658 crate::tile::arm_screen(screen);
10659 crate::tile::arm_filter_intra(filter_intra_on());
10660 let mut cdfs = start_cdfs.0.clone();
10661 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
10662 // Each tile's own MV grid: a candidate scan never reaches past
10663 // the tile's bounds, so a grid holding only this tile's own
10664 // blocks reads exactly as the decoder's frame-wide one does
10665 // under `MiGrid::set_tile_bounds`.
10666 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
10667 mv_grid.set_sign_bias(sign_bias);
10668 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
10669 mi_cols,
10670 mi_rows,
10671 base_q_idx,
10672 &blocks,
10673 tx_select,
10674 &mut cdfs,
10675 layout.rect(index),
10676 &mut mv_grid,
10677 )?;
10678 Ok((bytes, Some(cdfs)))
10679 })?;
10680 if let Some(cdfs) = stored {
10681 *end_cdfs.borrow_mut() = Some(cdfs);
10682 }
10683 Ok(out)
10684 };
10685 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
10686 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
10687 // this tile against the same single-slot reference this encoder predicted
10688 // from, under each candidate level.
10689 // The reference a DECODER holds is this frame's cropped size, not the
10690 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
10691 // reference whose height is not the header's own `frame_height` (spec
10692 // 7.9's compatible-size rule), and the chained-decode round trips prove
10693 // the two predict identically.
10694 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
10695 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
10696 reference.clone()
10697 } else {
10698 Picture {
10699 width: fw,
10700 height: fh,
10701 y: crop_plane(&reference.y, reference.width, fw, fh),
10702 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
10703 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
10704 }
10705 };
10706 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
10707 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
10708 // blocks may name GOLDEN needs that plane too, cropped the same way.
10709 let trial_golden = golden.map(|g| {
10710 if (g.width, g.height) == (fw, fh) {
10711 g.clone()
10712 } else {
10713 Picture {
10714 width: fw,
10715 height: fh,
10716 y: crop_plane(&g.y, g.width, fw, fh),
10717 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
10718 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
10719 }
10720 }
10721 });
10722 let trial_altref = altref.map(|a| {
10723 if (a.width, a.height) == (fw, fh) {
10724 a.clone()
10725 } else {
10726 Picture {
10727 width: fw,
10728 height: fh,
10729 y: crop_plane(&a.y, a.width, fw, fh),
10730 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
10731 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
10732 }
10733 }
10734 });
10735 let mut refs: [Option<&Picture>; 8] = [None; 8];
10736 refs[1] = Some(&trial_ref);
10737 refs[4] = trial_golden.as_ref();
10738 refs[7] = trial_altref.as_ref();
10739 let refpix = crate::decode::RefPix::ready(refs);
10740 pick_and_apply_filters(
10741 &mut header,
10742 &mut luma,
10743 &mut chroma,
10744 [&picture_y8, &picture_u8, &picture_v8],
10745 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
10746 // this frame's own `tx_select`, so the search runs under inter
10747 // `TxMode::Select` too (it used to skip and leave every inter frame
10748 // unfiltered once Select became the default).
10749 true,
10750 &mut tiles,
10751 search.lambda,
10752 fctx,
10753 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
10754 // are what the NEXT frame writes from, so the winning re-code
10755 // publishes its own into `end_cdfs` -- the first write's are stale
10756 // the moment a second tile is coded.
10757 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
10758 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
10759 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
10760 crate::decode::decode_inter_frame_tiles_lr(
10761 &payloads,
10762 &header_tile_info,
10763 h.mi_cols,
10764 h.mi_rows,
10765 base_q_idx,
10766 h.frame_width,
10767 h.frame_height,
10768 &refpix,
10769 cdef,
10770 lf,
10771 h.allow_high_precision_mv,
10772 h.force_integer_mv,
10773 Some(mc::InterpFilterKind::Regular),
10774 seq.enable_dual_filter,
10775 h.reference_select,
10776 tx_select,
10777 lr,
10778 // The trial decode re-reads the tile the writer just wrote,
10779 // so it starts from the same tables the writer did (this
10780 // frame's `start_cdfs`), not from the defaults.
10781 Some(start_cdfs.0.clone()),
10782 sign_bias,
10783 h.allow_screen_content_tools,
10784 switchable_motion_mode,
10785 h.allow_warped_motion,
10786 seq.enable_filter_intra,
10787 // lane-deltaq: this frame's own delta_q/delta_lf params, so
10788 // the trial decode reads the per-superblock `delta_qindex`
10789 // syntax the writer just wrote.
10790 h.delta.clone(),
10791 fctx,
10792 )
10793 },
10794 )?;
10795 let mut cdfs = end_cdfs
10796 .into_inner()
10797 .unwrap_or_else(|| start_cdfs.0.clone());
10798 cdfs.reset_counts();
10799 let next_cdfs = CdfSnapshot(cdfs);
10800 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
10801 header.tile_info.tile_size_bytes = tile_size_bytes;
10802 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
10803 let mut stream = temporal_delimiter();
10804 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
10805
10806 let [u, v] = chroma;
10807 Ok(Encoded {
10808 stream,
10809 modes,
10810 inter_block_share,
10811 reconstruction: Picture {
10812 width: luma.width,
10813 height: luma.height,
10814 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
10815 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
10816 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
10817 },
10818 tile,
10819 mi_cols: header.mi_cols,
10820 mi_rows: header.mi_rows,
10821 base_q_idx,
10822 tx_select,
10823 switchable_motion_mode,
10824 screen,
10825 start_cdfs,
10826 next_cdfs,
10827 loop_filter: header.loop_filter,
10828 cdef: header.cdef,
10829 loop_restoration: header.loop_restoration,
10830 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
10831 // intra frames only).
10832 allow_intrabc: false,
10833 delta: header.delta.clone(),
10834 })
10835}
10836
10837/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
10838/// frame's temporal unit followed by one inter frame's temporal unit per
10839/// remaining picture, all sharing the key frame's sequence header -- and
10840/// each frame's own [`Encoded`], in coding order.
10841#[derive(Clone, Debug)]
10842pub struct EncodedSequence {
10843 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
10844 /// sequence header and the key frame) followed by each later frame's
10845 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
10846 /// the sequence header the key frame carried).
10847 pub stream: Vec<u8>,
10848 /// One entry per picture, in DISPLAY order — the order a decoder outputs
10849 /// them and the order `pictures` came in. Without a pyramid that is also
10850 /// the coding order; with one the two differ, and `coding_order` is the
10851 /// map between them.
10852 pub frames: Vec<Encoded>,
10853 /// The index into `frames` of each coded frame, in CODING order — what a
10854 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
10855 /// `0..frames.len()` on the flat path.
10856 pub coding_order: Vec<usize>,
10857}
10858
10859/// Encodes a sequence of pictures as a key frame followed by one inter frame
10860/// per remaining picture, each predicting from the previous frame's own
10861/// decoded reconstruction — never from the source, which is what a decoder
10862/// cannot see. Every picture must be the same even size (any even width and
10863/// height — each is padded to a whole number of 64x64 superblocks
10864/// internally, which is what lets an inter frame's reference always match
10865/// the frame being coded against it), and `pictures` must be non-empty.
10866///
10867/// # Errors
10868/// Returns an error when `pictures` is empty, when any picture besides the
10869/// first is not the same size as the first, or under the same conditions
10870/// [`encode_key_frame`] and the inter frame path do.
10871pub(crate) fn encode_sequence_with_ctx(
10872 pictures: &[Picture],
10873 base_q_idx: u8,
10874 deadzone: f64, fctx: &crate::decode::FrameCtx,
10875) -> Result<EncodedSequence> {
10876 let Some((first, rest)) = pictures.split_first() else {
10877 return Err(Error::unsupported(
10878 "AV1 encode",
10879 "a sequence needs at least one picture",
10880 ));
10881 };
10882 first.check_even()?;
10883 let render = (first.width, first.height);
10884 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
10885 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
10886 // the leaves that predict backward off it, and a `show_existing_frame`
10887 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
10888 // an A/B. Screen content stays flat (the content gate in
10889 // `Av1Encoder::encode_frames`, whose detector this asks first so the
10890 // whole sequence path is decided in one place), and so does a run that
10891 // asks for a quantizer rounding offset the facade does not carry: the
10892 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
10893 // the ablations' -- must keep the flat path rather than be silently
10894 // ignored.
10895 //
10896 // The reordering itself is NOT reimplemented here: it is the facade's
10897 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
10898 // called with this sequence's shape, so the two paths cannot drift.
10899 let pyramid = crate::encoder::Pyramid::from_env()
10900 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
10901 .filter(|_| !picture_is_screen(first));
10902 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
10903 if let Some(pyramid) = pyramid {
10904 for picture in rest {
10905 picture.check_even()?;
10906 if (picture.width, picture.height) != render {
10907 return Err(Error::unsupported(
10908 "AV1 encode",
10909 "every picture in a sequence must be the same size as the first",
10910 ));
10911 }
10912 }
10913 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
10914 pictures,
10915 base_q_idx,
10916 pyramid,
10917 armed_tiles(),
10918 );
10919 }
10920 // The key frame and every inter frame after it are coded at the same
10921 // padded size, so the reference each inter frame predicts from -- the
10922 // previous frame's own uncropped reconstruction, at the size a decoder's
10923 // reference buffer actually holds -- always matches the frame being
10924 // coded against it.
10925 let key = encode_key_frame_inner(
10926 &first.padded_to(SUPERBLOCK),
10927 base_q_idx,
10928 deadzone,
10929 &KEY_FRAME_MODES,
10930 split_blocks(),
10931 render,
10932 unspecified_color_config(), fctx,
10933 )?;
10934 let mut stream = key.stream.clone();
10935 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
10936 // key frame refreshes every slot, each inter frame only slot 0), which is
10937 // what `GOLDEN_FRAME` names.
10938 let golden = key.reconstruction.clone();
10939 // The frame two back, once there is one that is not the key frame
10940 // itself (which `GOLDEN_FRAME` already names).
10941 let mut prev2: Option<Picture> = None;
10942 let mut carried = key.next_cdfs.clone();
10943 let mut reference = key.reconstruction.clone();
10944 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
10945 for (i, picture) in rest.iter().enumerate() {
10946 picture.check_even()?;
10947 // lane-av1tpl2: the lookahead window the per-block lambda weighting
10948 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
10949 // sources at this frame's coded (padded) size. The tail of the
10950 // sequence gets a shorter window, and the last frame none at all.
10951 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
10952 .iter()
10953 .take(tpl_depth() - 1)
10954 .map(|n| n.padded_to(SUPERBLOCK))
10955 .collect();
10956 if (picture.width, picture.height) != render {
10957 return Err(Error::unsupported(
10958 "AV1 encode",
10959 "every picture in a sequence must be the same size as the first",
10960 ));
10961 }
10962 let order_hint = (i + 1) as u32;
10963 let inter = encode_inter_frame(
10964 &picture.padded_to(SUPERBLOCK),
10965 &reference,
10966 base_q_idx,
10967 deadzone,
10968 order_hint,
10969 flat_order_hints(order_hint, 0, prev2.is_some()),
10970 render,
10971 Some(&carried.0),
10972 Some(&golden),
10973 prev2.as_ref(), fctx,
10974 None,
10975 &lookahead,
10976 )?;
10977 stream.extend_from_slice(&inter.stream);
10978 carried = inter.next_cdfs.clone();
10979 prev2 = Some(std::mem::replace(
10980 &mut reference,
10981 inter.reconstruction.clone(),
10982 ));
10983 frames.push(crop_encoded(&inter, render.0, render.1));
10984 }
10985 Ok(EncodedSequence {
10986 stream,
10987 coding_order: (0..frames.len()).collect(),
10988 frames,
10989 })
10990}
10991
10992#[cfg(test)]
10993mod tests {
10994
10995 /// lane-av1tpl2's propagated map, on the two properties every decision
10996 /// under it rests on: a frame the whole lookahead window repeats exactly
10997 /// (uniform texture) leans on every cell alike, so every factor is 1 and
10998 /// the weighting is a no-op; and where the window really does save bits
10999 /// by predicting -- the textured half of a frame whose other half is
11000 /// flat -- the factor FALLS below 1, i.e. that half is coded more
11001 /// distortion-averse than the half nothing gains from.
11002 /// The distortion metric itself (lane-sse): a block the true frame edge
11003 /// cuts through is scored over its INSIDE part only, so a difference that
11004 /// lives entirely in the padding costs nothing and a block wholly past
11005 /// the edge scores zero. Before this, the search ranked modes,
11006 /// transforms and partition trees on samples the display crop throws
11007 /// away -- which lane-b64b had fixed for the 64x64 root alone.
11008 #[test]
11009 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
11010 // A 40x40 true frame on a 64x64 padded coding surface.
11011 let source = vec![10u8; 64 * 64];
11012 let plane = fresh_plane(&source, 64, 64, 40, 40);
11013 let mut reconstruction = vec![10u8; 64 * 64];
11014 // Off by 190 at (50, 50) -- past the true edge in both axes.
11015 reconstruction[50 * 64 + 50] = 200;
11016 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored");
11017 // Off by 10 at (39, 39) -- the last sample the decoder shows.
11018 reconstruction[39 * 64 + 39] = 20;
11019 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored");
11020 // A 16x16 block whose every sample is padding.
11021 let block = vec![200u8; 16 * 16];
11022 assert_eq!(plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored");
11023 // A 16x16 block the edge cuts: 8 of its columns are inside.
11024 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
11025 }
11026
11027 #[test]
11028 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
11029 // Four 64x64 superblocks across: the shipped map forms its ratio per
11030 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
11031 // only ever produce one ratio -- and one ratio, mean-normalised, is
11032 // the flat map, whatever the content underneath it.
11033 let (w, h) = (256usize, 64usize);
11034 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
11035 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
11036 let f = super::tpl_lambda_factors(&frames, w, h, 1.0);
11037 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
11038 for (i, &v) in f.iter().enumerate() {
11039 assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda");
11040 }
11041
11042 // Left half textured, right half constant: the window saves bits
11043 // predicting the left half and nothing at all on the right.
11044 let split: Vec<u8> = (0..w * h)
11045 .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 })
11046 .collect();
11047 let frames: Vec<&[u8]> = vec![&split, &split, &split];
11048 let cells_x = w / 16;
11049 for k in [0.25f64, 0.5, 1.0, 2.0] {
11050 let f = super::tpl_lambda_factors(&frames, w, h, k);
11051 for r in 0..h / 16 {
11052 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
11053 assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1");
11054 assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1");
11055 }
11056 }
11057 }
11058
11059 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
11060 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
11061 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
11062 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
11063 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
11064 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
11065 /// only a quarter of the 16x8 table and read the wrong byte for every
11066 /// block row but the first (silently wrong above-right/below-left
11067 /// availability -- wrong pixels, no error).
11068 #[test]
11069 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
11070 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
11071 let (bw_log2, bh_log2) =
11072 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
11073 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
11074 for (name, table) in
11075 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
11076 {
11077 assert_eq!(
11078 table.len() * 8,
11079 rows * cols,
11080 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
11081 );
11082 let mut seen = vec![0u32; table.len() * 8];
11083 for blk_row in 0..rows {
11084 for blk_col in 0..cols {
11085 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
11086 assert!(
11087 idx < seen.len(),
11088 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
11089 );
11090 seen[idx] += 1;
11091 }
11092 }
11093 assert!(
11094 seen.iter().all(|&n| n == 1),
11095 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
11096 (row stride is not {cols})"
11097 );
11098 }
11099 }
11100 }
11101 use super::*;
11102 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
11103 use std::io::Write;
11104 use std::process::{Command, Stdio};
11105
11106 /// Every rectangular shape this decoder codes, at every position a block
11107 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
11108 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
11109 /// (`reconintra.c`) answer, whose bodies are ported below.
11110 ///
11111 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
11112 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
11113 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
11114 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
11115 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
11116 /// oracle's own arrays, so a re-routed or truncated table fails here even
11117 /// where the two rows happen to agree.
11118 ///
11119 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
11120 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
11121 /// callers handle by predicting each transform unit as its own block.
11122 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
11123 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
11124 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
11125 /// (the horizontal shapes, which those partitions never produce).
11126 #[test]
11127 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
11128 let fctx = &crate::decode::FrameCtx::new();
11129 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
11130 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
11131 (4, 8, 64, 9280, 64, 550),
11132 (8, 4, 64, 3712, 64, 9630),
11133 (8, 16, 16, 2352, 16, 134),
11134 (16, 8, 16, 960, 16, 2400),
11135 (16, 32, 4, 620, 4, 32),
11136 (32, 16, 4, 32, 4, 184),
11137 (32, 64, 1, 127, 1, 0),
11138 (64, 32, 1, 19, 1, 34),
11139 (4, 16, 32, 5472, 32, 14),
11140 (16, 4, 32, 960, 32, 6464),
11141 (8, 32, 8, 1400, 8, 2),
11142 (32, 8, 8, 32, 8, 1136),
11143 (16, 64, 2, 382, 2, 0),
11144 (64, 16, 2, 4, 2, 84),
11145 ];
11146 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
11147 /// a block whose transform covers it whole (`row_off == col_off == 0`,
11148 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
11149 /// superblock (`sb_mi_size == 16`).
11150 fn libaom_reach(
11151 bw: usize,
11152 bh: usize,
11153 x: usize,
11154 y: usize,
11155 width: usize,
11156 height: usize, _fctx: &crate::decode::FrameCtx,
11157 ) -> (bool, bool) {
11158 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
11159 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
11160 let sb_mi_size = 16usize;
11161 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
11162 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
11163 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
11164 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
11165 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
11166 // has_top_right: top_available && right_available, then row_off == 0.
11167 let top_right = if y == 0 || x + bw >= width {
11168 false
11169 } else if blk_row_in_sb == 0 {
11170 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
11171 // `bw_unit < bw_unit`, false for a whole-block transform.)
11172 true
11173 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
11174 false
11175 } else {
11176 bit(tr_table)
11177 };
11178 // has_bottom_left: bottom_available && left_available, col_off == 0.
11179 let bottom_left = if x == 0 || y + bh >= height {
11180 false
11181 } else if blk_col_in_sb == 0 {
11182 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
11183 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
11184 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
11185 false
11186 } else {
11187 bit(bl_table)
11188 };
11189 (top_right, bottom_left)
11190 }
11191 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
11192 let (tr, bl) = rect_reach_tables(bw, bh);
11193 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
11194 assert_eq!(
11195 (tr.len(), sum(tr), bl.len(), sum(bl)),
11196 (tr_len, tr_sum, bl_len, bl_sum),
11197 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
11198 );
11199 // Two superblocks across and down, so the superblock-relative
11200 // position (and not the frame position) is what decides.
11201 for sb_y in [0usize, 64] {
11202 for sb_x in [0usize, 64] {
11203 for y in (sb_y..sb_y + 64).step_by(bh) {
11204 for x in (sb_x..sb_x + 64).step_by(bw) {
11205 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
11206 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
11207 assert_eq!(
11208 (got.above_right, got.below_left),
11209 want,
11210 "{bw}x{bh} at ({x}, {y})"
11211 );
11212 }
11213 }
11214 }
11215 }
11216 }
11217 }
11218
11219 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
11220 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
11221 /// aomenc gate decodes its stream through ffmpeg and is meaningless
11222 /// without it -- turns it into a hard failure. Without this the require
11223 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
11224 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
11225 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
11226 fn have_ffmpeg() -> bool {
11227 let present = Command::new("ffmpeg")
11228 .arg("-version")
11229 .stdout(Stdio::null())
11230 .stderr(Stdio::null())
11231 .status()
11232 .is_ok_and(|s| s.success());
11233 assert!(
11234 present
11235 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
11236 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
11237 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
11238 );
11239 present
11240 }
11241
11242 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
11243 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
11244 let mut child = Command::new("ffmpeg")
11245 .args([
11246 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
11247 ])
11248 .stdin(Stdio::piped())
11249 .stdout(Stdio::piped())
11250 .stderr(Stdio::piped())
11251 .spawn()
11252 .expect("ffmpeg failed to start");
11253 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
11254 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
11255 // fills before the last input byte is written -- which is exactly what
11256 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
11257 // (measured: 45 min, both processes at 0% CPU). A write error here is
11258 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
11259 // below, are the real diagnosis.
11260 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
11261 let payload = stream.to_vec();
11262 let writer = std::thread::spawn(move || {
11263 let _ = stdin.write_all(&payload);
11264 });
11265 let out = child.wait_with_output().expect("ffmpeg failed to run");
11266 writer.join().expect("ffmpeg stdin writer thread");
11267 assert!(
11268 out.status.success(),
11269 "ffmpeg refused the stream: {}",
11270 String::from_utf8_lossy(&out.stderr)
11271 );
11272 let (luma, chroma) = (width * height, width * height / 4);
11273 assert_eq!(
11274 out.stdout.len(),
11275 luma + 2 * chroma,
11276 "expected one 4:2:0 frame"
11277 );
11278 Picture {
11279 width,
11280 height,
11281 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
11282 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
11283 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
11284 }
11285 }
11286
11287 /// A picture with something of everything in it: a gradient, an edge, a
11288 /// ripple and a block of flat colour, none of them aligned to the block
11289 /// grid.
11290 /// The in-loop filters actually FIRE and the stream still decodes to
11291 /// exactly what the encoder kept as its reconstruction
11292 /// (gate-blind-to-feature: a filter search that always answered "off"
11293 /// would leave every other test just as green, and the BD gate that
11294 /// would notice is `#[ignore]`d).
11295 ///
11296 /// Run:
11297 /// cargo test -p ec-av1 --release --lib -- \
11298 /// encode::tests::the_filter_search_picks_real_filters
11299 #[test]
11300 fn the_filter_search_picks_real_filters() {
11301 let _knobs = crate::speed::knob_read();
11302 let fctx = &crate::decode::FrameCtx::new();
11303 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
11304 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
11305 let fired = encoded
11306 .frames
11307 .iter()
11308 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
11309 .count();
11310 assert!(
11311 fired > 0,
11312 "no frame of this sequence chose any in-loop filtering: {:?}",
11313 encoded
11314 .frames
11315 .iter()
11316 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
11317 .collect::<Vec<_>>()
11318 );
11319 // The reconstruction the encoder predicts from is the FILTERED one,
11320 // and it is what a decoder of the stream produces -- byte for byte,
11321 // frame for frame.
11322 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
11323 assert_eq!(decoded.len(), encoded.frames.len());
11324 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
11325 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
11326 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
11327 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
11328 }
11329 }
11330
11331 fn test_card(width: usize, height: usize) -> Picture {
11332 let mut picture = Picture::grey(width, height);
11333 for y in 0..height {
11334 for x in 0..width {
11335 let gradient = x as f64 * 200.0 / width as f64;
11336 let ripple = 30.0
11337 * (x as f64 * std::f64::consts::PI / 23.0).sin()
11338 * (y as f64 * std::f64::consts::PI / 37.0).cos();
11339 let edge = if x > width * 3 / 7 && y > height / 3 {
11340 40.0
11341 } else {
11342 0.0
11343 };
11344 picture.y[y * width + x] =
11345 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
11346 }
11347 }
11348 for y in 0..height / 2 {
11349 for x in 0..width / 2 {
11350 let i = y * width / 2 + x;
11351 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
11352 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
11353 }
11354 }
11355 picture
11356 }
11357
11358 fn psnr(a: &[u16], b: &[u16]) -> f64 {
11359 let squared: f64 = a
11360 .iter()
11361 .zip(b)
11362 .map(|(&x, &y)| {
11363 let d = f64::from(x) - f64::from(y);
11364 d * d
11365 })
11366 .sum();
11367 if squared == 0.0 {
11368 return f64::INFINITY;
11369 }
11370 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
11371 }
11372
11373 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
11374 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
11375 /// frame's new root fires on most superblocks -- and what BOTH decoders
11376 /// produce is the encoder's own reconstruction, sample for sample.
11377 ///
11378 /// The fire count is the `gate-blind-to-feature` guard: without it every
11379 /// assert below passes on a stream that codes no whole superblock at all.
11380 #[test]
11381 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
11382 let _knobs = crate::speed::knob_read();
11383 let fctx = &crate::decode::FrameCtx::new();
11384 // 4 x 3 superblocks, all of them wholly inside the frame.
11385 let (width, height) = (256usize, 192usize);
11386 let mut picture = Picture::grey(width, height);
11387 for y in 0..height {
11388 for x in 0..width {
11389 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
11390 }
11391 }
11392 for y in 0..height / 2 {
11393 for x in 0..width / 2 {
11394 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
11395 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
11396 }
11397 }
11398 let _ = take_i64_root_hits();
11399 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
11400 let [roots, _offered] = take_i64_root_hits();
11401 // The counters are process-global, so another test encoding in
11402 // parallel can only ADD to them -- the per-FRAME fact is the mode
11403 // list, which carries one entry per coded block and so exactly 12
11404 // when every superblock was coded as one 64x64 intra block.
11405 assert_eq!(
11406 encoded.modes.len(),
11407 12,
11408 "not every superblock was coded as one 64x64 intra block"
11409 );
11410 assert!(
11411 roots >= 8,
11412 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
11413 );
11414 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
11415
11416 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
11417 assert_eq!(ours.len(), 1, "our decoder's frames");
11418 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
11419 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
11420 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
11421
11422 if !have_ffmpeg() {
11423 eprintln!("SKIP the ffmpeg half: no ffmpeg");
11424 return;
11425 }
11426 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11427 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
11428 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
11429 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
11430 }
11431
11432 /// The claim the whole encoder rests on: what a decoder produces is what
11433 /// the encoder said it would, sample for sample, on every plane.
11434 ///
11435 /// Prediction reads the reconstruction, so a single sample of drift
11436 /// anywhere would spread into every block below and to the right of it —
11437 /// which is why this is an equality and not a tolerance.
11438 #[test]
11439 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
11440 let _knobs = crate::speed::knob_read();
11441 let fctx = &crate::decode::FrameCtx::new();
11442 if !have_ffmpeg() {
11443 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
11444 return;
11445 }
11446 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48), (248, 152)] {
11447 let picture = test_card(width, height);
11448 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11449 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11450 assert_eq!(
11451 decoded.y, encoded.reconstruction.y,
11452 "{width}x{height}: luma"
11453 );
11454 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
11455 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
11456 }
11457 // One q index from each of the four coefficient-CDF contexts
11458 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
11459 let (width, height) = (64usize, 64usize);
11460 let picture = test_card(width, height);
11461 let _ = take_tx_depth_hits();
11462 for &q in &[15u8, 45, 100, 200] {
11463 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
11464 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11465 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
11466 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
11467 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
11468 }
11469 // lane-av1tx: the exactness above is only a claim about SPLIT
11470 // transforms if some block actually split one (`gate-blind-to-feature`
11471 // -- with `tx_depth` stuck at 0 every assert here passes on the
11472 // pre-lane stream). The test card's edges split at these four
11473 // quantizers; the counter is per-process (another test encoding in
11474 // parallel can only ADD to it, so this can be masked, never falsely
11475 // failed), so it is read once for the whole q ladder.
11476 let depths = take_tx_depth_hits();
11477 assert!(
11478 depths[1] + depths[2] > 0,
11479 "no block split its transform: depths {depths:?}"
11480 );
11481 }
11482
11483 /// A synthetic screen-content picture -- a few flat colours in a grid of
11484 /// boxes with hard edges and text-like bars, the shape a desktop capture
11485 /// has -- so the palette path is exercised on content it is for.
11486 #[cfg(test)]
11487 fn screen_card(width: usize, height: usize) -> Picture {
11488 const INK: [u16; 4] = [16, 90, 180, 235];
11489 let mut picture = Picture::grey(width, height);
11490 for y in 0..height {
11491 for x in 0..width {
11492 let cell = (x / 24 + y / 24) % 2;
11493 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
11494 picture.y[y * width + x] = INK[cell * 2 + bar];
11495 }
11496 }
11497 // Four chroma colours, not two: a two-colour chroma block only ever
11498 // codes a `PaletteSizeUV` of 2, which leaves
11499 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
11500 // deltas and the neighbour cache flags, exercised only when
11501 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
11502 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
11503 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
11504 for y in 0..height / 2 {
11505 for x in 0..width / 2 {
11506 let cell = (x / 12 + 2 * (y / 12)) % 4;
11507 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
11508 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
11509 }
11510 }
11511 picture
11512 }
11513
11514 /// The lane's own end-to-end check: on screen content the detector fires,
11515 /// blocks really take a palette (fire count, class
11516 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
11517 /// symbol this lane writes -- reconstructs exactly what the encoder did.
11518 /// The film-shaped `test_card` must NOT trip the detector, which is what
11519 /// keeps every non-screen stream byte-identical.
11520 #[test]
11521 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
11522 let _knobs = crate::speed::knob_read();
11523 let fctx = &crate::decode::FrameCtx::new();
11524 let (width, height) = (192usize, 96usize);
11525 let _ = crate::tile::take_palette_hits();
11526 let picture = screen_card(width, height);
11527 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11528 assert!(
11529 encoded.screen,
11530 "the detector did not fire on screen content -- no palette syntax was coded at all"
11531 );
11532 let hits = crate::tile::take_palette_hits();
11533 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
11534 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
11535 // The chroma half is a claim about the plane-1 syntax only if some
11536 // block really took a chroma palette (`gate-blind-to-feature`): every
11537 // exactness assert below passes on a stream that codes
11538 // `palette_uv_mode == 0` everywhere.
11539 let uv_hits = crate::tile::take_palette_uv_hits();
11540 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
11541 let uv_cached = crate::tile::take_palette_uv_cache_hits();
11542 eprintln!(
11543 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
11544 uv_hits[0],
11545 &uv_hits[2..]
11546 );
11547 assert!(
11548 uv_cached > 0,
11549 "no chroma base colour came out of the neighbour cache -- \
11550 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
11551 );
11552 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
11553 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
11554 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
11555 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
11556 if !have_ffmpeg() {
11557 eprintln!("SKIP the ffmpeg half: no ffmpeg");
11558 return;
11559 }
11560 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11561 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
11562 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
11563 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
11564 // A whole GOP: the inter frames' own intra blocks carry the palette
11565 // syntax too (the three intra arms of the inter writers), which only
11566 // ffmpeg reading the frames back can prove.
11567 let moved: Vec<Picture> = (0..4)
11568 .map(|f| {
11569 let base = screen_card(width, height);
11570 let mut out = Picture::grey(width, height);
11571 for y in 0..height {
11572 for x in 0..width {
11573 let sx = (x + f * 7) % width;
11574 out.y[y * width + x] = base.y[y * width + sx];
11575 }
11576 }
11577 for y in 0..height / 2 {
11578 for x in 0..width / 2 {
11579 let sx = (x + f * 3) % (width / 2);
11580 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
11581 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
11582 }
11583 }
11584 out
11585 })
11586 .collect();
11587 let _ = crate::tile::take_palette_hits();
11588 let _ = crate::tile::take_palette_uv_hits();
11589 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
11590 let gop_hits = crate::tile::take_palette_hits();
11591 let gop_uv_hits = crate::tile::take_palette_uv_hits();
11592 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
11593 eprintln!(
11594 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
11595 {} chroma palette blocks",
11596 inter_screen, gop_hits[0], gop_uv_hits[0]
11597 );
11598 assert!(
11599 gop_uv_hits[0] > 0,
11600 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
11601 );
11602 assert!(
11603 inter_screen > 0,
11604 "no inter frame set allow_screen_content_tools"
11605 );
11606 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
11607 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
11608 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
11609 }
11610 if have_ffmpeg() {
11611 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
11612 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
11613 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
11614 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
11615 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
11616 }
11617 }
11618
11619 // The other half of the keep rule: film-shaped content leaves the
11620 // detector (and so the whole sequence header) alone.
11621 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
11622 assert!(!film.screen, "the detector fired on the film-shaped test card");
11623 }
11624
11625 /// The lane's keep-rule measurement: the gate's own screen capture, one
11626 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
11627 /// Setting the bit forces deblocking, CDEF and loop restoration off for
11628 /// that frame, so the table is exactly the filter loss against the bytes
11629 /// the copied blocks save.
11630 #[test]
11631 #[ignore = "needs the real-library manifest and ffmpeg"]
11632 fn probe_intrabc_key_frame() {
11633 let _knobs = crate::speed::knob_write();
11634 let fctx = &crate::decode::FrameCtx::new();
11635 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11636 .join("../../fixtures");
11637 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
11638 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
11639 return;
11640 };
11641 let Some(clip) = manifest
11642 .lines()
11643 .skip(1)
11644 .filter_map(|l| l.split('\t').next())
11645 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
11646 else {
11647 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
11648 return;
11649 };
11650 let (width, height) = (640usize, 384usize);
11651 let picture = clip_frame(clip, "0", width, height);
11652 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
11653 for q in [5u8, 20, 35, 45] {
11654 for on in [false, true] {
11655 force_intrabc(Some(on));
11656 let _ = crate::tile::take_intrabc_hits();
11657 let _ = take_intrabc_search();
11658 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
11659 let hits = crate::tile::take_intrabc_hits();
11660 let search = take_intrabc_search();
11661 eprintln!(
11662 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
11663 if encoded.allow_intrabc { "on" } else { "off" },
11664 encoded.stream.len(),
11665 psnr_all(&encoded.reconstruction, &picture),
11666 hits[0],
11667 &hits[1..],
11668 search[0], search[1], search[2],
11669 );
11670 }
11671 }
11672 force_intrabc(None);
11673 }
11674
11675 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
11676 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
11677 /// take a block vector (fire count + DV histogram, class
11678 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
11679 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
11680 /// exactly what the encoder did.
11681 #[test]
11682 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
11683 let _knobs = crate::speed::knob_write();
11684 let fctx = &crate::decode::FrameCtx::new();
11685 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
11686 // superblocks of 64) and tall enough for a source superblock row
11687 // above the blocks that copy from it.
11688 let (width, height) = (512usize, 256usize);
11689 let picture = screen_card(width, height);
11690 let _ = crate::tile::take_intrabc_hits();
11691 // The default is OFF (it measured worse on the real screen capture --
11692 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
11693 // the arm on for its own encode and puts it back straight after.
11694 force_intrabc(Some(true));
11695 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11696 force_intrabc(None);
11697 assert!(
11698 encoded.allow_intrabc,
11699 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
11700 intrabc_source_share() * 100.0
11701 );
11702 let hits = crate::tile::take_intrabc_hits();
11703 eprintln!(
11704 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
11705 hits[0],
11706 &hits[1..],
11707 intrabc_source_share() * 100.0
11708 );
11709 let search = take_intrabc_search();
11710 eprintln!(
11711 "intrabc searches {} found-valid {} won-RD {}",
11712 search[0], search[1], search[2]
11713 );
11714 assert!(
11715 hits[0] > 0,
11716 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
11717 );
11718 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
11719 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
11720 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
11721 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
11722 if !have_ffmpeg() {
11723 eprintln!("SKIP the ffmpeg half: no ffmpeg");
11724 return;
11725 }
11726 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11727 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
11728 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
11729 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
11730 }
11731
11732 /// The minimal repro that isolated the inter-residual desync: a key frame
11733 /// followed by one inter frame whose single superblock carries one
11734 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
11735 /// coefficient, its three sibling blocks all `skip: true`. Before the
11736 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
11737 /// found when processing input") even though every symbol either block
11738 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
11739 /// same coefficient syntax decodes clean on every intra key-frame gate).
11740 #[test]
11741 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
11742 let _knobs = crate::speed::knob_write();
11743 let fctx = &crate::decode::FrameCtx::new();
11744 if !have_ffmpeg() {
11745 eprintln!(
11746 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
11747 );
11748 return;
11749 }
11750 let (width, height) = (64usize, 64usize);
11751 let picture = Picture::grey(width, height);
11752 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11753
11754 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
11755 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
11756
11757 let residual_block = BlockCoeffs {
11758 angle_delta_y: 0,
11759 cfl_alphas: None,
11760 filter_intra: None,
11761 luma: vec![Coeff {
11762 row: 0,
11763 col: 0,
11764 level: 4,
11765 }],
11766 u: Vec::new(),
11767 v: Vec::new(),
11768 mode: 0,
11769 uv_mode: 0,
11770 skip: false,
11771 eight: None,
11772 dv: None,
11773 palette: None,
11774 palette_uv: None,
11775 tx_depth: 0,
11776 inter: Some(InterInfo {
11777 ref1: None,
11778 mv1: (0, 0),
11779 ref_frame: crate::mvstack::LAST_FRAME,
11780 mode: InterMode::NearestMv,
11781 mv: (0, 0),
11782 ref_mv_idx: 0,
11783 }),
11784 motion_mode: 0,
11785 };
11786 let skipped_block = BlockCoeffs {
11787 skip: true,
11788 inter: Some(InterInfo {
11789 ref1: None,
11790 mv1: (0, 0),
11791 ref_frame: crate::mvstack::LAST_FRAME,
11792 mode: InterMode::NearestMv,
11793 mv: (0, 0),
11794 ref_mv_idx: 0,
11795 }),
11796 ..BlockCoeffs::default()
11797 };
11798 let blocks = vec![
11799 Quadrant::Whole(residual_block),
11800 Quadrant::Whole(skipped_block.clone()),
11801 Quadrant::Whole(skipped_block.clone()),
11802 Quadrant::Whole(skipped_block),
11803 ];
11804 // lane-av1obmc: the header this tile is decoded under carries
11805 // `is_motion_mode_switchable`, so the writer must be armed with it
11806 // too or the decoder reads a `motion_mode` symbol nobody wrote.
11807 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
11808 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
11809 let tile =
11810 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
11811 .unwrap();
11812
11813 // `key.stream` is already a temporal delimiter, the sequence header
11814 // and the key frame's own OBU (`encode_key_frame` built it from the
11815 // same `key_frame_headers(width, height, 100)` this test calls), so
11816 // the inter frame's OBU is appended straight onto it rather than
11817 // re-deriving the key frame's tile bytes.
11818 let mut stream = key.stream.clone();
11819 stream.extend_from_slice(&temporal_delimiter());
11820 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
11821
11822 ffmpeg_decode_sequence(&stream, width, height, 2);
11823 }
11824
11825 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
11826 /// frame size an AV1 decoder allocates, not necessarily the render size
11827 /// (see [`a_frame_round_trips_at_its_own_size`]).
11828 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
11829 // Distinct per call, not per process: the test binary runs callers on
11830 // parallel threads, and a shared name lets one test's cleanup delete
11831 // the stream another test's ffprobe is still reading.
11832 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
11833 let path = std::env::temp_dir().join(format!(
11834 "ec-av1-probe-{}-{}.obu",
11835 std::process::id(),
11836 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
11837 ));
11838 let _ = std::fs::remove_file(&path);
11839 std::fs::write(&path, stream).expect("writing the probe stream");
11840 let out = Command::new("ffprobe")
11841 .args([
11842 "-v",
11843 "error",
11844 "-f",
11845 "obu",
11846 "-select_streams",
11847 "v:0",
11848 "-show_entries",
11849 "stream=width,height",
11850 "-of",
11851 "csv=p=0",
11852 ])
11853 .arg(&path)
11854 .output()
11855 .expect("ffprobe failed to run");
11856 let _ = std::fs::remove_file(&path);
11857 assert!(
11858 out.status.success(),
11859 "ffprobe refused the stream: {}",
11860 String::from_utf8_lossy(&out.stderr)
11861 );
11862 let text = String::from_utf8_lossy(&out.stdout);
11863 let mut fields = text.trim().split(',');
11864 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
11865 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
11866 (width, height)
11867 }
11868
11869 /// lane-av1cap: the final filter replay against the capture decode it
11870 /// replaced, at the block-padded and straddling sizes the whole-frame
11871 /// tests cover -- `set_verify_final_replay` makes
11872 /// [`pick_and_apply_filters`] run both on every frame and assert, per
11873 /// frame, that the spliced picture and the two filter stages the
11874 /// restoration search reads are bit-identical over the frame's own crop.
11875 #[test]
11876 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
11877 let _knobs = crate::speed::knob_write();
11878 let fctx = &crate::decode::FrameCtx::new();
11879 crate::decode::set_verify_final_replay(true);
11880 for &(width, height) in
11881 &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)]
11882 {
11883 eprintln!("--- {width}x{height}");
11884 let picture = test_card(width, height);
11885 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11886 }
11887 crate::decode::set_verify_final_replay(false);
11888 }
11889
11890 /// A key frame at an arbitrary even size round-trips through ffmpeg over
11891 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
11892 /// picture's own size, and what ffmpeg decodes over that same top-left
11893 /// region equals it sample for sample.
11894 ///
11895 /// This does not check that `ffprobe` reports the picture's own size,
11896 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
11897 /// (block-padded) frame size, the same one libaom itself would code for
11898 /// a non-block-aligned picture. `render_width`/`render_height` (which
11899 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
11900 /// decoder is required to crop pixels by, and ffmpeg's does not --
11901 /// checked empirically against ffprobe here and against a real libaom
11902 /// encode separately. So the coded size, not the render size, is what
11903 /// `ffprobe` is asserted to report below.
11904 #[test]
11905 fn a_frame_round_trips_at_its_own_size() {
11906 let _knobs = crate::speed::knob_read();
11907 let fctx = &crate::decode::FrameCtx::new();
11908 if !have_ffmpeg() {
11909 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
11910 return;
11911 }
11912 // 854x480 is covered separately by
11913 // `an_854x480_picture_round_trips_through_its_padding`, which its own
11914 // doc comment explains was worth keeping as its own test.
11915 for &(width, height) in &[
11916 (1920usize, 1080usize),
11917 (640, 352),
11918 (1280, 720),
11919 (64, 56),
11920 (854, 480),
11921 (216, 96),
11922 (192, 120),
11923 ] {
11924 let picture = test_card(width, height);
11925 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11926 assert_eq!(
11927 (encoded.reconstruction.width, encoded.reconstruction.height),
11928 (width, height),
11929 "{width}x{height}: reconstruction is cropped to the picture's own size"
11930 );
11931 assert_eq!(
11932 ffprobe_size(&encoded.stream),
11933 (width as u32, height as u32),
11934 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
11935 );
11936 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11937 assert_eq!(
11938 decoded.y, encoded.reconstruction.y,
11939 "{width}x{height}: luma"
11940 );
11941 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
11942 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
11943 }
11944 }
11945
11946 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
11947 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
11948 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
11949 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
11950 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
11951 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
11952 /// col`) -- different bits of an 8-byte table, one true, one false. The
11953 /// stride libaom indexes by is fixed at its compile-time maximum
11954 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
11955 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
11956 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
11957 /// row/col position within the (correctly 64-relative) superblock stayed
11958 /// right, only the table's own row stride was wrong. Fixed in
11959 /// `Reach::table_stride`; not an arithmetic-coder desync (an
11960 /// EC_RNG-per-symbol trace against the same debug decoder found the
11961 /// bitstream byte-for-byte identical to libaom's across all 51188
11962 /// symbols of this frame before this bug was found).
11963 ///
11964 /// Since the frame header started writing the true (unpadded) display
11965 /// size into `frame_width`/`frame_height` rather than the padded coded
11966 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
11967 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
11968 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
11969 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
11970 /// the header's own size before output).
11971 #[test]
11972 fn an_854x480_picture_round_trips_through_its_padding() {
11973 let _knobs = crate::speed::knob_read();
11974 let fctx = &crate::decode::FrameCtx::new();
11975 if !have_ffmpeg() {
11976 return;
11977 }
11978 let (width, height) = (854usize, 480usize);
11979 let picture = test_card(width, height);
11980 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11981 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11982 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
11983 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
11984 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
11985 }
11986
11987 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
11988 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
11989 /// superblock, both partition tables:
11990 ///
11991 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
11992 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
11993 /// wiring the TU sites onto it changes no existing stream;
11994 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
11995 /// NULL in libaom because that lookup never happens, and reading a
11996 /// 4x4 row out of the three-row vert tables is what crashed a real
11997 /// `--enable-tx-size-search=1` stream (r2);
11998 /// 3. and it must be the BLOCK's vert answer where the two tables
11999 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
12000 /// row 1, column 0 reads its above-right samples from the 8x8 to its
12001 /// upper right, which a vertical AB partition codes AFTER it
12002 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
12003 #[test]
12004 fn of_tu_follows_the_block_row_including_under_vert_ab() {
12005 let fctx = &crate::decode::FrameCtx::new();
12006 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
12007 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
12008 // above-right answer is the BLOCK's, which is the whole reason a unit
12009 // asks the block instead of looking itself up (the
12010 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
12011 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
12012 assert_eq!(
12013 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
12014 plain.above_right,
12015 "ordinary table: the top-right TX4 unit takes the block's row"
12016 );
12017 let guard = Reach::vert_ab_partition();
12018 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
12019 assert_eq!(
12020 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
12021 vert.above_right,
12022 "vert AB: the unit follows the vert row the block just picked"
12023 );
12024 assert_ne!(
12025 plain.above_right, vert.above_right,
12026 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
12027 );
12028 drop(guard);
12029 }
12030
12031 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
12032 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
12033 /// reconintra.c`), for every 16x16 and 32x32 block position across three
12034 /// superblocks square -- interior and every superblock edge (top row,
12035 /// left column, right column, bottom row) both sizes reach. Written to
12036 /// catch the class the `table_stride` bug was: an index stride silently
12037 /// wrong for one block size while looking plausible for the other.
12038 #[test]
12039 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
12040 let fctx = &crate::decode::FrameCtx::new();
12041 // Transcribed from has_top_right/has_bottom_left's row_off==0,
12042 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
12043 // 128px reference grid) pinned as libaom pins it, independent of the
12044 // 64px superblock this crate actually codes.
12045 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
12046 if y == 0 || x + side >= width {
12047 return false;
12048 }
12049 let (row, col, per_side) = (
12050 (y % SUPERBLOCK) / side,
12051 (x % SUPERBLOCK) / side,
12052 SUPERBLOCK / side,
12053 );
12054 if row == 0 {
12055 return true;
12056 }
12057 if col + 1 == per_side {
12058 return false;
12059 }
12060 let stride = 128 / side;
12061 let index = row * stride + col;
12062 let table = if side == BLOCK {
12063 [95u8, 87].to_vec()
12064 } else {
12065 vec![255, 85, 119, 85, 127, 85, 119, 85]
12066 };
12067 (table[index / 8] >> (index % 8)) & 1 != 0
12068 }
12069
12070 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
12071 if x == 0 || y + side >= height {
12072 return false;
12073 }
12074 let (row, col, per_side) = (
12075 (y % SUPERBLOCK) / side,
12076 (x % SUPERBLOCK) / side,
12077 SUPERBLOCK / side,
12078 );
12079 if col == 0 {
12080 return row * side + side < SUPERBLOCK;
12081 }
12082 if row + 1 == per_side {
12083 return false;
12084 }
12085 let stride = 128 / side;
12086 let index = row * stride + col;
12087 let table = if side == BLOCK {
12088 [4u8, 4].to_vec()
12089 } else {
12090 vec![84, 16, 84, 0, 84, 16, 84, 0]
12091 };
12092 (table[index / 8] >> (index % 8)) & 1 != 0
12093 }
12094
12095 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
12096 for side in [16usize, BLOCK] {
12097 for y in (0..height).step_by(side) {
12098 for x in (0..width).step_by(side) {
12099 let reach = Reach::of(side, x, y, width, height, fctx);
12100 assert_eq!(
12101 reach.above_right,
12102 libaom_top_right(side, x, y, width, height),
12103 "side={side} x={x} y={y}: above_right"
12104 );
12105 assert_eq!(
12106 reach.below_left,
12107 libaom_bottom_left(side, x, y, height, fctx),
12108 "side={side} x={x} y={y}: below_left"
12109 );
12110 }
12111 }
12112 }
12113 }
12114
12115 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
12116 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
12117 /// column inside the superblock) may read the below-left samples the
12118 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
12119 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
12120 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
12121 /// stream that partitions that small first hits the still-refused
12122 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
12123 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
12124 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
12125 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
12126 /// pixels -- lane-palette2 r12: the square multi-TU path used the
12127 /// standalone-block tables instead of this rule and granted a 16x16
12128 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
12129 #[test]
12130 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
12131 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
12132 // *_count_unit = tx size / 4.
12133 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
12134 let (plane_bw_unit, count) = (bw / 4, tx / 4);
12135 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
12136 let _ = bh;
12137 if row_off_u > 0 {
12138 col_off_u + count < plane_bw_unit
12139 } else if col_off_u + count < plane_bw_unit {
12140 true
12141 } else {
12142 blk
12143 }
12144 }
12145 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
12146 let (plane_bh_unit, count) = (bh / 4, tx / 4);
12147 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
12148 let _ = bw;
12149 if col_off_u > 0 {
12150 false
12151 } else if row_off_u + count < plane_bh_unit {
12152 true
12153 } else {
12154 blk
12155 }
12156 }
12157 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
12158 for &tx in &[4usize, 8, 16, 32] {
12159 if tx > bw.min(bh) {
12160 continue;
12161 }
12162 for row_off in (0..bh).step_by(tx) {
12163 for col_off in (0..bw).step_by(tx) {
12164 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
12165 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
12166 assert_eq!(
12167 got.above_right,
12168 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
12169 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
12170 );
12171 assert_eq!(
12172 got.below_left,
12173 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
12174 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
12175 );
12176 }
12177 }
12178 }
12179 }
12180 }
12181 }
12182
12183 #[test]
12184 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
12185 let fctx = &crate::decode::FrameCtx::new();
12186 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
12187 // Interior superblock, so neither the frame edge nor the col == 0 /
12188 // last-row early returns answer instead of the table.
12189 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
12190 let mut flipped = 0;
12191 for row in 0..8 {
12192 for col in 1..8 {
12193 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
12194 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
12195 let vert = {
12196 let _guard = Reach::vert_ab_partition();
12197 Reach::of(8, x, y, width, height, fctx).below_left
12198 };
12199 // The TR square of a VERT_A/_B sits at an even row, odd
12200 // column; every other slot must be untouched by the guard.
12201 if row % 2 == 0 && col % 2 == 1 {
12202 assert!(!raster, "raster below_left at row={row} col={col}");
12203 assert!(vert, "vert below_left at row={row} col={col}");
12204 flipped += 1;
12205 } else {
12206 assert_eq!(raster, vert, "guard moved row={row} col={col}");
12207 }
12208 }
12209 }
12210 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
12211 // The guard is scoped: it must not leak past its own block.
12212 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
12213 }
12214
12215 /// An odd width or height is refused by name, not by however the padder
12216 /// or the block coder would happen to fail on it.
12217 #[test]
12218 fn odd_dimensions_are_refused() {
12219 let _knobs = crate::speed::knob_read();
12220 let fctx = &crate::decode::FrameCtx::new();
12221 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
12222 let picture = Picture::grey(width, height);
12223 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
12224 .expect_err(&format!("{width}x{height} is odd and must be refused"));
12225 assert!(
12226 err.to_string().contains("even"),
12227 "{width}x{height}: error was {err}"
12228 );
12229 }
12230 }
12231
12232 /// A sequence at a size that is not a multiple of the block grid decodes
12233 /// to the right frame count and the right size for every frame,
12234 /// including the inter frames whose reference is the previous frame's
12235 /// own (padded) reconstruction.
12236 #[test]
12237 fn sequence_round_trips_at_a_non_multiple_size() {
12238 let _knobs = crate::speed::knob_read();
12239 let fctx = &crate::decode::FrameCtx::new();
12240 if !have_ffmpeg() {
12241 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
12242 return;
12243 }
12244 let (width, height) = (160usize, 96usize);
12245 let pictures: Vec<Picture> = (0..3)
12246 .map(|i| panned_test_card(width, height, i * 3))
12247 .collect();
12248 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
12249 assert_eq!(encoded.frames.len(), 3);
12250 for (i, frame) in encoded.frames.iter().enumerate() {
12251 assert_eq!(
12252 (frame.reconstruction.width, frame.reconstruction.height),
12253 (width, height),
12254 "frame {i}: reconstruction size"
12255 );
12256 }
12257 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
12258 // true (display) size a sequence's frames share, not the padded one.
12259 assert_eq!(
12260 ffprobe_size(&encoded.stream),
12261 (width as u32, height as u32),
12262 "sequence: ffprobe reports the true (display) size"
12263 );
12264 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
12265 assert_eq!(decoded.len(), 3, "decoded frame count");
12266 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
12267 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
12268 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
12269 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
12270 }
12271 }
12272
12273 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
12274 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
12275 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
12276 /// `pos + side_mi / 2 < bound` boundary), which is the case
12277 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
12278 /// refusing. A key frame alone already covered this size; this proves the
12279 /// inter tile writer's parity with it across a real multi-frame export.
12280 #[test]
12281 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
12282 let _knobs = crate::speed::knob_read();
12283 let fctx = &crate::decode::FrameCtx::new();
12284 if !have_ffmpeg() {
12285 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
12286 return;
12287 }
12288 let (width, height) = (1280usize, 720usize);
12289 let pictures: Vec<Picture> = (0..3)
12290 .map(|i| panned_test_card(width, height, i * 3))
12291 .collect();
12292 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
12293 assert_eq!(encoded.frames.len(), 3);
12294 for (i, frame) in encoded.frames.iter().enumerate() {
12295 assert_eq!(
12296 (frame.reconstruction.width, frame.reconstruction.height),
12297 (width, height),
12298 "frame {i}: reconstruction size"
12299 );
12300 }
12301 assert_eq!(
12302 ffprobe_size(&encoded.stream),
12303 (width as u32, height as u32),
12304 "ffprobe reports the true (display) 1280x720 size"
12305 );
12306 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
12307 assert_eq!(decoded.len(), 3, "decoded frame count");
12308 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
12309 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
12310 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
12311 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
12312 }
12313 }
12314
12315 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
12316 /// leaf's own half (`has_half` at the SUB level) itself straddles the
12317 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
12318 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
12319 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
12320 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
12321 /// straddling-16x16 branch), so an inter frame no longer refuses this
12322 /// size either. This only proves the encoder does not error out -- see
12323 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
12324 /// decoder-clean proof (a 3-frame sequence, so the inter path is
12325 /// actually exercised).
12326 #[test]
12327 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
12328 let _knobs = crate::speed::knob_read();
12329 let fctx = &crate::decode::FrameCtx::new();
12330 let (width, height) = (640usize, 360usize);
12331 let picture = Picture::grey(width, height);
12332 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
12333
12334 // `encode_sequence`'s second frame is the inter path: same size, now
12335 // wired the same way.
12336 let pictures = vec![picture.clone(), picture];
12337 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
12338 .expect("inter frame now codes the mod-32==8 straddle too");
12339 }
12340
12341 /// The r15 fix at production size: three 640x360 key frames (inter is
12342 /// still refused at this size, per the test above, so this stands in for
12343 /// the charter's "3-frame sequence" using three independent key frames of
12344 /// shifted content), each proven decoder-clean through ffmpeg rather than
12345 /// only encoder-clean.
12346 #[test]
12347 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
12348 let _knobs = crate::speed::knob_read();
12349 let fctx = &crate::decode::FrameCtx::new();
12350 if !have_ffmpeg() {
12351 eprintln!(
12352 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
12353 no ffmpeg"
12354 );
12355 return;
12356 }
12357 let (width, height) = (640usize, 360usize);
12358 for shift in [0i64, 7, 19] {
12359 let picture = panned_test_card(width, height, shift);
12360 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
12361 let decoded = ffmpeg_decode(&encoded.stream, width, height);
12362 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
12363 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
12364 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
12365 }
12366 }
12367
12368 /// The 640x360 straddle class, but through the inter path an actual
12369 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
12370 /// proves the leaf-8 inter stream this round wires up is not just
12371 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
12372 #[test]
12373 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
12374 let _knobs = crate::speed::knob_read();
12375 let fctx = &crate::decode::FrameCtx::new();
12376 if !have_ffmpeg() {
12377 eprintln!(
12378 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
12379 );
12380 return;
12381 }
12382 let (width, height) = (640usize, 360usize);
12383 let pictures: Vec<Picture> = (0..4)
12384 .map(|i| panned_test_card(width, height, i * 3))
12385 .collect();
12386 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
12387 assert_eq!(encoded.frames.len(), 4);
12388 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
12389 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
12390 }
12391 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
12392 assert_eq!(decoded.len(), 4, "decoded frame count");
12393 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
12394 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
12395 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
12396 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
12397 }
12398 }
12399
12400 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
12401 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
12402 let out = Command::new("ffmpeg")
12403 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
12404 .args(["-vf", &format!("scale={width}:{height}")])
12405 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
12406 .output()
12407 .expect("ffmpeg failed to run");
12408 assert!(
12409 out.status.success(),
12410 "ffmpeg: {}",
12411 String::from_utf8_lossy(&out.stderr)
12412 );
12413 let (luma, chroma) = (width * height, width * height / 4);
12414 assert_eq!(
12415 out.stdout.len(),
12416 luma + 2 * chroma,
12417 "expected one 4:2:0 frame"
12418 );
12419 Picture {
12420 width,
12421 height,
12422 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
12423 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
12424 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
12425 }
12426 }
12427
12428 /// Prints what the mode search saves over DC prediction alone, for the
12429 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
12430 /// weight the search puts on rate can be swept.
12431 #[test]
12432 #[ignore = "a sweep, not a gate"]
12433 fn probe_lambda() {
12434 let _knobs = crate::speed::knob_read();
12435 let fctx = &crate::decode::FrameCtx::new();
12436 let mut pictures = vec![
12437 ("test card".to_string(), test_card(160, 96)),
12438 ("stripes".to_string(), stripes(160, 96, true)),
12439 ];
12440 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
12441 for entry in clips.split(':').filter(|e| !e.is_empty()) {
12442 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
12443 let name = path.rsplit('/').next().unwrap_or(path).to_string();
12444 pictures.push((name, clip_frame(path, skip, 640, 352)));
12445 }
12446 }
12447 for (name, picture) in pictures {
12448 let dc = ladder(&picture, &[DC_PRED], fctx);
12449 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
12450 println!(
12451 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
12452 bd_rate(&dc, &searched) * 100.0,
12453 10f64.powf(searched[1].1),
12454 searched[1].0,
12455 10f64.powf(dc[1].1),
12456 dc[1].0,
12457 );
12458 }
12459 }
12460
12461 /// Prints the whole mode-search ladder, so two builds of the search can be
12462 /// compared against each other rather than each against its own baseline.
12463 #[test]
12464 #[ignore = "a sweep, not a gate"]
12465 fn probe_ladder() {
12466 let _knobs = crate::speed::knob_read();
12467 let fctx = &crate::decode::FrameCtx::new();
12468 for (name, picture) in sweep_pictures() {
12469 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
12470 let points = all
12471 .iter()
12472 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
12473 .collect::<Vec<_>>()
12474 .join(" ");
12475 println!("ladder {name}: {points}");
12476 }
12477 }
12478
12479 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
12480 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
12481 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
12482 #[test]
12483 #[ignore = "a sweep, not a gate"]
12484 fn probe_split() {
12485 let _knobs = crate::speed::knob_read();
12486 let fctx = &crate::decode::FrameCtx::new();
12487 for (name, picture) in sweep_pictures() {
12488 let ladder = |split: bool| {
12489 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
12490 .iter()
12491 .map(|&q| {
12492 let encoded = encode_key_frame_inner(
12493 &picture,
12494 q,
12495 0.5,
12496 &KEY_FRAME_MODES,
12497 split,
12498 (picture.width, picture.height),
12499 unspecified_color_config(), fctx,
12500 )
12501 .unwrap();
12502 (
12503 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
12504 (encoded.stream.len() as f64).log10(),
12505 )
12506 })
12507 .collect();
12508 points.sort_by(|a, b| a.0.total_cmp(&b.0));
12509 points
12510 };
12511 let (whole, split) = (ladder(false), ladder(true));
12512 let blocks = encode_key_frame_inner(
12513 &picture,
12514 90,
12515 0.5,
12516 &KEY_FRAME_MODES,
12517 true,
12518 (picture.width, picture.height),
12519 unspecified_color_config(), fctx,
12520 )
12521 .unwrap()
12522 .modes
12523 .len();
12524 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
12525 println!(
12526 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
12527 bd_rate(&whole, &split) * 100.0
12528 );
12529 }
12530 }
12531
12532 /// A striped picture, running one way or the other. The stripes are what
12533 /// separates a vertical predictor from a horizontal one: a mode search
12534 /// reading a transposed edge would pick the wrong one of the pair, which no
12535 /// symmetric picture would show.
12536 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
12537 let mut picture = Picture::grey(width, height);
12538 for y in 0..height {
12539 for x in 0..width {
12540 let along = if vertical { x } else { y };
12541 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
12542 }
12543 }
12544 picture
12545 }
12546
12547 /// Where two planes first disagree, and by how much: a mismatch reported as
12548 /// a position says which block and which sample of it went wrong, which a
12549 /// pair of thousand-sample arrays does not.
12550 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
12551 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
12552 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
12553 Some(format!(
12554 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
12555 i % width,
12556 i / width,
12557 ours[i],
12558 theirs[i]
12559 ))
12560 }
12561
12562 /// Every mode the encoder offers has to predict what the decoder predicts,
12563 /// not just the ones a particular picture happens to choose: each is forced
12564 /// over a whole picture and the reconstruction gated against ffmpeg.
12565 #[test]
12566 fn every_mode_decodes_to_what_the_encoder_predicted() {
12567 let _knobs = crate::speed::knob_write();
12568 let fctx = &crate::decode::FrameCtx::new();
12569 if !have_ffmpeg() {
12570 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
12571 return;
12572 }
12573 // A mode ablation measures the MODE search: a filter-intra block is
12574 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
12575 // "the encoder coded something else" check for a reason that is not
12576 // about the mode search at all.
12577 force_filter_intra(Some(false));
12578 // 128 wide is a whole number of superblocks and 160 is not: the last
12579 // superblock of a 160-wide row is half a one, whose blocks have no
12580 // above-right samples inside the frame at all.
12581 for (width, height) in [(128, 96), (160, 96)] {
12582 let picture = test_card(width, height);
12583 for mode in KEY_FRAME_MODES {
12584 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
12585 let decoded = ffmpeg_decode(&encoded.stream, width, height);
12586 for (plane, ours, theirs, stride) in [
12587 ("luma", &encoded.reconstruction.y, &decoded.y, width),
12588 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
12589 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
12590 ] {
12591 assert!(
12592 first_difference(ours, theirs, stride).is_none(),
12593 "{width}x{height} mode {mode}, {plane}: {}",
12594 first_difference(ours, theirs, stride).unwrap()
12595 );
12596 }
12597 assert!(
12598 encoded.modes.iter().all(|&m| m == mode),
12599 "mode {mode}: the encoder coded something else"
12600 );
12601 }
12602 }
12603 }
12604
12605 /// The search has to follow the picture: vertical stripes are cheapest
12606 /// predicted from the row above, horizontal ones from the column to the
12607 /// left. Reading the edges the other way round would swap the two answers
12608 /// while leaving every fidelity gate intact.
12609 #[test]
12610 fn the_search_picks_the_direction_the_picture_runs() {
12611 let _knobs = crate::speed::knob_write();
12612 let fctx = &crate::decode::FrameCtx::new();
12613 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
12614 // a filter-intra block is coded `DC_PRED` whatever mode the arm
12615 // offers, and these stripes are SCREEN content, where the filter arm
12616 // now searches its own transform depth (lane-fitu) and wins outright
12617 // -- which says nothing about the mode search this gate measures.
12618 force_filter_intra(Some(false));
12619 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
12620 let picture = stripes(128, 96, vertical);
12621 // Only the pair, because on stripes a third mode predicts exactly
12622 // what the right one of the pair does -- PAETH reads the corner and
12623 // the left column, which a striped picture makes equal -- and the
12624 // tie then goes to whichever is cheaper to name, which is not what
12625 // this gate is about.
12626 let encoded =
12627 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
12628 // The first block of the picture has neither neighbour, so it
12629 // cannot tell the modes apart; every other one can.
12630 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
12631 assert!(
12632 picked * 2 > encoded.modes.len() - 1,
12633 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
12634 encoded.modes.len() - 1,
12635 encoded.modes
12636 );
12637 }
12638 }
12639
12640 /// What the search is for: the same picture, at the same quantizer, coded
12641 /// smaller and more faithfully than DC alone can manage.
12642 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
12643 /// between the two rate-distortion curves in log-rate against PSNR, as a
12644 /// fraction of the reference's rate. Negative means the second curve costs
12645 /// less for the same picture.
12646 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
12647 let low = reference[0].0.max(other[0].0);
12648 let high = reference[reference.len() - 1]
12649 .0
12650 .min(other[other.len() - 1].0);
12651 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
12652 // the non-directional one on the synthetic diagonals -- every point
12653 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
12654 // to integrate over any more. A curve that dominates that way has
12655 // saved everything the measure can express (the
12656 // `instrument-at-bound` class: the answer is at the instrument's own
12657 // edge, not undefined), so name it rather than panicking; anything
12658 // less clean than strict dominance still is.
12659 if high <= low {
12660 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
12661 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
12662 let dominates = other[0].0 > reference[reference.len() - 1].0
12663 && other_hi_rate <= ref_lo_rate;
12664 assert!(
12665 dominates,
12666 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
12667 );
12668 return -1.0;
12669 }
12670 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
12671 let i = curve
12672 .windows(2)
12673 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
12674 .unwrap_or(0);
12675 let (x0, y0) = curve[i];
12676 let (x1, y1) = curve[i + 1];
12677 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
12678 };
12679 let steps = 64;
12680 let mut area = 0.0;
12681 for step in 0..steps {
12682 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
12683 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
12684 }
12685 10f64.powf(area / f64::from(steps)) - 1.0
12686 }
12687
12688 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
12689 /// fidelity.
12690 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
12691 // A mode ablation measures the MODE search: the palette would code
12692 // these synthetic two-colour pictures losslessly under every arm and
12693 // leave nothing to compare (see [`force_screen`]).
12694 force_screen(Some(false));
12695 // Same reason, for the filter-intra candidate: it wins blocks under
12696 // BOTH arms of a mode ablation and so cancels the difference the
12697 // ablation measures (class `gate-recipe-confound`).
12698 force_filter_intra(Some(false));
12699 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
12700 .iter()
12701 .map(|&q| {
12702 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
12703 (
12704 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
12705 (encoded.stream.len() as f64).log10(),
12706 )
12707 })
12708 .collect();
12709 points.sort_by(|a, b| a.0.total_cmp(&b.0));
12710 points
12711 }
12712
12713 /// What the search is for: the same pictures cost less to code at the same
12714 /// fidelity than DC prediction alone can manage. A picture that runs one
12715 /// way saves far more than a busy one, which is the shape a working
12716 /// directional pair has.
12717 #[test]
12718 fn the_search_beats_dc_alone() {
12719 let _knobs = crate::speed::knob_read();
12720 let fctx = &crate::decode::FrameCtx::new();
12721 for (name, picture, want) in [
12722 ("test card", test_card(160, 96), -0.05),
12723 ("stripes", stripes(160, 96, true), -0.40),
12724 ] {
12725 let saved = bd_rate(
12726 &ladder(&picture, &[DC_PRED], fctx),
12727 &ladder(&picture, &NON_DIRECTIONAL, fctx),
12728 );
12729 assert!(
12730 saved < want,
12731 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
12732 saved * 100.0,
12733 -want * 100.0
12734 );
12735 }
12736 }
12737
12738 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
12739 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
12740 fn sweep_pictures() -> Vec<(String, Picture)> {
12741 let mut pictures = vec![
12742 ("test card".to_string(), test_card(160, 96)),
12743 ("stripes".to_string(), stripes(160, 96, true)),
12744 ("diagonal".to_string(), diagonal(160, 96, true)),
12745 ];
12746 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
12747 for entry in clips.split(':').filter(|e| !e.is_empty()) {
12748 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
12749 let name = path.rsplit('/').next().unwrap_or(path).to_string();
12750 pictures.push((name, clip_frame(path, skip, 640, 352)));
12751 }
12752 }
12753 pictures
12754 }
12755
12756 /// What the six directional modes are worth, per picture, at whatever
12757 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
12758 /// no further, and how often the search picks one.
12759 #[test]
12760 #[ignore = "a sweep, not a gate"]
12761 fn probe_directional() {
12762 let _knobs = crate::speed::knob_write();
12763 let fctx = &crate::decode::FrameCtx::new();
12764 for (name, picture) in sweep_pictures() {
12765 let dc = ladder(&picture, &[DC_PRED], fctx);
12766 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
12767 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
12768 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
12769 let directional = encoded
12770 .modes
12771 .iter()
12772 .filter(|&&m| (3..=8).contains(&m))
12773 .count();
12774 // A picture whose ladders sit at different fidelities altogether
12775 // has no BD-rate to report -- see the flat-sample-window class.
12776 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
12777 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
12778 };
12779 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
12780 if overlap(a, b) {
12781 format!("{:+.2}%", bd_rate(a, b) * 100.0)
12782 } else {
12783 "no overlap".to_string()
12784 }
12785 };
12786 println!(
12787 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
12788 against(&flat, &all),
12789 against(&dc, &all),
12790 encoded.modes.len(),
12791 );
12792 }
12793 }
12794
12795 /// A picture whose stripes run along a diagonal, one way or the other.
12796 /// This is to the directional modes what [`stripes`] is to the vertical and
12797 /// horizontal pair: a predictor that walked the edge in the wrong direction
12798 /// would answer the two pictures the same way round.
12799 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
12800 let mut picture = Picture::grey(width, height);
12801 for y in 0..height {
12802 for x in 0..width {
12803 let along = if down_right { x + height - y } else { x + y };
12804 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
12805 }
12806 }
12807 picture
12808 }
12809
12810 /// The mode picked by the most blocks of a picture, ignoring the first
12811 /// block, which has no neighbours to tell the modes apart with.
12812 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
12813 // A mode ablation measures the MODE search: the palette would code
12814 // these synthetic two-colour pictures losslessly under every arm and
12815 // leave nothing to compare (see [`force_screen`]).
12816 force_screen(Some(false));
12817 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
12818 let blocks = &encoded.modes[1..];
12819 let mut counts = [0usize; 13];
12820 for &mode in blocks {
12821 counts[usize::from(mode)] += 1;
12822 }
12823 let (mode, count) = counts
12824 .iter()
12825 .enumerate()
12826 .max_by_key(|&(_, count)| *count)
12827 .expect("thirteen modes");
12828 (mode as u8, *count, blocks.len())
12829 }
12830
12831 /// The search has to follow a diagonal the way it runs: stripes down and to
12832 /// the right are cheapest predicted at 135 degrees, stripes down and to the
12833 /// left at 45. A walk that stepped the wrong way along the edge, or read
12834 /// the above row where it should read the left column, would swap these.
12835 #[test]
12836 fn the_search_picks_the_diagonal_the_picture_runs() {
12837 let _knobs = crate::speed::knob_write();
12838 let fctx = &crate::decode::FrameCtx::new();
12839 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
12840 let picture = diagonal(160, 96, down_right);
12841 let (mode, count, blocks) = favourite_mode(&picture, fctx);
12842 assert_eq!(
12843 mode, want,
12844 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
12845 );
12846 }
12847 }
12848
12849 /// What the directional modes are for: a picture that runs along a diagonal
12850 /// costs far less to code with them than the seven that read only their own
12851 /// edges can manage, and a picture that runs no particular way costs no
12852 /// more. The second half is the one that bites: a mode set the search
12853 /// cannot price is a mode set that loses rate on content that does not want
12854 /// it, which is what costing the mode symbol is for.
12855 #[test]
12856 fn the_diagonals_beat_the_modes_that_read_no_further() {
12857 let _knobs = crate::speed::knob_read();
12858 let fctx = &crate::decode::FrameCtx::new();
12859 for (name, picture, want) in [
12860 ("down-right", diagonal(160, 96, true), -0.20),
12861 ("down-left", diagonal(160, 96, false), -0.20),
12862 ("test card", test_card(160, 96), 0.01),
12863 ] {
12864 let saved = bd_rate(
12865 &ladder(&picture, &NON_DIRECTIONAL, fctx),
12866 &ladder(&picture, &KEY_FRAME_MODES, fctx),
12867 );
12868 assert!(
12869 saved < want,
12870 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
12871 saved * 100.0,
12872 -want * 100.0
12873 );
12874 }
12875 }
12876
12877 /// A mode the encoder cannot predict must be refused rather than coded as
12878 /// something else, and a search with nothing to choose from likewise.
12879 #[test]
12880 fn a_mode_the_encoder_cannot_predict_is_refused() {
12881 let _knobs = crate::speed::knob_read();
12882 let fctx = &crate::decode::FrameCtx::new();
12883 let picture = test_card(64, 64);
12884 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
12885 .unwrap_err()
12886 .to_string();
12887 assert!(
12888 message.contains("intra mode 13"),
12889 "the refusal must name the mode, got {message}"
12890 );
12891 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
12892 }
12893
12894 /// The picture that comes back is the picture that went in, to within the
12895 /// quantizer. A prediction that read the wrong neighbours, or a block
12896 /// written into the wrong place, would still decode to what the encoder
12897 /// reconstructed — it is this gate that says the reconstruction is of the
12898 /// right picture.
12899 #[test]
12900 fn the_encoded_picture_is_the_one_that_went_in() {
12901 let _knobs = crate::speed::knob_read();
12902 let fctx = &crate::decode::FrameCtx::new();
12903 let picture = test_card(160, 96);
12904 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
12905 let luma = psnr(&encoded.reconstruction.y, &picture.y);
12906 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
12907 for (plane, (got, want)) in [
12908 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
12909 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
12910 ]
12911 .iter()
12912 .enumerate()
12913 {
12914 let chroma = psnr(got, want);
12915 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
12916 }
12917 }
12918
12919 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
12920 /// does the opposite. Both are monotone, which is what a rate-distortion
12921 /// loop above this will assume.
12922 #[test]
12923 fn fidelity_and_rate_move_with_the_quantizer() {
12924 let _knobs = crate::speed::knob_read();
12925 let fctx = &crate::decode::FrameCtx::new();
12926 let picture = test_card(128, 128);
12927 let mut previous: Option<(usize, f64)> = None;
12928 for &q in &[70u8, 90, 110] {
12929 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
12930 let quality = psnr(&encoded.reconstruction.y, &picture.y);
12931 if let Some((bytes, better)) = previous {
12932 assert!(
12933 encoded.stream.len() < bytes,
12934 "q {q}: {} bytes",
12935 encoded.stream.len()
12936 );
12937 assert!(quality < better, "q {q}: PSNR {quality}");
12938 }
12939 previous = Some((encoded.stream.len(), quality));
12940 }
12941
12942 // The deadzone half of this claim lives in
12943 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
12944 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
12945 // every zeroing, the deadzone no longer moves a coded stream
12946 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
12947 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
12948 // job, not a quantiser defect.
12949
12950 // Bytes must not jump up across a q-context boundary: a wrong CDF
12951 // table for the far side would show up as a rate discontinuity here,
12952 // even though a coarser quantizer always codes no more than a finer
12953 // one on the same picture.
12954 //
12955 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
12956 // chroma searches its own mode, a coarser quantizer can pick a
12957 // *different* uv_mode on a block whose modes now cost nearly the
12958 // same, and the search prices that symbol against the static default
12959 // CDF while the writer codes it against an adapted one -- 311 -> 319
12960 // bytes at q 120->121 on this picture. The table this gate is really
12961 // watching would move the rate by far more than the mode churn does.
12962 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
12963 // same block can also change transform DEPTH between two neighbouring
12964 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
12965 // symbol is priced off the static CDF row 0 for the same reason the
12966 // uv_mode one is.
12967 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
12968 // path is pricing through the adapting CDF state (what
12969 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
12970 // drift of), after which the exact bound comes back.
12971 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
12972 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
12973 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
12974 assert!(
12975 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
12976 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
12977 );
12978 }
12979 }
12980
12981 /// A flat picture is a flat stream: every block predicts its neighbours'
12982 /// average, which is the picture's own value, and codes nothing.
12983 #[test]
12984 fn a_flat_picture_costs_almost_nothing() {
12985 let _knobs = crate::speed::knob_read();
12986 let fctx = &crate::decode::FrameCtx::new();
12987 let mut picture = Picture::grey(128, 128);
12988 picture.y.fill(97);
12989 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
12990 // The first block has no neighbour and predicts 128, so it carries a
12991 // DC; every block after it predicts 97 and carries nothing.
12992 assert!(
12993 encoded.stream.len() < 100,
12994 "{} bytes for a flat picture",
12995 encoded.stream.len()
12996 );
12997 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
12998 assert_eq!(s, 97, "sample {i} of a flat picture");
12999 }
13000 }
13001
13002 /// The sizes the encoder refuses, refused for a reason rather than by
13003 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
13004 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
13005 /// lands past the halfway point of whichever block it falls in, so
13006 /// `PARTITION_NONE` or a single gathered split flag still says everything
13007 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
13008 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
13009 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
13010 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
13011 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
13012 /// refusal here claimed otherwise and was wrong; see
13013 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
13014 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
13015 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
13016 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
13017 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
13018 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
13019 /// still refused is a malformed picture.
13020 #[test]
13021 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
13022 let _knobs = crate::speed::knob_read();
13023 let fctx = &crate::decode::FrameCtx::new();
13024 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
13025 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
13026 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
13027 .expect("36 luma columns still round up to an even MiCols");
13028
13029 let mut short = Picture::grey(64, 64);
13030 short.u.truncate(10);
13031 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
13032 }
13033
13034 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
13035 /// column half only (`has_half` false on cols, true on rows) -- exactly
13036 /// the single-axis straddle lane-av1-rect r7 wires through
13037 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
13038 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
13039 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
13040 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
13041 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
13042 /// `partition_context_lookup` entry this writer ever produces (no 4x4
13043 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
13044 /// leaf regardless of neighbour state -- our writer already agreed with
13045 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
13046 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
13047 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
13048 /// it does not regress the gate. r11 tell-for-tell traced two further,
13049 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
13050 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
13051 /// leaves, when the second leaf's true above (or left) neighbour is the
13052 /// first leaf itself -- fixed by threading the first leaf's mode into the
13053 /// second leaf's context, mi-precise, like `record_mi` already does for
13054 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
13055 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
13056 /// `reduced_tx_set` is false), but this crate's key frames set
13057 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
13058 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
13059 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
13060 /// symbol bits to desync everything after it. Fixed with a new
13061 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
13062 /// eset/size slot). Both fixes are provably correct against libaom
13063 /// source and each closed part of the gap (leaf0's `eob` went from a
13064 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
13065 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
13066 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
13067 /// (do not reuse r11's committed logs, which predate its own fixes) and
13068 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
13069 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
13070 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
13071 /// every other `write_block` caller at 16x16 and up already passes
13072 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
13073 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
13074 /// different amount of arithmetic range and derailed everything after
13075 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
13076 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
13077 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
13078 /// never updating those coarse arrays itself -- so a *second* straddling
13079 /// 16x16 quadrant stacked above or left of the first (never covered by
13080 /// r11's same-call `prev_leaf` override, which only threads state
13081 /// between the two leaves of one shared quadrant) read whatever stale
13082 /// mode sat in that slot before either leaf ran. Fixed by writing the
13083 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
13084 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
13085 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
13086 /// offset of a single unit; fixing (3)+(4) together still leaves a
13087 /// residual divergence one leaf further in -- the decoder now reads
13088 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
13089 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
13090 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
13091 /// desyncs the stream by exactly the width of one earlier symbol -- not
13092 /// yet isolated to a single named symbol. r15 found the last bug: the
13093 /// header fix from r14 explained the rng skew fully, and the remaining
13094 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
13095 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
13096 /// loop, once per leaf, so the first leaf's write clobbered the true
13097 /// external neighbour mode the second leaf of the *same* straddling
13098 /// quadrant still needed for its non-adjacency axis (a column-straddle
13099 /// case: two leaves share one `outer_at` column index, so leaf 1's
13100 /// write to `left_mode[r]` overwrote the real western neighbour before
13101 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
13102 /// doing it once, after the whole leaf loop, from the last (bottom/
13103 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
13104 #[test]
13105 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
13106 let _knobs = crate::speed::knob_read();
13107 let fctx = &crate::decode::FrameCtx::new();
13108 if !have_ffmpeg() {
13109 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
13110 return;
13111 }
13112 let (width, height) = (40usize, 32usize);
13113 let picture = test_card(width, height);
13114 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13115 assert_eq!(
13116 (encoded.reconstruction.width, encoded.reconstruction.height),
13117 (width, height)
13118 );
13119 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
13120 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
13121 }
13122 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13123 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
13124 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
13125 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
13126 }
13127
13128 /// A frame of real video, rather than a picture built to be easy.
13129 ///
13130 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
13131 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
13132 /// encoder's reconstruction has to survive the same equality gate as the
13133 /// synthetic pictures — real video reaches contexts a test card does not.
13134 #[test]
13135 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
13136 let _knobs = crate::speed::knob_read();
13137 let fctx = &crate::decode::FrameCtx::new();
13138 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
13139 eprintln!(
13140 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
13141 set EC_AV1_CLIP to a clip"
13142 );
13143 return;
13144 };
13145 if !have_ffmpeg() {
13146 eprintln!(
13147 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
13148 );
13149 return;
13150 }
13151 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
13152 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
13153 // test quick while still spanning many superblocks.
13154 let (width, height) = (640usize, 352usize);
13155 let picture = clip_frame(&clip, &skip, width, height);
13156
13157 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13158 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13159 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
13160 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
13161 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
13162 eprintln!(
13163 "{} bytes, luma PSNR {:.2} dB",
13164 encoded.stream.len(),
13165 psnr(&decoded.y, &picture.y)
13166 );
13167 }
13168
13169 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
13170 /// sequence of these is a translation a motion search can actually find
13171 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
13172 /// inter frame's rate against the key frame's is measuring the same
13173 /// picture moving, not two different pictures.
13174 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
13175 let mut picture = Picture::grey(width, height);
13176 for y in 0..height {
13177 for x in 0..width {
13178 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
13179 let gradient = sx * 200.0 / width as f64;
13180 let ripple = 30.0
13181 * (sx * std::f64::consts::PI / 23.0).sin()
13182 * (y as f64 * std::f64::consts::PI / 37.0).cos();
13183 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
13184 40.0
13185 } else {
13186 0.0
13187 };
13188 picture.y[y * width + x] =
13189 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
13190 }
13191 }
13192 for y in 0..height / 2 {
13193 for x in 0..width / 2 {
13194 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
13195 let i = y * width / 2 + x;
13196 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
13197 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
13198 }
13199 }
13200 picture
13201 }
13202
13203 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
13204 fn ffmpeg_decode_sequence(
13205 stream: &[u8],
13206 width: usize,
13207 height: usize,
13208 frames: usize,
13209 ) -> Vec<Picture> {
13210 let mut child = Command::new("ffmpeg")
13211 .args([
13212 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
13213 ])
13214 .stdin(Stdio::piped())
13215 .stdout(Stdio::piped())
13216 .stderr(Stdio::piped())
13217 .spawn()
13218 .expect("ffmpeg failed to start");
13219 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
13220 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
13221 // fills before the last input byte is written -- which is exactly what
13222 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
13223 // (measured: 45 min, both processes at 0% CPU). A write error here is
13224 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
13225 // below, are the real diagnosis.
13226 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
13227 let payload = stream.to_vec();
13228 let writer = std::thread::spawn(move || {
13229 let _ = stdin.write_all(&payload);
13230 });
13231 let out = child.wait_with_output().expect("ffmpeg failed to run");
13232 writer.join().expect("ffmpeg stdin writer thread");
13233 assert!(
13234 out.status.success(),
13235 "ffmpeg refused the stream: {}",
13236 String::from_utf8_lossy(&out.stderr)
13237 );
13238 let (luma, chroma) = (width * height, width * height / 4);
13239 let frame_bytes = luma + 2 * chroma;
13240 assert_eq!(
13241 out.stdout.len(),
13242 frame_bytes * frames,
13243 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
13244 String::from_utf8_lossy(&out.stderr)
13245 );
13246 (0..frames)
13247 .map(|i| {
13248 let base = i * frame_bytes;
13249 Picture {
13250 width,
13251 height,
13252 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
13253 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
13254 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
13255 }
13256 })
13257 .collect()
13258 }
13259
13260 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
13261 /// makes for a key frame, extended down the reference chain: each inter
13262 /// frame's reconstruction predicts from the previous frame's own decoded
13263 /// reconstruction, so a single sample of drift anywhere would propagate
13264 /// into every frame after it -- which is why every frame is checked, not
13265 /// just the last one, and why this is an equality and not a tolerance.
13266 #[test]
13267 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
13268 let _knobs = crate::speed::knob_read();
13269 let fctx = &crate::decode::FrameCtx::new();
13270 if !have_ffmpeg() {
13271 eprintln!(
13272 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
13273 );
13274 return;
13275 }
13276 let (width, height) = (128usize, 64usize);
13277 let pictures: Vec<Picture> = (0..5)
13278 .map(|i| panned_test_card(width, height, i * 3))
13279 .collect();
13280 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
13281 assert_eq!(encoded.frames.len(), 5);
13282
13283 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
13284 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
13285 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
13286 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
13287 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
13288 }
13289
13290 eprintln!("frame bytes luma PSNR (dB) inter share");
13291 for (i, frame) in encoded.frames.iter().enumerate() {
13292 eprintln!(
13293 "{i:5} {:5} {:14.2} {:11.2}",
13294 frame.stream.len(),
13295 psnr(&frame.reconstruction.y, &pictures[i].y),
13296 frame.inter_block_share
13297 );
13298 }
13299 }
13300
13301 /// The same sequence through OUR OWN decoder, sample-exact against the
13302 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
13303 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
13304 /// divergence point at all, while our decoder can be traced symbol by
13305 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
13306 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
13307 /// names the first differing frame, plane and position.
13308 #[test]
13309 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
13310 let _knobs = crate::speed::knob_read();
13311 let fctx = &crate::decode::FrameCtx::new();
13312 // 256x128, not the 128x64 this started at: once a leaf could search
13313 // its second reference (lane-av1comp4) the small card's every
13314 // eligible block went to a compound winner, which commits its flat
13315 // transform, and the split below stopped firing on content that
13316 // still splits at every larger size ([[gate-blind-to-feature]] --
13317 // the guard is right, the fixture had shrunk under it).
13318 let (width, height) = (256usize, 128usize);
13319 let pictures: Vec<Picture> =
13320 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
13321 let _ = take_inter_tx_split_hits();
13322 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
13323 let raw = take_inter_tx_split_hits();
13324 // Summed over the four block classes the census keys on (leaf/32x32 x
13325 // single/compound): this assert is about the split firing at all.
13326 let split = [
13327 raw.iter().step_by(2).sum::<usize>(),
13328 raw.iter().skip(1).step_by(2).sum::<usize>(),
13329 ];
13330 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
13331 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
13332 // content splits -- a green round trip in which the split never fires
13333 // would prove only the flat path.
13334 if tx_select() && tx_select_inter() {
13335 assert!(split[1] > 0, "the inter var-tx split never fired");
13336 }
13337 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
13338 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
13339 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
13340 let recon = &frame.reconstruction;
13341 for (plane, got, want, stride) in [
13342 ("luma", &dec.y, &recon.y, width),
13343 ("U", &dec.u, &recon.u, width / 2),
13344 ("V", &dec.v, &recon.v, width / 2),
13345 ] {
13346 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
13347 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
13348 panic!(
13349 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
13350 reconstruction {} ({} of {} samples differ)",
13351 at % stride,
13352 at / stride,
13353 got[at],
13354 want[at],
13355 got.iter().zip(want).filter(|(a, b)| a != b).count(),
13356 got.len(),
13357 );
13358 }
13359 }
13360 }
13361 }
13362
13363 /// The rate term the mode search ranks every decision by has to be the
13364 /// rate the writer then spends. The search prices a block's coefficients
13365 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
13366 /// against the default CDFs a tile starts from and the contexts of a
13367 /// block whose neighbours coded nothing -- while the tile writer codes
13368 /// them against a state that has been adapting all frame (the
13369 /// price-the-narrowing class). This measures that drift: the sum of what
13370 /// the search paid for the coefficients it kept, against the bytes the
13371 /// writer actually emitted for the whole tile (which also carries the
13372 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
13373 /// expected to be the larger of the two).
13374 #[test]
13375 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
13376 let _knobs = crate::speed::knob_read();
13377 let fctx = &crate::decode::FrameCtx::new();
13378 let (width, height) = (256usize, 128usize);
13379 let pictures: Vec<Picture> = (0..5)
13380 .map(|i| panned_test_card(width, height, i * 2))
13381 .collect();
13382 let _ = take_predicted_bits();
13383 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
13384 let predicted = take_predicted_bits();
13385 assert_eq!(predicted.len(), encoded.frames.len());
13386
13387 eprintln!("frame predicted bits written bits drift");
13388 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
13389 // defect this gate exists to catch), a positive one is the written
13390 // side carrying syntax the coefficient sum leaves out -- and since
13391 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
13392 // on that side, so the two directions no longer share a bound.
13393 let mut worst_over: f64 = 0.0;
13394 let mut worst_under: f64 = 0.0;
13395 // The census is per CODED frame, so it is zipped in coding order --
13396 // which is not display order under a pyramid.
13397 let coded: Vec<&Encoded> =
13398 encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect();
13399 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
13400 let written = frame.tile.len() as f64 * 8.0;
13401 let drift = (written - bits) / written;
13402 worst_over = worst_over.max(-drift);
13403 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
13404 // all (150-250 bits of tile, nearly all of it partition/mode/mv
13405 // syntax the coefficient sum never counts), so its ratio measures
13406 // that floor rather than any drift. Frames under 512 written bits
13407 // are left out of the under-price bound for that reason; the
13408 // over-price bound -- the defect direction, where the search pays
13409 // MORE than the writer -- still covers every frame.
13410 if written >= 512.0 {
13411 worst_under = worst_under.max(drift);
13412 }
13413 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
13414 }
13415 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
13416 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
13417 // over-prices every frame but the last (its sum EXCLUDES the
13418 // partition/mode/skip/mv syntax the written side carries, so the true
13419 // coefficient over-price is larger still): the writer's CDFs adapt to
13420 // the content while the search's stay at the defaults. The bound is
13421 // set just above the worst measured point -- a widening drift is the
13422 // thing this gate exists to catch.
13423 assert!(
13424 worst_over <= 0.16,
13425 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
13426 worst_over * 100.0
13427 );
13428 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
13429 // the worst inter frame, where nearly every block now codes an MV
13430 // residual and a reference the coefficient sum never counts. Re-measured
13431 // at +29.6% once the encoder's grid published compound blocks properly
13432 // (compound share 8.8% -> 11.5%): a compound block carries a second
13433 // reference tree, a compound mode symbol and -- for the half-new modes
13434 // -- an MV residual, none of which the coefficient sum counts.
13435 // lane-av1txbits: pricing against the tables the frame's writer really
13436 // starts from collapses the over-price above to nothing, so the whole
13437 // remaining gap is the syntax the coefficient sum leaves out. That is
13438 // the default on a non-screen frame since lane-av1price2 (this
13439 // fixture is one), and it reads +32.6% here.
13440 // lane-av1obmc: every eligible single-reference inter block now also
13441 // carries a `motion_mode` symbol the coefficient sum never counts,
13442 // and an OBMC block carries the more expensive of the two values --
13443 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
13444 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
13445 // decisions, so this bound and the byte pins above FAIL BY DESIGN
13446 // under it; the default path (no motion_mode syntax at all) is the
13447 // one they are measured on.
13448 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
13449 // coding pyramid now, so the five frames are a key frame, a hidden
13450 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
13451 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
13452 // near-empty leaves below it. Both bounds stand where they were.
13453 // lane-av1rejudge: local warp is ON by default now, so every eligible
13454 // single-reference block carries that same `motion_mode` symbol (a
13455 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
13456 // +34.9% here, one point past the OBMC reading above. The bound moves
13457 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
13458 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
13459 // symbol and one or two magnitude symbols, none of which the
13460 // coefficient sum counts either -- +36.9% here against the same
13461 // fixture's +34.9% with `EC_AV1_CFL=0`.
13462 // ... and a directional block whose `angle_delta_y` is no longer
13463 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
13464 assert!(
13465 worst_under <= 0.40,
13466 "the writer spent {:.2}% more than the search priced -- more than \
13467 the mode/mv syntax outside the coefficient sum explains",
13468 worst_under * 100.0
13469 );
13470 }
13471
13472 /// The census behind step (1) of the pricer lane: for every transform
13473 /// block the writer really codes, what the search priced those levels at
13474 /// against what the writer spent on them, split by table set and non-zero
13475 /// count. One average hides the interesting part -- the classes the
13476 /// estimate is systematically wrong about (all-zero blocks, the
13477 /// one-coefficient blocks the inter search lives on) -- so the split is
13478 /// printed and only the total is asserted on.
13479 #[test]
13480 fn pricer_error_census_by_block_class() {
13481 let _knobs = crate::speed::knob_read();
13482 let fctx = &crate::decode::FrameCtx::new();
13483 let (width, height) = (256usize, 128usize);
13484 let pictures: Vec<Picture> = (0..5)
13485 .map(|i| panned_test_card(width, height, i * 2))
13486 .collect();
13487 crate::tile::pricer_census_on();
13488 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
13489 let rows = crate::tile::take_pricer_census();
13490 assert!(!rows.is_empty(), "the census saw no transform block");
13491
13492 println!("| set | nz | blocks | priced bits | written bits | error |");
13493 println!("|---|---|---|---|---|---|");
13494 let (mut priced_all, mut written_all) = (0.0, 0.0);
13495 for ((set, bucket), (blocks, priced, written)) in &rows {
13496 priced_all += priced;
13497 written_all += written;
13498 println!(
13499 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
13500 crate::tile::census_bucket_label(*bucket),
13501 if *written > 0.0 {
13502 (priced - written) / written * 100.0
13503 } else {
13504 0.0
13505 }
13506 );
13507 }
13508 println!(
13509 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
13510 rows.values().map(|r| r.0).sum::<u64>(),
13511 (priced_all - written_all) / written_all * 100.0
13512 );
13513 assert!(written_all > 0.0);
13514 }
13515
13516 /// Step (2) of the pricer lane: the same census, but on the REAL clips
13517 /// the BD gate scores -- one film clip and the screen capture -- so the
13518 /// question the film/screen split raises can be answered from data. Real
13519 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
13520 /// the screen capture larger, and the census says why: on a screen
13521 /// capture the frame's own starting tables are the tables of a frame that
13522 /// coded PALETTE and long runs of zero blocks, so they are far from the
13523 /// tables the writer ends the frame with; the pricer error does not fall
13524 /// the way it does on film.
13525 ///
13526 /// Not a gate -- it prints. Run it once per mode:
13527 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
13528 /// --ignored pricer_error_census_on_clips --nocapture
13529 #[test]
13530 #[ignore = "reads the real library, needs ffmpeg"]
13531 fn pricer_error_census_on_clips() {
13532 let _knobs = crate::speed::knob_write();
13533 if !have_ffmpeg() {
13534 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
13535 return;
13536 }
13537 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
13538 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
13539 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
13540 if film.exists() {
13541 clips.push(("film 1080p".to_string(), film));
13542 }
13543 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
13544 && let Some(p) = manifest
13545 .lines()
13546 .skip(1)
13547 .filter_map(|l| l.split('\t').next())
13548 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
13549 {
13550 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
13551 }
13552 assert!(!clips.is_empty(), "no source clip available");
13553 let (width, height, frames) = (640usize, 384usize, 6usize);
13554 for (name, path) in &clips {
13555 let fctx = &crate::decode::FrameCtx::new();
13556 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
13557 SCREEN_FRAMES.iter().for_each(|c| {
13558 c.store(0, std::sync::atomic::Ordering::Relaxed);
13559 });
13560 let _ = crate::tile::take_pricing_hits();
13561 crate::tile::pricer_census_on();
13562 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
13563 let rows = crate::tile::take_pricer_census();
13564 let (price_default, price_real) = crate::tile::take_pricing_hits();
13565 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
13566 println!(
13567 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
13568 {screen_on}, pricer armings default={price_default} real={price_real}"
13569 );
13570 println!("| set | nz | blocks | priced bits | written bits | error |");
13571 println!("|---|---|---|---|---|---|");
13572 let (mut priced_all, mut written_all) = (0.0, 0.0);
13573 for ((set, bucket), (blocks, priced, written)) in &rows {
13574 priced_all += priced;
13575 written_all += written;
13576 println!(
13577 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
13578 crate::tile::census_bucket_label(*bucket),
13579 if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
13580 );
13581 }
13582 println!(
13583 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
13584 rows.values().map(|r| r.0).sum::<u64>(),
13585 (priced_all - written_all) / written_all * 100.0
13586 );
13587 assert!(written_all > 0.0, "{name}: the census saw no transform block");
13588 }
13589 }
13590
13591 /// Low motion has to actually buy something: at least one inter frame of
13592 /// a panning sequence has to cost fewer bytes than the key frame that
13593 /// starts it, and the inter-block share it prints has to be non-zero --
13594 /// a search that never picks an inter mode would still pass a rate gate
13595 /// on a picture with no motion in it (the class this repo calls
13596 /// gate-blind-to-feature), so the share is printed even though it is not
13597 /// asserted on beyond being reachable at all.
13598 #[test]
13599 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
13600 let _knobs = crate::speed::knob_read();
13601 let fctx = &crate::decode::FrameCtx::new();
13602 let (width, height) = (256usize, 128usize);
13603 let pictures: Vec<Picture> = (0..5)
13604 .map(|i| panned_test_card(width, height, i * 2))
13605 .collect();
13606 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
13607
13608 let key_bytes = encoded.frames[0].stream.len();
13609 eprintln!("frame bytes inter share");
13610 for (i, frame) in encoded.frames.iter().enumerate() {
13611 eprintln!(
13612 "{i:5} {:5} {:11.2}",
13613 frame.stream.len(),
13614 frame.inter_block_share
13615 );
13616 }
13617 assert!(
13618 encoded.frames[1..]
13619 .iter()
13620 .any(|f| f.stream.len() < key_bytes),
13621 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
13622 );
13623 assert!(
13624 encoded.frames[1..]
13625 .iter()
13626 .any(|f| f.inter_block_share > 0.0),
13627 "no inter frame coded a single inter block -- the search never fired"
13628 );
13629 }
13630
13631 /// A manual perf probe, not a gate: prints where a key frame's and an
13632 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
13633 /// measures before it optimizes rather than guessing. Run with
13634 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
13635 #[test]
13636 #[ignore = "a perf probe, not a gate"]
13637 fn stage_timing_breakdown() {
13638 let _knobs = crate::speed::knob_read();
13639 let fctx = &crate::decode::FrameCtx::new();
13640 use std::time::Instant;
13641
13642 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
13643 let picture = test_card(width, height);
13644
13645 let t = Instant::now();
13646 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
13647 let dc_only_t = t.elapsed();
13648
13649 let t = Instant::now();
13650 let non_directional =
13651 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
13652 let non_directional_t = t.elapsed();
13653
13654 let t = Instant::now();
13655 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13656 let all_modes_t = t.elapsed();
13657
13658 eprintln!(
13659 "\n=== key frame {width}x{height} ===\n\
13660 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
13661 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
13662 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
13663 dc_only.stream.len(),
13664 non_directional.stream.len(),
13665 all_modes.stream.len(),
13666 );
13667
13668 // One inter frame predicting off the key frame's own
13669 // reconstruction, the (256, 256)-padded surface encode_sequence
13670 // itself would hand encode_inter_frame.
13671 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
13672 let padded_pic = picture.padded_to(SUPERBLOCK);
13673 let t = Instant::now();
13674 let inter =
13675 encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, &[]).unwrap();
13676 let inter_t = t.elapsed();
13677 eprintln!(
13678 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
13679 {:.2})",
13680 inter.stream.len(),
13681 inter.inter_block_share
13682 );
13683 }
13684
13685 // Isolated per-call cost of the trial pipeline's own stages, at both
13686 // transform sizes the search runs, averaged over enough calls to
13687 // rise above `Instant::now`'s own noise.
13688 for side in [16usize, 32] {
13689 const N: u32 = 20_000;
13690 let residual: Vec<i32> = (0..side * side)
13691 .map(|i| ((i * 37 % 61) as i32) - 30)
13692 .collect();
13693
13694 let t = Instant::now();
13695 let mut levels = Vec::new();
13696 for _ in 0..N {
13697 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
13698 }
13699 let forward_t = t.elapsed() / N;
13700
13701 let t = Instant::now();
13702 for _ in 0..N {
13703 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
13704 }
13705 let inverse_t = t.elapsed() / N;
13706
13707 let set = if side == 32 {
13708 crate::cdf_state::TxbSet::Luma32
13709 } else {
13710 crate::cdf_state::TxbSet::Luma16
13711 };
13712 let t = Instant::now();
13713 for _ in 0..N {
13714 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
13715 }
13716 let entropy_t = t.elapsed() / N;
13717
13718 let above = vec![128u8; side * 2];
13719 let left = vec![128u8; side * 2];
13720 let mut prediction = vec![0u8; side * side];
13721 let t = Instant::now();
13722 for _ in 0..N {
13723 intra_predict_u8(
13724 D45_PRED,
13725 0,
13726 Some(&above),
13727 Some(&left),
13728 Some(128),
13729 side,
13730 side,
13731 false,
13732 false,
13733 &mut prediction, fctx,
13734 );
13735 }
13736 let predict_t = t.elapsed() / N;
13737
13738 eprintln!(
13739 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
13740 predict (1 directional mode): {predict_t:>9.2?}\n\
13741 forward_and_quantize: {forward_t:>9.2?}\n\
13742 dequant_and_inverse: {inverse_t:>9.2?}\n\
13743 coeff_bits: {entropy_t:>9.2?}"
13744 );
13745 }
13746 }
13747
13748 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
13749 /// (motion search, [`crate::mc::predict`], transform+quantize,
13750 /// `coeff_bits`), plus what is left over once those are subtracted --
13751 /// the thirteen-mode intra-candidate loop `search_inter_block` still
13752 /// runs on every inter block (its own transform/quant/entropy calls are
13753 /// already inside buckets 2/3, so "left over" here is everything NOT
13754 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
13755 /// symbol-cost lookups outside `coeff_bits`).
13756 ///
13757 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
13758 #[test]
13759 #[ignore = "a perf probe, not a gate"]
13760 fn stage_timing_breakdown_inter() {
13761 let _knobs = crate::speed::knob_read();
13762 let fctx = &crate::decode::FrameCtx::new();
13763 use std::time::Instant;
13764
13765 let (width, height) = (1280usize, 720);
13766 let picture = test_card(width, height);
13767 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13768 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
13769 let padded_pic = picture.padded_to(SUPERBLOCK);
13770
13771 stage_reset();
13772 let t = Instant::now();
13773 let inter =
13774 encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, &[]).unwrap();
13775 let total_t = t.elapsed();
13776 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
13777 let accounted = motion_search + transform_quant + entropy;
13778 // motion_search already contains interpolation's own time (every
13779 // candidate the search costs calls crate::mc::predict), so it is not
13780 // added again here -- interpolation is reported alongside as "of
13781 // which interpolation", not as a fifth additive bucket.
13782 let other = total_t.saturating_sub(accounted);
13783
13784 eprintln!(
13785 "\n=== inter frame {width}x{height}, one frame ===\n\
13786 total: {total_t:>9.2?} ({} bytes)\n\
13787 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
13788 {interpolation:>9.2?})\n\
13789 transform + quantize: {transform_quant:>9.2?}\n\
13790 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
13791 everything else (13-mode intra {other:>9.2?}\n\
13792 candidate loop's own predict/bookkeeping, NEARESTMV's own \
13793 predict, RD glue):",
13794 inter.stream.len(),
13795 );
13796 }
13797
13798 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
13799 /// frames (a dark/flat one, a detailed one, a normal film one) at two
13800 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
13801 /// None`, the baseline this same build produces without
13802 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
13803 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
13804 /// go in the lane report, which is where "ship as default" is decided --
13805 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
13806 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
13807 #[test]
13808 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
13809 fn prune_k_quality_sweep() {
13810 let _knobs = crate::speed::knob_read();
13811 let fctx = &crate::decode::FrameCtx::new();
13812 if !have_ffmpeg() {
13813 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
13814 return;
13815 }
13816 let (width, height) = (640usize, 352usize);
13817 let frames: &[(&str, &str, &str)] = &[
13818 // (label, clip, seek) -- a near-black scene, a busy one, and an
13819 // ordinary film frame, each from a different real file.
13820 (
13821 "dark/flat",
13822 "/home/user/Videos/reela.mp4",
13823 "3",
13824 ),
13825 (
13826 "detailed",
13827 "/home/user/Downloads/reelb.mkv",
13828 "1200",
13829 ),
13830 (
13831 "film",
13832 "/home/user/Videos/Films/reelc.mkv",
13833 "600",
13834 ),
13835 ];
13836 for &(label, clip, skip) in frames {
13837 if !std::path::Path::new(clip).exists() {
13838 eprintln!("SKIP {label}: {clip} not present on this machine");
13839 continue;
13840 }
13841 let picture = clip_frame(clip, skip, width, height);
13842 for &q in &[60u8, 150] {
13843 // SAFETY (not literally unsafe, just process-global): this is
13844 // a single-threaded #[ignore] probe, run by hand, never
13845 // alongside other tests that read Search::top_k.
13846 set_test_top_k_override(None);
13847 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
13848 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
13849 eprint!(
13850 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
13851 baseline.stream.len(),
13852 baseline_psnr
13853 );
13854 for &k in &[3usize, 4, 6] {
13855 set_test_top_k_override(Some(k));
13856 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
13857 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
13858 eprint!(
13859 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
13860 pruned.stream.len(),
13861 pruned_psnr,
13862 pruned_psnr - baseline_psnr
13863 );
13864 }
13865 eprintln!();
13866 }
13867 }
13868 set_test_top_k_override(None);
13869 }
13870
13871 /// Two consecutive decoded frames from one clip, for an inter-frame
13872 /// sweep -- [`clip_frame`] alone only ever gives one.
13873 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
13874 let out = Command::new("ffmpeg")
13875 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
13876 .args(["-vf", &format!("scale={width}:{height}")])
13877 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
13878 .output()
13879 .expect("ffmpeg failed to run");
13880 assert!(
13881 out.status.success(),
13882 "ffmpeg: {}",
13883 String::from_utf8_lossy(&out.stderr)
13884 );
13885 let (luma, chroma) = (width * height, width * height / 4);
13886 let frame_len = luma + 2 * chroma;
13887 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
13888 std::array::from_fn(|i| {
13889 let bytes = &out.stdout[i * frame_len..][..frame_len];
13890 Picture {
13891 width,
13892 height,
13893 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
13894 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
13895 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
13896 }
13897 })
13898 }
13899
13900 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
13901 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
13902 /// then one inter frame off it (`search_inter_block`'s own intra
13903 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
13904 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
13905 /// padding step complicates the comparison. Prints bytes and luma PSNR
13906 /// for the inter frame alone, unpruned vs each `K`.
13907 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
13908 #[test]
13909 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
13910 fn prune_k_quality_sweep_inter() {
13911 let _knobs = crate::speed::knob_read();
13912 let fctx = &crate::decode::FrameCtx::new();
13913 if !have_ffmpeg() {
13914 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
13915 return;
13916 }
13917 let (width, height) = (1280usize, 704usize);
13918 let frames: &[(&str, &str, &str)] = &[
13919 (
13920 "dark/flat",
13921 "/home/user/Videos/reela.mp4",
13922 "3",
13923 ),
13924 (
13925 "detailed",
13926 "/home/user/Downloads/reelb.mkv",
13927 "1200",
13928 ),
13929 (
13930 "film",
13931 "/home/user/Videos/Films/reelc.mkv",
13932 "600",
13933 ),
13934 ];
13935 for &(label, clip, skip) in frames {
13936 if !std::path::Path::new(clip).exists() {
13937 eprintln!("SKIP {label}: {clip} not present on this machine");
13938 continue;
13939 }
13940 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
13941 for &q in &[60u8, 150] {
13942 // SAFETY (not literally unsafe, just process-global): a
13943 // single-threaded #[ignore] probe, run by hand, never
13944 // alongside other tests that read Search::top_k.
13945 set_test_top_k_override_inter(None);
13946 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
13947 let baseline = encode_inter_frame(
13948 &inter_source,
13949 &key.reconstruction,
13950 q,
13951 0.5,
13952 1,
13953 flat_order_hints(1, 0, false),
13954 (width, height), None, None, None, fctx, None, &[],
13955 )
13956 .unwrap();
13957 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
13958 eprint!(
13959 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
13960 baseline.stream.len(),
13961 baseline_psnr
13962 );
13963 for &k in &[3usize, 4, 6] {
13964 set_test_top_k_override_inter(Some(k));
13965 let pruned = encode_inter_frame(
13966 &inter_source,
13967 &key.reconstruction,
13968 q,
13969 0.5,
13970 1,
13971 flat_order_hints(1, 0, false),
13972 (width, height), None, None, None, fctx, None, &[],
13973 )
13974 .unwrap();
13975 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
13976 eprint!(
13977 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
13978 pruned.stream.len(),
13979 pruned_psnr,
13980 pruned_psnr - baseline_psnr
13981 );
13982 }
13983 eprintln!();
13984 }
13985 }
13986 set_test_top_k_override_inter(None);
13987 }
13988
13989 /// `frames` consecutive pictures out of a real clip, scaled to a whole
13990 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
13991 /// to an arbitrary count for the fixture regression gate below.
13992 fn clip_frames(
13993 clip: &str,
13994 skip: &str,
13995 width: usize,
13996 height: usize,
13997 frames: usize,
13998 ) -> Vec<Picture> {
13999 clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames)
14000 }
14001
14002 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
14003 /// for a native-resolution CROP instead of a downscale (the downscale is
14004 /// what destroys a screen capture's exact repeats -- class
14005 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
14006 fn clip_frames_vf(
14007 clip: &str,
14008 skip: &str,
14009 vf: &str,
14010 width: usize,
14011 height: usize,
14012 frames: usize,
14013 ) -> Vec<Picture> {
14014 // ONE definition of the gate's loader recipe, shared with
14015 // `examples/enc_probe` so the instrument cannot arm a different source
14016 // than the gate it reports on (class `instrument disagrees with the
14017 // gate`; lane-probe).
14018 crate::probe::source(clip, skip, vf, width, height, frames)
14019 }
14020
14021 /// The standing regression gate on real content: 12 frames of a real
14022 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
14023 /// this crate's own input regardless of its own source codec), encoded
14024 /// as an AV1 GOP and checked against three numeric floors so a
14025 /// compatibility or quality regression fails the suite instead of
14026 /// waiting for a downstream repo's gate to catch it (as happened for a
14027 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
14028 /// refusal, both caught only that way).
14029 ///
14030 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
14031 /// that geometry is already covered elsewhere), chosen only so encode
14032 /// time and gate numbers are not muddied by an edge-block class this
14033 /// test is not about.
14034 ///
14035 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
14036 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
14037 /// below carry a margin off those measured numbers (PSNR floor =
14038 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
14039 #[test]
14040 fn real_clip_encodes_within_its_quality_and_size_budget() {
14041 let _knobs = crate::speed::knob_read();
14042 let fctx = &crate::decode::FrameCtx::new();
14043 if !have_ffmpeg() {
14044 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
14045 return;
14046 }
14047 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
14048 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
14049 if !clip.exists() {
14050 eprintln!(
14051 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
14052 clip.display()
14053 );
14054 return;
14055 }
14056 let (width, height, frame_count) = (640usize, 384usize, 12usize);
14057 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
14058 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
14059 assert_eq!(encoded.frames.len(), frame_count);
14060
14061 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
14062 // stream and hands back every frame -- a stream a downstream
14063 // decoder refuses is the exact class of regression this gate
14064 // exists for.
14065 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
14066 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
14067
14068 // Gate 2: quality vs the source did not silently collapse.
14069 let mean_psnr: f64 = decoded
14070 .iter()
14071 .zip(&source)
14072 .map(|(d, s)| psnr(&d.y, &s.y))
14073 .sum::<f64>()
14074 / frame_count as f64;
14075 assert!(
14076 mean_psnr >= 44.91,
14077 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
14078 );
14079
14080 // Gate 3: the stream did not silently bloat.
14081 assert!(
14082 encoded.stream.len() <= 80_340,
14083 "stream grew to {} bytes, over the 80340-byte ceiling",
14084 encoded.stream.len()
14085 );
14086 }
14087
14088 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
14089 /// straddle size: 640x384 is exact on both axes (32-aligned), so
14090 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
14091 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
14092 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
14093 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
14094 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
14095 /// card; this one is the real-clip gate, same three floors.
14096 ///
14097 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
14098 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
14099 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
14100 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
14101 #[test]
14102 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
14103 let _knobs = crate::speed::knob_read();
14104 let fctx = &crate::decode::FrameCtx::new();
14105 if !have_ffmpeg() {
14106 eprintln!(
14107 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
14108 no ffmpeg"
14109 );
14110 return;
14111 }
14112 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
14113 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
14114 if !clip.exists() {
14115 eprintln!(
14116 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
14117 {} missing",
14118 clip.display()
14119 );
14120 return;
14121 }
14122 let (width, height, frame_count) = (704usize, 400usize, 8usize);
14123 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
14124 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
14125 assert_eq!(encoded.frames.len(), frame_count);
14126
14127 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
14128 // stream and hands back every frame.
14129 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
14130 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
14131
14132 // Gate 2: quality vs the source did not silently collapse.
14133 let mean_psnr: f64 = decoded
14134 .iter()
14135 .zip(&source)
14136 .map(|(d, s)| psnr(&d.y, &s.y))
14137 .sum::<f64>()
14138 / frame_count as f64;
14139 assert!(
14140 mean_psnr >= 44.98,
14141 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
14142 );
14143
14144 // Gate 3: the stream did not silently bloat.
14145 assert!(
14146 encoded.stream.len() <= 62_703,
14147 "stream grew to {} bytes, over the 62703-byte ceiling",
14148 encoded.stream.len()
14149 );
14150 }
14151
14152 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
14153 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
14154 /// facade -- timed end to end, so the edith export-time projection is a
14155 /// real number rather than a guess from the isolated key/inter numbers
14156 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
14157 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
14158 #[test]
14159 #[ignore = "a perf probe, not a gate"]
14160 fn sequence_bench_sanity() {
14161 let _knobs = crate::speed::knob_read();
14162 let fctx = &crate::decode::FrameCtx::new();
14163 use std::time::Instant;
14164 let (width, height) = (1280usize, 720usize);
14165 let pictures: Vec<Picture> = (0..24)
14166 .map(|i| panned_test_card(width, height, i * 3))
14167 .collect();
14168 let t = Instant::now();
14169 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
14170 let elapsed = t.elapsed();
14171 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
14172 eprintln!(
14173 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
14174 elapsed / 24
14175 );
14176 }
14177
14178 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
14179 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
14180 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
14181 /// -- --ignored --nocapture`.
14182 #[test]
14183 #[ignore = "a calibration probe, not a gate"]
14184 fn calibration_sweep_base_q_idx() {
14185 let _knobs = crate::speed::knob_read();
14186 let fctx = &crate::decode::FrameCtx::new();
14187 if !have_ffmpeg() {
14188 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
14189 return;
14190 }
14191 let (width, height, frames) = (640usize, 384usize, 12usize);
14192 for clip in [
14193 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
14194 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
14195 ] {
14196 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
14197 .join("../../fixtures/video")
14198 .join(clip);
14199 if !path.exists() {
14200 eprintln!("SKIP {clip}: fixture missing");
14201 continue;
14202 }
14203 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
14204 eprintln!("--- {clip} ---");
14205 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
14206 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
14207 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
14208 let mean_psnr: f64 = decoded
14209 .iter()
14210 .zip(&source)
14211 .map(|(d, s)| psnr(&d.y, &s.y))
14212 .sum::<f64>()
14213 / frames as f64;
14214 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
14215 eprintln!(
14216 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
14217 encoded.stream.len()
14218 );
14219 }
14220 }
14221 }
14222
14223 // -----------------------------------------------------------------------
14224 // The encoder's standing BD-rate baseline against libaom and rav1e.
14225 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
14226 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
14227 // agreeing with our encoder proves nothing about the bitstream.
14228 // -----------------------------------------------------------------------
14229
14230 /// All-plane PSNR of a decoded picture against its source, on the same
14231 /// 8-bit scale [`psnr`] uses.
14232 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
14233 let cat = |p: &Picture| {
14234 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
14235 v.extend_from_slice(&p.y);
14236 v.extend_from_slice(&p.u);
14237 v.extend_from_slice(&p.v);
14238 v
14239 };
14240 psnr(&cat(decoded), &cat(source))
14241 }
14242
14243 /// The pictures back as the planar 8-bit bytes an encoder reads.
14244 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
14245 let mut raw = Vec::new();
14246 for p in source {
14247 for plane in [&p.y, &p.u, &p.v] {
14248 raw.extend(plane.iter().map(|&s| s as u8));
14249 }
14250 }
14251 raw
14252 }
14253
14254 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
14255 /// through ffmpeg: one point per entry of `points`, each a quality flag
14256 /// set. Returns the ladder ordered by fidelity and the total encode wall
14257 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
14258 /// so both curves are measured by the same decoder.
14259 fn external_ladder(
14260 source: &[Picture],
14261 width: usize,
14262 height: usize,
14263 encoder: &str,
14264 points: &[Vec<String>],
14265 ) -> (Vec<(f64, f64)>, f64) {
14266 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
14267 let dir = std::env::temp_dir();
14268 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
14269 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
14270 let mut ladder = Vec::new();
14271 let mut wall = 0.0;
14272 for (i, params) in points.iter().enumerate() {
14273 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
14274 let start = std::time::Instant::now();
14275 let out = Command::new("ffmpeg")
14276 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
14277 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
14278 .arg(&raw_path)
14279 .args(["-an", "-threads", "1"])
14280 .args(["-g", &source.len().to_string(), "-c:v", encoder])
14281 .args(params)
14282 .args(["-f", "obu"])
14283 .arg(&obu)
14284 .output()
14285 .expect("ffmpeg failed to run");
14286 wall += start.elapsed().as_secs_f64();
14287 assert!(
14288 out.status.success(),
14289 "{encoder} {params:?}: {}",
14290 String::from_utf8_lossy(&out.stderr)
14291 );
14292 let stream = std::fs::read(&obu).expect("reference stream");
14293 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
14294 // lane-dkey: every reference point must also decode through OUR
14295 // decoder, sample-exact against ffmpeg's decode of the same bytes.
14296 // A BD table computed off streams we cannot read is a table about
14297 // an encoder we cannot check; this is the assertion that would
14298 // have caught the `force_integer_mv` defect (its stream decoded to
14299 // 25 dB garbage while this gate stayed green) and the crf-5 key
14300 // frame desync. A failure names the encoder, the point's flags and
14301 // the first differing frame/plane/sample.
14302 // lane-dpm1: a failing reference point is COLLECTED, not panicked
14303 // on, so one run still prints the whole BD table and names every
14304 // bad point instead of stopping at the first. The collection is
14305 // asserted empty by [`assert_ladder_decodes`] at the end of each
14306 // gate.
14307 match crate::stream::decode_stream(&stream) {
14308 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
14309 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
14310 ours.len(),
14311 decoded.len(),
14312 )),
14313 Ok(ours) => {
14314 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
14315 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
14316 note_ladder_failure(format!(
14317 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
14318 decoder decoded {got}, ffmpeg {want}"
14319 ));
14320 break;
14321 }
14322 }
14323 }
14324 Err(e) => note_ladder_failure(format!(
14325 "{encoder} {params:?}: our decoder refused the stream ({e})"
14326 )),
14327 }
14328 let mean: f64 = decoded
14329 .iter()
14330 .zip(source)
14331 .map(|(d, s)| psnr_all(d, s))
14332 .sum::<f64>()
14333 / source.len() as f64;
14334 ladder.push((mean, (stream.len() as f64).log10()));
14335 let _ = std::fs::remove_file(&obu);
14336 }
14337 let _ = std::fs::remove_file(&raw_path);
14338 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
14339 (ladder, wall)
14340 }
14341
14342 /// Every reference ladder point that did not decode sample-exactly
14343 /// through our own decoder, collected across a whole gate run so the BD
14344 /// table still prints and EVERY bad point is named
14345 /// (`encoder params frame plane sample`) instead of only the first.
14346 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
14347
14348 fn note_ladder_failure(msg: String) {
14349 eprintln!("LADDER DECODE FAILURE: {msg}");
14350 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
14351 }
14352
14353 /// Fail the gate at its END on everything [`external_ladder`] collected.
14354 fn assert_ladder_decodes() {
14355 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
14356 assert!(
14357 failures.is_empty(),
14358 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
14359 failures.len(),
14360 failures.join("\n"),
14361 );
14362 }
14363
14364 /// First differing sample between two pictures, as
14365 /// `(plane, index, left, right)` -- so a gate failure names the plane and
14366 /// the sample instead of just "differs". A length difference counts as a
14367 /// mismatch of that plane at the first index past the shorter one.
14368 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
14369 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
14370 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
14371 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
14372 }
14373 if l.len() != r.len() {
14374 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
14375 }
14376 }
14377 None
14378 }
14379
14380 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
14381 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
14382 /// stream is decoded twice -- by ffmpeg and by our own
14383 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
14384 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
14385 /// in Y, U and V over every shown frame in display order. That is itself
14386 /// a gate: it proves the bitstream says what the encoder thinks, in the
14387 /// only two decoders that read it.
14388 fn our_ladder(
14389 name: &str,
14390 source: &[Picture],
14391 width: usize,
14392 height: usize,
14393 fctx: &crate::decode::FrameCtx,
14394 ) -> (Vec<(f64, f64)>, f64) {
14395 let mut ladder = Vec::new();
14396 let mut wall = 0.0;
14397 for &q in &[150u8, 120, 90, 60] {
14398 let start = std::time::Instant::now();
14399 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
14400 // the gate has to be able to re-sweep it. 0.5 is the shipped one
14401 // (`crate::encoder::DEADZONE`).
14402 let deadzone = std::env::var("EC_AV1_DEADZONE")
14403 .ok()
14404 .and_then(|v| v.parse().ok())
14405 .unwrap_or(0.5);
14406 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
14407 wall += start.elapsed().as_secs_f64();
14408 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
14409 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
14410 assert_eq!(
14411 ours.len(),
14412 source.len(),
14413 "{name} q={q}: our decoder's display-order frame count"
14414 );
14415 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
14416 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
14417 panic!(
14418 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
14419 {got}, the encoder reconstructed {want}"
14420 );
14421 }
14422 }
14423 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
14424 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
14425 panic!(
14426 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
14427 {got}, the encoder reconstructed {want}"
14428 );
14429 }
14430 }
14431 let mean: f64 = decoded
14432 .iter()
14433 .zip(source)
14434 .map(|(d, s)| psnr_all(d, s))
14435 .sum::<f64>()
14436 / source.len() as f64;
14437 ladder.push((mean, (encoded.stream.len() as f64).log10()));
14438 }
14439 // What this clip asked for and what the content gate left it coding
14440 // under: a screen clip requests a pyramid and codes flat, and that
14441 // difference is what keeps its row identical to the flat baseline
14442 // (class `gate-blind-to-feature`).
14443 eprintln!(
14444 "{name}: sequence, pyramid requested {:?} effective {:?}",
14445 crate::encoder::Pyramid::from_env(),
14446 last_sequence_pyramid(),
14447 );
14448 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
14449 (ladder, wall)
14450 }
14451
14452 /// [`our_ladder`] through the streaming facade — the surface the editor's
14453 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
14454 /// each stream is also reordered (hidden `ALTREF` first,
14455 /// `show_existing_frame` last per group) and each level is coded at its
14456 /// own quantizer offset; without one it is the flat ladder, which
14457 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
14458 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
14459 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
14460 /// the whole ladder how many frames and how many bytes it spent, and the
14461 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
14462 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
14463 /// flat path, so a requested pyramid can come back `None` here.
14464 fn our_ladder_facade(
14465 name: &str,
14466 source: &[Picture],
14467 width: usize,
14468 height: usize,
14469 pyramid: Option<crate::encoder::Pyramid>,
14470 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) {
14471 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
14472 let slot = |l: Level| match l {
14473 Level::Key => 0,
14474 Level::Arf => 1,
14475 Level::Leaf => 2,
14476 Level::ShowExisting => 3,
14477 };
14478 let mut ladder = Vec::new();
14479 let mut wall = 0.0;
14480 let mut effective = None;
14481 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
14482 for &q in &[150u8, 120, 90, 60] {
14483 let config = EncoderConfig {
14484 width,
14485 height,
14486 base_q_idx: q,
14487 gop: source.len(),
14488 colour: Colour::Unspecified,
14489 tile_cols_log2: 0,
14490 tile_rows_log2: 0,
14491 };
14492 let start = std::time::Instant::now();
14493 let mut enc = match pyramid {
14494 None => Av1Encoder::new(config).unwrap(),
14495 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
14496 };
14497 let mut packets = Vec::new();
14498 for picture in source {
14499 packets.extend(enc.encode_frames(picture).unwrap());
14500 }
14501 packets.extend(enc.flush().unwrap());
14502 wall += start.elapsed().as_secs_f64();
14503 effective = enc.pyramid();
14504 let mut stream = Vec::new();
14505 for p in &packets {
14506 counts[slot(p.level)] += 1;
14507 bytes[slot(p.level)] += p.data.len();
14508 stream.extend_from_slice(&p.data);
14509 }
14510 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
14511 // correct if the DISPLAY-order output still has one frame per
14512 // source picture, in the right order -- checked against our own
14513 // decoder as well as ffmpeg's, both below.
14514 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
14515 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
14516 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
14517 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
14518 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
14519 panic!(
14520 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
14521 decoded {got}, our decoder decoded {want}"
14522 );
14523 }
14524 }
14525 let mean: f64 = decoded
14526 .iter()
14527 .zip(source)
14528 .map(|(d, s)| psnr_all(d, s))
14529 .sum::<f64>()
14530 / source.len() as f64;
14531 ladder.push((mean, (stream.len() as f64).log10()));
14532 }
14533 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
14534 (ladder, wall, counts, bytes, effective)
14535 }
14536
14537 /// Byte-exactness gate for encoder work that is meant to change only
14538 /// how long the encoder takes.
14539 ///
14540 /// The BD gate above measures quality, which a speed lane can move by a
14541 /// hair without failing anything; this pins the streams themselves.
14542 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
14543 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
14544 /// in the tile) and again on lane-av1mv's merge of it: an extra
14545 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
14546 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
14547 /// prices coefficients against the tables the frame's writer really
14548 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
14549 /// decision change the BD gate judges. Re-pinned again on
14550 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
14551 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
14552 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
14553 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
14554 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
14555 /// by default ([`warp_on`], a sequence/frame header bit and a new
14556 /// motion_mode symbol on eligible blocks) and
14557 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
14558 /// every inter frame's superblocks now code at their own lambda
14559 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
14560 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
14561 /// and the two var-tx depth searches ([`tx32_depth_search`],
14562 /// [`compound_var_tx`]) are on by default, all three re-judged on the
14563 /// native gate's real film rows.
14564 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
14565 /// every block whose chroma takes it codes a different mode symbol, two
14566 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
14567 /// restores the previous streams. Re-pinned again in the same lane once
14568 /// directional luma winners searched their `angle_delta_y`
14569 /// (`EC_AV1_ANGLE=0` restores that half).
14570 #[test]
14571 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
14572 let _knobs = crate::speed::knob_read();
14573 if !have_ffmpeg() {
14574 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
14575 return;
14576 }
14577 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
14578 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
14579 if !clip.exists() {
14580 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
14581 return;
14582 }
14583 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
14584 // FNV-1a over the stream: a witness that every coded bit is where it
14585 // was, which a byte count alone is not.
14586 let fnv = |b: &[u8]| {
14587 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
14588 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
14589 })
14590 };
14591 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
14592 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
14593 // of 4, its leaves at q+8 and a `show_existing_frame` header per
14594 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
14595 // four frames; four pictures is one short mini-GOP, which is the
14596 // shape that pays least (the ARF's own quality has no later group to
14597 // carry it), so this is not the BD gate's number.
14598 // Re-taken again on lane-av1cfl: the chroma search offers
14599 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
14600 // so every block taking either codes different syntax and different
14601 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
14602 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
14603 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
14604 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
14605 // so these four pictures code as one truncated group -- a hidden
14606 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
14607 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
14608 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
14609 // Re-taken on lane-fintra: the sequence header sets
14610 // `enable_filter_intra`, so every DC_PRED intra block of at most
14611 // 32x32 without a luma palette carries a `use_filter_intra` flag and
14612 // the blocks that take one code a filter-intra mode, a different
14613 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
14614 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
14615 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
14616 // (default pyramid `8:-32:16`, one truncated group of 8 with its
14617 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
14618 // root can code a REAL residual now (one TX_64X64 luma transform and
14619 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
14620 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
14621 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
14622 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
14623 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
14624 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
14625 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
14626 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
14627 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
14628 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
14629 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
14630 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
14631 // these four pictures -- offers every superblock a 64x64 intra root
14632 // now. `EC_AV1_I64=0` restores 8557 / 33345.
14633 let pins: [(u8, usize, u64); 2] =
14634 [(150, 8562, 0x66f5_4ffc_aacf_964f), (60, 33357, 0x1d61_9ca4_e960_b044)];
14635 for (q, bytes, hash) in pins {
14636 let encoded = encode_sequence(&source, q, 0.5).unwrap();
14637 assert_eq!(
14638 (encoded.stream.len(), fnv(&encoded.stream)),
14639 (bytes, hash),
14640 "q={q}: the encoder's stream moved"
14641 );
14642 }
14643 }
14644
14645 /// A ladder is only a ladder if both axes rise together.
14646 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
14647 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
14648 for w in ladder.windows(2) {
14649 assert!(
14650 w[1].0 > w[0].0 && w[1].1 > w[0].1,
14651 "{name}: not monotone, {ladder:?}"
14652 );
14653 }
14654 }
14655
14656 /// The sweep behind [`screen_content`]'s constants
14657 /// (`unswept-decision-constants`), on the SAME five clips
14658 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
14659 /// same native crop: for each colour bound N the share of 16x16 luma
14660 /// blocks with 2..=N distinct colours, and the share of those whose
14661 /// per-pixel variance also clears a floor V -- libaom's
14662 /// `av1_set_screen_content_options` counts the variance-cleared blocks
14663 /// too (its `counts_2`, which gates intrabc), and without that term a
14664 /// smooth dark film frame reads as screen content.
14665 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
14666 #[test]
14667 #[ignore = "reads the real library"]
14668 fn probe_screen_detect() {
14669 let _knobs = crate::speed::knob_read();
14670 if !have_ffmpeg() {
14671 eprintln!("SKIP probe_screen_detect: no ffmpeg");
14672 return;
14673 }
14674 let limits = [4usize, 8, 16, 32, 64, 128];
14675 let floors = [0u64, 4, 16, 64, 256];
14676 // The census of one clip at one size: mean share, over the frames, of
14677 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
14678 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
14679 let mut acc = [[0f64; 5]; 6];
14680 for picture in frames {
14681 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
14682 let mut hit = [[0usize; 5]; 6];
14683 let mut blocks = 0usize;
14684 for by in (0..ch).step_by(16) {
14685 for bx in (0..cw).step_by(16) {
14686 let mut seen = [false; 256];
14687 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
14688 for row in 0..16 {
14689 for col in 0..16 {
14690 let v = y[(by + row) * cw + bx + col];
14691 sum += u64::from(v);
14692 sq += u64::from(v) * u64::from(v);
14693 if !seen[usize::from(v)] {
14694 seen[usize::from(v)] = true;
14695 colors += 1;
14696 }
14697 }
14698 }
14699 let var = (sq - sum * sum / 256) / 256;
14700 blocks += 1;
14701 for (li, &limit) in limits.iter().enumerate() {
14702 if colors > 1 && colors <= limit {
14703 for (fi, &floor) in floors.iter().enumerate() {
14704 hit[li][fi] += usize::from(var > floor);
14705 }
14706 }
14707 }
14708 }
14709 }
14710 for li in 0..6 {
14711 for fi in 0..5 {
14712 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
14713 }
14714 }
14715 }
14716 let n = frames.len().max(1) as f64;
14717 eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len());
14718 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>());
14719 for (li, &limit) in limits.iter().enumerate() {
14720 eprintln!(
14721 " {limit:>5} |{}",
14722 (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>()
14723 );
14724 }
14725 };
14726 for (name, path, seek) in native_gate_clips() {
14727 let Some((nw, nh)) = probe_dims(&path) else {
14728 eprintln!("SKIP {name}: ffprobe gave no size");
14729 continue;
14730 };
14731 let cw = nw.min(1920) / 128 * 128;
14732 let ch = nh.min(1024) / 128 * 128;
14733 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
14734 let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12);
14735 census(&name, &frames, cw, ch);
14736 // The 640x384 gate scales instead of cropping, and the scaling
14737 // changes the census (bars smooth out): the constants have to
14738 // separate at BOTH sizes.
14739 let small = clip_frames(&path, &seek, 640, 384, 12);
14740 census(&name, &small, 640, 384);
14741 }
14742 }
14743
14744 /// The detector against the WHOLE real library (class
14745 /// `unswept-decision-constants`, user rule "his data is the gate"):
14746 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
14747 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
14748 /// duration, four frames each, 8-bit 4:2:0, at native size or a
14749 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
14750 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
14751 /// Prints per file and offset the share of qualifying 16x16 blocks, the
14752 /// [`screen_content`] verdict and a content hint (mean luma, luma
14753 /// standard deviation, inter MAD), then sweeps the colour bound against
14754 /// the variance floor over the whole library: for each (N, V) the worst
14755 /// (highest) share among the camera/film rows against the best (lowest)
14756 /// among the screen-recording rows, so the rule with the widest gap can
14757 /// be read off. Rows carry the manifest index, codec and size only --
14758 /// no titles, no home paths.
14759 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
14760 #[test]
14761 #[ignore = "reads the real library"]
14762 fn probe_screen_library() {
14763 let _knobs = crate::speed::knob_read();
14764 if !have_ffmpeg() {
14765 eprintln!("SKIP probe_screen_library: no ffmpeg");
14766 return;
14767 }
14768 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
14769 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
14770 eprintln!("SKIP probe_screen_library: no real-library manifest");
14771 return;
14772 };
14773 let limits = [4usize, 8, 16, 32, 64];
14774 let floors = [0u64, 4, 8, 16, 32, 64, 128];
14775 // Whatever ffmpeg gave us, without the exact-count assertion the
14776 // gate loaders make: a seek near the end of a clip returns fewer
14777 // frames, and that is a row to print, not a panic.
14778 let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
14779 let out = Command::new("ffmpeg")
14780 .args(["-v", "error", "-ss", seek, "-i", clip])
14781 .args(["-frames:v", &n.to_string()])
14782 .args(["-vf", vf])
14783 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
14784 .output();
14785 let Ok(out) = out else { return Vec::new() };
14786 if !out.status.success() {
14787 return Vec::new();
14788 }
14789 let (luma, chroma) = (w * h, w * h / 4);
14790 let frame_len = luma + 2 * chroma;
14791 (0..out.stdout.len() / frame_len)
14792 .map(|i| {
14793 let b = &out.stdout[i * frame_len..][..frame_len];
14794 Picture {
14795 width: w,
14796 height: h,
14797 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
14798 u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
14799 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
14800 }
14801 })
14802 .collect()
14803 };
14804 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
14805 // variance > V, for every (N, V) of the sweep grid, over one frame.
14806 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
14807 let mut hit = [[0usize; 7]; 5];
14808 let mut blocks = 0usize;
14809 for by in (0..h).step_by(16) {
14810 for bx in (0..w).step_by(16) {
14811 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
14812 let mut seen = [false; 256];
14813 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
14814 for row in 0..bh {
14815 for col in 0..bw {
14816 let v = y[(by + row) * w + bx + col];
14817 sum += u64::from(v);
14818 sq += u64::from(v) * u64::from(v);
14819 if !seen[usize::from(v)] {
14820 seen[usize::from(v)] = true;
14821 colors += 1;
14822 }
14823 }
14824 }
14825 let n = (bh * bw) as u64;
14826 let var = (sq - sum * sum / n) / n;
14827 blocks += 1;
14828 for (li, &limit) in limits.iter().enumerate() {
14829 if colors > 1 && colors <= limit {
14830 for (fi, &floor) in floors.iter().enumerate() {
14831 hit[li][fi] += usize::from(var > floor);
14832 }
14833 }
14834 }
14835 }
14836 }
14837 let mut out = [[0f64; 7]; 5];
14838 for li in 0..5 {
14839 for fi in 0..7 {
14840 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
14841 }
14842 }
14843 out
14844 };
14845 // (index, label, path, duration, screen-by-its-own-content). The
14846 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
14847 // are desktop recordings; everything else in this library is camera
14848 // or film material.
14849 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
14850 for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] {
14851 let path = fixtures.join("video").join(file);
14852 if path.exists() {
14853 rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false));
14854 }
14855 }
14856 for (i, line) in manifest.lines().skip(1).enumerate() {
14857 let f: Vec<&str> = line.split('\t').collect();
14858 if f.len() < 10 {
14859 continue;
14860 }
14861 let (path, codec) = (f[0], f[2]);
14862 if codec == "-" || codec.is_empty() {
14863 continue;
14864 }
14865 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
14866 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
14867 continue;
14868 };
14869 if !std::path::Path::new(path).exists() {
14870 eprintln!("SKIP {}: file is gone", i + 1);
14871 continue;
14872 }
14873 let name = path.rsplit('/').next().unwrap_or(path);
14874 let is_capture = path.contains("/OBS/")
14875 || (name.len() > 19
14876 && name.as_bytes()[4] == b'-'
14877 && name.as_bytes()[7] == b'-'
14878 && name.as_bytes()[10] == b' '
14879 && name.as_bytes()[13] == b'-');
14880 rows.push((
14881 format!("{}", i + 1),
14882 format!("{codec} {w}x{h}"),
14883 path.to_string(),
14884 f[8].parse::<f64>().unwrap_or(0.0),
14885 is_capture,
14886 ));
14887 }
14888 // Per (N, V): the worst camera/film row and the best screen row, so
14889 // the separation of the whole library is one subtraction.
14890 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
14891 eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |");
14892 for (idx, label, path, dur, is_capture) in &rows {
14893 let Some((nw, nh)) = probe_dims(path) else {
14894 eprintln!("SKIP {idx}: ffprobe gave no size");
14895 continue;
14896 };
14897 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
14898 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
14899 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
14900 let mut file_grid = [[0f64; 7]; 5];
14901 let mut file_frames = 0usize;
14902 for pct in [10u32, 50, 90] {
14903 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
14904 let frames = decode(path, &seek, &vf, cw, ch, 4);
14905 if frames.is_empty() {
14906 eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" });
14907 continue;
14908 }
14909 let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64);
14910 let mut prev: Option<Vec<u8>> = None;
14911 for picture in &frames {
14912 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
14913 let grid = census(&y, cw, ch);
14914 for li in 0..5 {
14915 for fi in 0..7 {
14916 file_grid[li][fi] += grid[li][fi];
14917 }
14918 }
14919 file_frames += 1;
14920 // The shipped rule is (16 colours, var > 16): grid row 2,
14921 // floor 16 is column 3.
14922 share += grid[2][3];
14923 yes += usize::from(screen_content(&y, cw, cw, ch));
14924 let n = y.len() as f64;
14925 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
14926 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
14927 mean += sum / n;
14928 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
14929 if let Some(p) = &prev {
14930 mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n;
14931 }
14932 prev = Some(y);
14933 }
14934 let f = frames.len() as f64;
14935 eprintln!(
14936 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
14937 if *is_capture { "screen" } else { "camera" },
14938 share / f,
14939 if yes * 2 > frames.len() { "SCREEN" } else { "camera" },
14940 frames.len(),
14941 mean / f,
14942 sd / f,
14943 mad / (f - 1.0).max(1.0),
14944 );
14945 }
14946 if file_frames == 0 {
14947 continue;
14948 }
14949 for li in 0..5 {
14950 for fi in 0..7 {
14951 let s = file_grid[li][fi] / file_frames as f64;
14952 match is_capture {
14953 true => scr_min[li][fi] = scr_min[li][fi].min(s),
14954 false => cam_max[li][fi] = cam_max[li][fi].max(s),
14955 }
14956 }
14957 }
14958 }
14959 eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):");
14960 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>());
14961 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
14962 for (li, &limit) in limits.iter().enumerate() {
14963 let mut row = String::new();
14964 for fi in 0..7 {
14965 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
14966 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
14967 if s - c > best {
14968 best = s - c;
14969 best_rule = (limit, floors[fi]);
14970 }
14971 }
14972 eprintln!(" {limit:>5} |{row}");
14973 }
14974 // The threshold sits at the midpoint of the widest gap; the shipped
14975 // constant is its reciprocal in whole parts of the frame.
14976 let (li, fi) = (
14977 limits.iter().position(|&l| l == best_rule.0).unwrap(),
14978 floors.iter().position(|&f| f == best_rule.1).unwrap(),
14979 );
14980 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
14981 eprintln!(
14982 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
14983 best_rule.0,
14984 best_rule.1,
14985 best,
14986 cam_max[li][fi],
14987 scr_min[li][fi],
14988 mid,
14989 (100.0 / mid.max(0.1)).round() as usize,
14990 );
14991 }
14992
14993 /// The missing instrument: what this encoder costs against libaom and
14994 /// rav1e at matched fidelity, and how long it takes to get there.
14995 ///
14996 /// Recipe, identical on all three sides: 12 consecutive frames of each
14997 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
14998 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
14999 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
15000 /// it by default), 4:2:0 8-bit in and out. Reference points:
15001 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
15002 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
15003 /// tile_cols=1:tile_rows=1:threads=1`
15004 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
15005 /// ffmpeg-decoded frames of each encoder's own stream.
15006 ///
15007 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
15008 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
15009 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
15010 /// four encodes of that ladder together):
15011 ///
15012 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
15013 /// |---|---|---|---|---|
15014 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
15015 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
15016 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
15017 ///
15018 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
15019 /// the encoder takes -- every stream it writes is byte-identical, so the
15020 /// BD columns are this box's own re-run of the same recipe rather than a
15021 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
15022 /// rav1e). What moved is the wall of the four encodes:
15023 ///
15024 /// | clip | wall ours before | after | instructions:u before -> after |
15025 /// |---|---|---|---|
15026 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
15027 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
15028 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
15029 ///
15030 /// Three exact steps, none of which touches a coded bit: the coefficient
15031 /// rate pricer stopped rebuilding every CDF table per candidate
15032 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
15033 /// tile once per candidate (`decode::FilterReplay`), and the forward
15034 /// transform stopped transforming the all-zero residual that 70% of its
15035 /// calls carry.
15036 ///
15037 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
15038 ///
15039 /// | step | 1080p | 2160p | screen |
15040 /// |---|---|---|---|
15041 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
15042 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
15043 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
15044 ///
15045 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
15046 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
15047 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
15048 /// -- all three decided on the REAL film rows of
15049 /// [`bd_rate_screen_native`], which this downscaled recipe does not
15050 /// carry:
15051 ///
15052 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
15053 /// |---|---|---|---|
15054 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
15055 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
15056 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
15057 ///
15058 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
15059 /// DEFAULT of the sequence path this gate codes through -- the bars are
15060 /// non-screen so they take it, the capture is gated flat:
15061 ///
15062 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
15063 /// |---|---|---|---|---|
15064 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
15065 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
15066 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
15067 ///
15068 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
15069 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
15070 /// facade arm -- which is what "one mini-GOP driver, two entry points"
15071 /// means here. This downscaled recipe HATES the pyramid (as it hates
15072 /// every knob the real film rows of `bd_rate_screen_native` keep, which
15073 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
15074 /// above. The capture's row is the flat row to the byte in both runs --
15075 /// that equality IS the content gate.
15076 ///
15077 /// Loop restoration is NOT in yet: it is the one filter whose parameters
15078 /// are per restoration UNIT inside the tile payload, so it needs both
15079 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
15080 /// buffer to solve against -- neither of which this frame-header-level
15081 /// search reaches.
15082 ///
15083 /// The baseline it replaced, before an inter frame's blocks chose their
15084 /// own partition, was +501.4/+504.4/+440.9 against libaom and
15085 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
15086 ///
15087 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
15088 /// fidelity, while spending far more time than either (the partition
15089 /// search's own cost, uncut: see the two intra-pruning variants measured
15090 /// and rejected in the lane report). No
15091 /// threshold is asserted yet -- this run sets the baseline; the gate
15092 /// asserts four monotone points per ladder, and at EVERY ladder point of
15093 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
15094 /// `crate::stream::decode_stream` -- and asserts the encoder's
15095 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
15096 /// and V over every shown frame in display order. A failure names the
15097 /// clip, the q, the frame, the plane and the first differing sample.
15098 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
15099 /// which exposes no per-packet reconstruction, so that path asserts the
15100 /// two decoders against each other on all three planes.)
15101 ///
15102 /// Run:
15103 /// cargo test -p ec-av1 --release --lib -- --ignored \
15104 /// bd_rate_vs_libaom_and_rav1e --nocapture
15105 #[test]
15106 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
15107 fn bd_rate_vs_libaom_and_rav1e() {
15108 let _knobs = crate::speed::knob_write();
15109 if !have_ffmpeg() {
15110 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
15111 return;
15112 }
15113 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
15114 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
15115 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
15116 // rows for real content (the real rows live in the native gate).
15117 for (label, name) in [
15118 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
15119 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
15120 ] {
15121 let path = fixtures.join("video").join(name);
15122 if path.exists() {
15123 clips.push((label.to_string(), path));
15124 } else {
15125 eprintln!("SKIP clip {name}: missing");
15126 }
15127 }
15128 // Screen capture: the repo carries no screen-capture fixture, so take
15129 // the first OBS recording the real-library manifest names.
15130 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
15131 Ok(manifest) => {
15132 let screen = manifest
15133 .lines()
15134 .skip(1)
15135 .filter_map(|l| l.split('\t').next())
15136 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
15137 match screen {
15138 Some(p) => clips.push((
15139 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
15140 std::path::PathBuf::from(p),
15141 )),
15142 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
15143 }
15144 }
15145 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
15146 }
15147 assert!(!clips.is_empty(), "no source clip available");
15148
15149 let (width, height, frames) = (640usize, 384usize, 12usize);
15150 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
15151 .iter()
15152 .map(|q| {
15153 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
15154 .map(String::from)
15155 .to_vec()
15156 })
15157 .collect();
15158 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
15159 .iter()
15160 .map(|q| {
15161 vec![
15162 "-rav1e-params".to_string(),
15163 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
15164 ]
15165 })
15166 .collect();
15167 println!(
15168 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
15169 );
15170 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
15171 println!("|---|---|---|---|---|");
15172 for (name, path) in &clips {
15173 let fctx = &crate::decode::FrameCtx::new();
15174 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
15175 let _ = take_partition_hits();
15176 let _ = crate::tile::take_palette_hits();
15177 SCREEN_FRAMES.iter().for_each(|c| {
15178 c.store(0, std::sync::atomic::Ordering::Relaxed);
15179 });
15180 let _ = take_uv_mode_hits();
15181 let _ = crate::tile::take_inter_mode_hits();
15182 let _ = crate::tile::take_drl_hits();
15183 let _ = crate::tile::take_ref_hits();
15184 let _ = crate::tile::take_compound_mode_hits();
15185 let _ = crate::tile::take_compound_pair_hits();
15186 let _ = crate::tile::take_compound_size_hits();
15187 let _ = crate::tile::take_compound_leaf_mode_hits();
15188 let _ = take_b64_root_hits();
15189 let _ = take_b64_residual_hits();
15190 let _ = take_b64_compound_hits();
15191 let _ = crate::motion::take_census();
15192 // The entry-surface arm: run the SAME ladder through the
15193 // streaming facade the editor's export calls, which must print
15194 // the same BD numbers as the sequence path -- byte for byte the
15195 // same stream now that both drive one mini-GOP driver
15196 // (lane-av1pyrdef).
15197 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
15198 let (ours, ours_wall) = match facade {
15199 false => our_ladder(name, &source, width, height, fctx),
15200 true => {
15201 let pyramid = crate::encoder::Pyramid::from_env();
15202 let (ladder, wall, counts, bytes, effective) =
15203 our_ladder_facade(name, &source, width, height, pyramid);
15204 eprintln!(
15205 "{name}: facade, pyramid requested {pyramid:?} effective \
15206 {effective:?} -- frames key {} arf {} leaf {} \
15207 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
15208 counts[0], counts[1], counts[2], counts[3],
15209 bytes[0], bytes[1], bytes[2], bytes[3],
15210 );
15211 (ladder, wall)
15212 }
15213 };
15214 // How often the inter split actually fired over this clip's four
15215 // encodes, against the whole 32x32 that was the only outcome
15216 // before (gate-blind-to-feature).
15217 let [whole32, split32, whole16, split16] = take_partition_hits();
15218 // Which inter modes actually fired over this clip's four encodes,
15219 // and at which DRL index -- a mode nobody picks is a mode the BD
15220 // number cannot be crediting (gate-blind-to-feature).
15221 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
15222 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
15223 let refs = crate::tile::take_ref_hits();
15224 let modes_total = (nearest + near + global + new).max(1);
15225 eprintln!(
15226 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
15227 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
15228 {drl0}/{drl1}/{drl2}/{drl3}",
15229 100.0 * nearest as f64 / modes_total as f64,
15230 100.0 * near as f64 / modes_total as f64,
15231 100.0 * global as f64 / modes_total as f64,
15232 100.0 * new as f64 / modes_total as f64,
15233 );
15234 // The compound census: what share of the coded inter blocks took
15235 // a compound reference at all, which compound mode they took, and
15236 // which pair (gate-blind-to-feature -- a compound mode nobody
15237 // picks cannot be what a BD number credits).
15238 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
15239 // superblocks were left whole at all, and how many of those coded
15240 // a residual or took a compound reference.
15241 let (roots, root_res, root_comp) = (
15242 take_b64_root_hits(),
15243 take_b64_residual_hits(),
15244 take_b64_compound_hits(),
15245 );
15246 eprintln!(
15247 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
15248 );
15249 let comp_modes = crate::tile::take_compound_mode_hits();
15250 let comp_pairs = crate::tile::take_compound_pair_hits();
15251 let comp_sizes = crate::tile::take_compound_size_hits();
15252 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
15253 let comp_total: usize = comp_modes.iter().sum();
15254 eprintln!(
15255 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
15256 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
15257 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
15258 modes_total + comp_total,
15259 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
15260 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
15261 comp_modes[6], comp_modes[7],
15262 comp_pairs[3], comp_pairs[6],
15263 );
15264 eprintln!(
15265 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
15266 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
15267 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6],
15268 comp_leaf[7],
15269 );
15270 eprintln!(
15271 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
15272 comp_sizes[1], comp_sizes[2], comp_sizes[3],
15273 );
15274 // Where the wall-owning stage actually goes: how many candidate
15275 // evaluations (one `mc::predict` + SAD each) a search spends, how
15276 // many of them are subpel, and how often the winner is the seed
15277 // it started from -- the census the seeded search is judged by.
15278 let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census();
15279 let per = |n: u64| n as f64 / calls.max(1) as f64;
15280 eprintln!(
15281 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
15282 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
15283 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
15284 per(evals),
15285 100.0 * subpel as f64 / evals.max(1) as f64,
15286 per(rounds),
15287 100.0 * near_pred as f64 / calls.max(1) as f64,
15288 100.0 * unmoved as f64 / calls.max(1) as f64,
15289 );
15290 eprintln!(
15291 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
15292 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
15293 );
15294 eprintln!(
15295 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
15296 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
15297 whole32 + split32,
15298 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
15299 whole16 + split16,
15300 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
15301 );
15302 // The deblocking level each of this clip's frames chose
15303 // (lane-av1filt): 0 everywhere would mean the filter never fires.
15304 let levels = crate::filter_search::take_chosen_levels();
15305 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
15306 let mean = |f: fn(&Chosen) -> u8| {
15307 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
15308 };
15309 eprintln!(
15310 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
15311 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
15312 levels.len(),
15313 mean(|l| l.0.0),
15314 mean(|l| l.0.1),
15315 mean(|l| l.1.0),
15316 mean(|l| l.1.1),
15317 mean(|l| l.2.0),
15318 mean(|l| l.2.1),
15319 );
15320 // How many strength presets each frame's CDEF list carried and
15321 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
15322 // everywhere would mean the per-unit choice never fires.
15323 let presets = crate::filter_search::take_cdef_presets();
15324 let mut by_bits = [0usize; 4];
15325 for (b, _) in &presets {
15326 by_bits[usize::from(*b)] += 1;
15327 }
15328 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
15329 let on_extra: usize = presets
15330 .iter()
15331 .flat_map(|(_, c)| c.iter().skip(1))
15332 .sum();
15333 eprintln!(
15334 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
15335 on a non-default preset ({:.1}%)",
15336 by_bits[0],
15337 by_bits[1],
15338 by_bits[2],
15339 by_bits[3],
15340 on_extra,
15341 units,
15342 100.0 * on_extra as f64 / units.max(1) as f64
15343 );
15344 // How the 64x64 luma restoration units split between
15345 // RESTORE_NONE and Wiener (lane-av1lr).
15346 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
15347 eprintln!(
15348 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
15349 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
15350 );
15351 // Which chroma modes the search actually wins with, against the
15352 // unconditional DC_PRED that was the only outcome before
15353 // (gate-blind-to-feature).
15354 // Screen-content detection and the palette it turns on
15355 // (gate-blind-to-feature): how many frames set
15356 // `allow_screen_content_tools`, how many blocks took a palette,
15357 // and of what size. A film clip must print `screen frames on=0`.
15358 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
15359 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
15360 // Which tables the SEARCH priced against, per frame arming
15361 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
15362 // real starting ones. A film clip must show every inter arming on
15363 // the real side, a screen clip none of them.
15364 let (price_default, price_real) = crate::tile::take_pricing_hits();
15365 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
15366 let palette = crate::tile::take_palette_hits();
15367 eprintln!(
15368 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
15369 palette[0],
15370 (2..=8)
15371 .filter(|&n| palette[n] > 0)
15372 .map(|n| format!("{n}={}", palette[n]))
15373 .collect::<Vec<_>>()
15374 .join(" ")
15375 );
15376 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
15377 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
15378 // only ever fires at one magnitude is a search that never left
15379 // its first candidate (gate-blind-to-feature).
15380 // The luma angle-delta histogram (lane-av1cfl): how many
15381 // directional blocks won at each delta. All-zero would mean the
15382 // refinement never beat the base angle.
15383 let deltas = take_angle_delta_hits();
15384 if deltas.iter().sum::<usize>() > 0 {
15385 eprintln!(
15386 "{name}: angle_delta_y {}",
15387 deltas
15388 .iter()
15389 .enumerate()
15390 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
15391 .collect::<Vec<_>>()
15392 .join(" ")
15393 );
15394 }
15395 let alphas = take_cfl_alpha_hits();
15396 if alphas.iter().sum::<usize>() > 0 {
15397 eprintln!(
15398 "{name}: cfl |alpha| {}",
15399 alphas
15400 .iter()
15401 .enumerate()
15402 .filter(|&(_, &n)| n > 0)
15403 .map(|(a, &n)| format!("{a}={n}"))
15404 .collect::<Vec<_>>()
15405 .join(" ")
15406 );
15407 }
15408 let palette_uv = crate::tile::take_palette_uv_hits();
15409 eprintln!(
15410 "{name}: chroma palette blocks {} sizes {}",
15411 palette_uv[0],
15412 (2..=8)
15413 .filter(|&n| palette_uv[n] > 0)
15414 .map(|n| format!("{n}={}", palette_uv[n]))
15415 .collect::<Vec<_>>()
15416 .join(" ")
15417 );
15418 let uv = take_uv_mode_hits();
15419 let uv_total: usize = uv.iter().sum();
15420 eprintln!(
15421 "{name}: uv modes {}",
15422 uv.iter()
15423 .enumerate()
15424 .filter(|&(_, &n)| n > 0)
15425 .map(|(m, &n)| format!(
15426 "{}={n} ({:.1}%)",
15427 UV_MODE_NAMES[m],
15428 100.0 * n as f64 / uv_total.max(1) as f64
15429 ))
15430 .collect::<Vec<_>>()
15431 .join(" ")
15432 );
15433 // Which transform depth the intra blocks of this clip's key
15434 // frames resolved to (lane-av1tx): depth 0 is one transform over
15435 // the whole block, 1 and 2 its halvings.
15436 let depths = take_tx_depth_hits();
15437 let depth_total: usize = depths.iter().sum();
15438 eprintln!(
15439 "{name}: intra tx depths {}",
15440 depths
15441 .iter()
15442 .enumerate()
15443 .map(|(d, &n)| format!(
15444 "{d}={n} ({:.1}%)",
15445 100.0 * n as f64 / depth_total.max(1) as f64
15446 ))
15447 .collect::<Vec<_>>()
15448 .join(" ")
15449 );
15450 print_inter_tx_census(name);
15451 // lane-av1obmc: how many blocks actually CODED a motion_mode
15452 // symbol and which value they took, by footprint -- "OBMC is on"
15453 // as a measurement rather than a claim (class
15454 // `gate-blind-to-feature`).
15455 let mm = crate::tile::take_motion_mode_hits();
15456 eprintln!(
15457 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
15458 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
15459 eligible)",
15460 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
15461 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
15462 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
15463 mm.iter().sum::<usize>(),
15464 );
15465 let (aom, aom_wall) =
15466 external_ladder(&source, width, height, "libaom-av1", &aom_points);
15467 let (rav1e, rav1e_wall) =
15468 external_ladder(&source, width, height, "librav1e", &rav1e_points);
15469 assert_monotone(&format!("{name}: ours"), &ours);
15470 assert_monotone(&format!("{name}: libaom"), &aom);
15471 assert_monotone(&format!("{name}: rav1e"), &rav1e);
15472 let points = ours
15473 .iter()
15474 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
15475 .collect::<Vec<_>>()
15476 .join(", ");
15477 println!(
15478 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
15479 bd_rate(&aom, &ours) * 100.0,
15480 bd_rate(&rav1e, &ours) * 100.0,
15481 );
15482 println!(
15483 "| references | libaom {} | rav1e {} | | |",
15484 aom.iter()
15485 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
15486 .collect::<Vec<_>>()
15487 .join(", "),
15488 rav1e
15489 .iter()
15490 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
15491 .collect::<Vec<_>>()
15492 .join(", "),
15493 );
15494 }
15495 assert_ladder_decodes();
15496 }
15497 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
15498 /// split by block class in lane-av1txdepth): depth 0 is one transform over
15499 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
15500 /// leaves and the 32x32 root, each single-reference or compound. A class
15501 /// with no counts at all never reached `commit_inter_luma` -- which is
15502 /// what its knob being off looks like (class `gate-blind-to-feature`).
15503 fn print_inter_tx_census(name: &str) {
15504 let splits = take_inter_tx_split_hits();
15505 let total: usize = splits.iter().sum();
15506 let row = |label: &str, base: usize| {
15507 let (n0, n1) = (splits[base], splits[base + 1]);
15508 format!(
15509 "{label} 0={n0} 1={n1} ({:.1}% split)",
15510 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
15511 )
15512 };
15513 eprintln!(
15514 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
15515 row("leaf single", 0),
15516 row("leaf compound", 2),
15517 row("32x32 single", 4),
15518 row("32x32 compound", 6),
15519 );
15520 }
15521
15522 /// The video stream's coded size, from ffprobe.
15523 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
15524 crate::probe::dims(clip)
15525 }
15526
15527 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
15528 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
15529 /// superblock-aligned one, still centred and still even for 4:2:0.
15530 ///
15531 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
15532 /// superblocks by design, so no default gate row has a block the frame
15533 /// edge cuts through -- while every arbitrary export size does (3840x1608
15534 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
15535 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
15536 /// read on.
15537 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
15538 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
15539 let (w, h) = spec.split_once('x').expect("EC_AV1_NATIVE_CROP is <width>x<height>");
15540 let (cw, ch): (usize, usize) =
15541 (w.parse().expect("crop width"), h.parse().expect("crop height"));
15542 let (nw, nh) = crate::probe::dims(clip)?;
15543 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
15544 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
15545 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
15546 }
15547
15548 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
15549 /// with `probe_screen_detect` so the detector sweep measures exactly the
15550 /// clips the keep table is read off. Selector env vars as documented on
15551 /// the gate; a missing clip prints a SKIP and drops its row.
15552 fn native_gate_clips() -> Vec<(String, String, String)> {
15553 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
15554 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
15555 let (film, film4k, screen) = (
15556 on("EC_AV1_NATIVE_FILM"),
15557 on("EC_AV1_NATIVE_FILM4K"),
15558 on("EC_AV1_NATIVE_SCREEN"),
15559 );
15560 // No selector at all means every clip; any selector means that subset.
15561 let all = !(film || film4k || screen);
15562 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
15563 // not film -- they print as "bars" so no reader takes them for real
15564 // content -- and the two rows below them are the real AV1 films.
15565 let mut clips: Vec<(String, String, String)> = Vec::new();
15566 for (want, label, file) in [
15567 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
15568 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
15569 ] {
15570 if !want {
15571 continue;
15572 }
15573 let path = fixtures.join("video").join(file);
15574 match path.exists() {
15575 true => {
15576 clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into()))
15577 }
15578 false => eprintln!("SKIP {label}: {file} missing"),
15579 }
15580 }
15581 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
15582 // The real films, taken out of the real-library manifest by codec and
15583 // coded width so no title and no home path lives in this file. Each
15584 // seek is PINNED (class `seeded fixture not reproducible`) at a
15585 // moving, non-black window -- a black leader would make every arm
15586 // read +0.000 (class `flat sample window`). Both sources are 10-bit
15587 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
15588 // what all three encoders see, so the comparison stays
15589 // encoder-vs-encoder.
15590 let pick = |width: &str| -> Option<String> {
15591 let m = manifest.as_ref().ok()?;
15592 m.lines()
15593 .skip(1)
15594 .map(|l| l.split('\t').collect::<Vec<_>>())
15595 .find(|f| {
15596 f.len() > 4
15597 && f[2] == "av1"
15598 && f[3] == width
15599 && std::path::Path::new(f[0]).exists()
15600 })
15601 .map(|f| f[0].to_string())
15602 };
15603 for (want, label, width, seek) in [
15604 (all || film, "film A (1080p source)", "1920", "00:35:00"),
15605 (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"),
15606 ] {
15607 if !want {
15608 continue;
15609 }
15610 match pick(width) {
15611 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
15612 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
15613 }
15614 }
15615 if all || screen {
15616 match &manifest {
15617 Ok(manifest) => match manifest
15618 .lines()
15619 .skip(1)
15620 .filter_map(|l| l.split('\t').next())
15621 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
15622 {
15623 Some(p) => clips.push((
15624 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
15625 p.to_string(),
15626 "0".into(),
15627 )),
15628 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
15629 },
15630 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
15631 }
15632 }
15633 clips
15634 }
15635
15636 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
15637 /// downscales the OBS capture to 640x384, which destroys exactly the
15638 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
15639 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
15640 /// on that recipe is taken on content the tool cannot serve. This arm
15641 /// crops -- never scales -- a superblock-aligned window out of the middle
15642 /// of the capture at its own resolution (at most 1920x1024, so the wall
15643 /// stays in the minutes) and runs the same 12-frame, four-quantizer
15644 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
15645 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
15646 /// sample-exactness assertion `our_ladder` makes.
15647 ///
15648 /// It is its own `--ignored` test so the default gate's wall does not
15649 /// grow. Every variant is an environment knob, and each of those is a
15650 /// `OnceLock` read once per process, so a variant is a separate run:
15651 ///
15652 /// cargo test -p ec-av1 --release --lib -- --ignored \
15653 /// bd_rate_screen_native --nocapture # baseline
15654 /// EC_AV1_INTRABC=1 ... same command # intra block copy
15655 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
15656 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
15657 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
15658 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
15659 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
15660 ///
15661 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
15662 /// through (lane-av1pyrdef); the run prints the requested and the
15663 /// effective pyramid per clip, and a screen clip's effective one is
15664 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
15665 /// streaming facade instead, which prints the per-level frame and byte
15666 /// census and asserts ffmpeg's decode against our own decoder on all
15667 /// three planes in display order; both arms code the same bytes
15668 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
15669 ///
15670 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
15671 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
15672 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
15673 /// cost -- so every "film" column in the historical tables of this file
15674 /// is that generator, not film. The real content is `film A`, `film B`
15675 /// (native crops out of the two AV1 films the real-library manifest
15676 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
15677 /// decision only the bars rows support is not supported.
15678 ///
15679 /// Measured 2026-09-07, the five rows before and after the screen
15680 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
15681 /// BOTH real films were classified as screen content on 48/48 frames, so
15682 /// their coefficients were priced against the DEFAULT CDFs and the
15683 /// palette search ran over film; after, both are non-screen (0/48) and
15684 /// the capture is unchanged at 48/48:
15685 ///
15686 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
15687 /// |---|---|---|---|
15688 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
15689 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
15690 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
15691 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
15692 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
15693 ///
15694 /// Both bars rows and the capture are byte-identical across that change
15695 /// (their classification never moved); the palette search over film was
15696 /// costing roughly a tenth of the film rows' wall.
15697 ///
15698 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
15699 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
15700 /// the capture is gated flat and does not move a byte:
15701 ///
15702 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
15703 /// |---|---|---|---|---|
15704 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
15705 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
15706 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
15707 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
15708 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
15709 ///
15710 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
15711 /// which is the point of the shared driver: the two entry points code one
15712 /// stream. The bars rows are fixtures (recorded, never a decision); the
15713 /// two real films are what the pyramid ships for.
15714 ///
15715 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
15716 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
15717 /// setting any one of them keeps only the selected rows (the two 1080p
15718 /// rows, the two 2160p rows, the capture row respectively). A missing
15719 /// real film SKIPs its row; it never fails the gate.
15720 #[test]
15721 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
15722 fn bd_rate_screen_native() {
15723 let _knobs = crate::speed::knob_read();
15724 native_bd_arm("bd_rate_screen_native", 12, false);
15725 }
15726
15727 /// The LONG-GOP arm of the native BD gate: the same recipe as
15728 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
15729 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
15730 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
15731 /// reaches libaom as `--kf-max-dist=48` and rav1e as
15732 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
15733 /// inter pictures.
15734 ///
15735 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
15736 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
15737 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
15738 /// above 12 codes the same stream there -- the shipped `16` was measured
15739 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
15740 /// group (class `instrument at bound` / `gate blind to feature`). The
15741 /// user's exports are long GOPs, so the pyramid shape is decided here.
15742 ///
15743 /// cargo test -p ec-av1 --release --lib -- --ignored \
15744 /// bd_rate_film_long_gop --nocapture
15745 ///
15746 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
15747 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
15748 /// Read every row off the log's own "pyramid requested/effective" print,
15749 /// never off the argument order of the runs (lane-pyr3 misattributed
15750 /// three rows that way).
15751 ///
15752 /// Table: `lanes/pyr4.sweep.txt`.
15753 #[test]
15754 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
15755 fn bd_rate_film_long_gop() {
15756 let _knobs = crate::speed::knob_write();
15757 native_bd_arm("bd_rate_film_long_gop", 48, true);
15758 }
15759
15760 /// The shared driver of the two native BD arms above: `frames` pictures
15761 /// per row (the sequence's `gop` is the same number, so one key frame),
15762 /// four quantizers, `films_only` dropping every row but the two real
15763 /// films.
15764 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
15765 if !have_ffmpeg() {
15766 eprintln!("SKIP {label}: no ffmpeg");
15767 return;
15768 }
15769 let mut clips = native_gate_clips();
15770 if films_only {
15771 clips.retain(|(name, _, _)| name.starts_with("film "));
15772 }
15773 if clips.is_empty() {
15774 eprintln!("SKIP {label}: no clip");
15775 return;
15776 }
15777
15778 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
15779 .iter()
15780 .map(|q| {
15781 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
15782 .map(String::from)
15783 .to_vec()
15784 })
15785 .collect();
15786 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
15787 .iter()
15788 .map(|q| {
15789 vec![
15790 "-rav1e-params".to_string(),
15791 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
15792 ]
15793 })
15794 .collect();
15795 println!(
15796 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
15797 intrabc {}, palette maxcolors {}",
15798 armed_tiles(),
15799 crate::par::tile_threads(),
15800 intrabc_enabled(),
15801 palette_max_colors(),
15802 );
15803 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |");
15804 println!("|---|---|---|---|---|");
15805 for (name, path, seek) in &clips {
15806 let fctx = &crate::decode::FrameCtx::new();
15807 if probe_dims(path).is_none() {
15808 eprintln!("SKIP {name}: ffprobe gave no size");
15809 continue;
15810 }
15811 // A whole number of 128-wide superblocks, at most 1920x1024, out
15812 // of the middle of the frame; the offsets stay even for 4:2:0.
15813 // ONE definition, shared with `examples/enc_probe` so the probe
15814 // cannot measure a different window than this gate (lane-probe).
15815 let (vf, cw, ch) = match native_crop_override(path) {
15816 Some(over) => over,
15817 None => crate::probe::gate_crop(path),
15818 };
15819 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
15820 SCREEN_FRAMES.iter().for_each(|c| {
15821 c.store(0, std::sync::atomic::Ordering::Relaxed);
15822 });
15823 let _ = crate::tile::take_palette_hits();
15824 let _ = crate::tile::take_palette_uv_hits();
15825 let _ = crate::tile::take_intrabc_hits();
15826 let _ = take_intrabc_search();
15827 let _ = crate::tile::take_filter_intra_hits();
15828 let _ = take_edge_census();
15829 // The sequence path itself codes the pyramid now
15830 // (lane-av1pyrdef), and prints what it requested and what the
15831 // content gate left effective.
15832 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
15833 // lane-sse: the blocks the true frame edge cuts through, and how
15834 // much of their RAW squared error sat in the padding the encoder
15835 // invented past it -- what the inside-only score stopped ranking
15836 // on. Empty on a superblock-aligned crop, which is every default
15837 // gate row (class `gate-blind-to-feature`).
15838 if edge_census() {
15839 for (side, n, inside, padding) in take_edge_census() {
15840 eprintln!(
15841 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
15842 padding_sse={padding} ({:.1}% of raw)",
15843 100.0 * padding as f64 / (inside + padding).max(1) as f64,
15844 );
15845 }
15846 }
15847 // gate-blind-to-feature: what the screen tools actually did at
15848 // native resolution, over this clip's four encodes.
15849 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
15850 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
15851 // Which tables the SEARCH priced against, per frame arming
15852 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
15853 // real starting ones. A film clip must show every inter arming on
15854 // the real side, a screen clip none of them.
15855 let (price_default, price_real) = crate::tile::take_pricing_hits();
15856 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
15857 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
15858 // superblocks stayed whole, and how many of those coded a
15859 // residual, split that residual's luma, or took a compound
15860 // reference (class `gate-blind-to-feature`).
15861 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
15862 // the superblocks offered the trial were coded whole.
15863 let [i64_whole, i64_offered] = take_i64_root_hits();
15864 eprintln!(
15865 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%)",
15866 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
15867 );
15868 eprintln!(
15869 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
15870 take_b64_root_hits(),
15871 take_b64_residual_hits(),
15872 take_b64_var_tx_hits(),
15873 take_b64_compound_hits(),
15874 );
15875 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
15876 // of every priced block): what the deadzone quantiser handed the
15877 // RDOQ pass and what the pass changed, over every TRIAL block of
15878 // this row's four encodes -- not over the coded stream, so it is
15879 // the bits AT STAKE in the search, not in the bitstream.
15880 let rq = crate::tile::take_rdoq_stats();
15881 if rq[0] > 0 {
15882 eprintln!(
15883 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
15884 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
15885 rq[0],
15886 rq[1],
15887 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
15888 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
15889 rq[4],
15890 rq[5],
15891 rq[7] as f64 / 64.0,
15892 rq[6] as f64 / 64.0,
15893 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
15894 );
15895 }
15896 // lane-av1obmc2: the same motion_mode census the 640x384 gate
15897 // prints (class `gate-blind-to-feature`) -- how many blocks coded
15898 // the symbol at each footprint and how many took OBMC. Without it
15899 // the native table, which is the standing keep table, could not
15900 // say whether the tool fired at all.
15901 let mm = crate::tile::take_motion_mode_hits();
15902 eprintln!(
15903 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
15904 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
15905 eligible)",
15906 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
15907 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
15908 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
15909 mm.iter().sum::<usize>(),
15910 );
15911 print_inter_tx_census(name);
15912 let palette = crate::tile::take_palette_hits();
15913 let palette_uv = crate::tile::take_palette_uv_hits();
15914 let ibc = crate::tile::take_intrabc_hits();
15915 let search = take_intrabc_search();
15916 eprintln!(
15917 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
15918 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
15919 won {})",
15920 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
15921 palette[0],
15922 palette_uv[0],
15923 ibc[0],
15924 search[0],
15925 search[1],
15926 search[2],
15927 );
15928 // gate-blind-to-feature: how often the five recursive filter-intra
15929 // modes actually won a block over this clip's four encodes -- a
15930 // tool that never fires is not measured by the row above it.
15931 let fi = crate::tile::take_filter_intra_hits();
15932 eprintln!(
15933 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
15934 filter_intra_on(),
15935 fi[0],
15936 fi[1],
15937 fi[2],
15938 fi[3],
15939 fi[4],
15940 fi[5],
15941 );
15942 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
15943 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
15944 assert_monotone(&format!("{name}: ours"), &ours);
15945 assert_monotone(&format!("{name}: libaom"), &aom);
15946 assert_monotone(&format!("{name}: rav1e"), &rav1e);
15947 let points = ours
15948 .iter()
15949 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
15950 .collect::<Vec<_>>()
15951 .join(", ");
15952 println!(
15953 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
15954 bd_rate(&aom, &ours) * 100.0,
15955 bd_rate(&rav1e, &ours) * 100.0,
15956 );
15957 }
15958 assert_ladder_decodes();
15959 }
15960
15961 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
15962 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
15963 /// on the two film clips at their native gate crop. The 2160p clip loses
15964 /// at every arm of the propagating map and the named suspect was that its
15965 /// heavily filtered flat cells give a tiny denominator, so the dependence
15966 /// ratio explodes exactly where coding is cheap; this prints the numbers
15967 /// that confirm or refute it.
15968 #[test]
15969 #[ignore = "needs ffmpeg and the film fixtures"]
15970 fn tpl_intra_denominator_histogram() {
15971 let _knobs = crate::speed::knob_read();
15972 if !have_ffmpeg() {
15973 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
15974 return;
15975 }
15976 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
15977 for (label, file) in [
15978 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
15979 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
15980 ] {
15981 let path = fixtures.join("video").join(file);
15982 if !path.exists() {
15983 eprintln!("SKIP {label}: {file} missing");
15984 continue;
15985 }
15986 let path = path.to_str().unwrap();
15987 let Some((nw, nh)) = probe_dims(path) else {
15988 eprintln!("SKIP {label}: ffprobe gave no size");
15989 continue;
15990 };
15991 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
15992 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
15993 let source =
15994 clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
15995 let mut costs: Vec<f64> = Vec::new();
15996 for pic in &source {
15997 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
15998 costs.extend(
15999 super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)),
16000 );
16001 }
16002 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
16003 let mut sorted = costs.clone();
16004 sorted.sort_by(f64::total_cmp);
16005 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
16006 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
16007 eprintln!(
16008 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
16009 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
16010 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
16011 below 1.0x {} ({:.1}%)",
16012 costs.len(),
16013 q(0.0),
16014 q(0.01),
16015 q(0.05),
16016 q(0.25),
16017 q(0.50),
16018 q(0.75),
16019 q(0.99),
16020 q(1.0),
16021 below(0.25),
16022 100.0 * below(0.25) as f64 / costs.len() as f64,
16023 below(0.5),
16024 100.0 * below(0.5) as f64 / costs.len() as f64,
16025 below(1.0),
16026 100.0 * below(1.0) as f64 / costs.len() as f64,
16027 );
16028 }
16029 }
16030
16031 /// The probe arms the gate's source (lane-probe, class `instrument
16032 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
16033 /// command line and had no `-ss`, so it read film B from frame 0 -- a
16034 /// black leader -- and coded 59 kB where the gate's own ladder point
16035 /// coded 89 kB of the same title; every census taken through it was
16036 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
16037 /// the shared loader honours the seek (arming the probe's way and the
16038 /// gate's way gives byte-identical streams, and dropping the seek does
16039 /// not), on a synthetic clip whose content moves over time.
16040 #[test]
16041 fn the_probe_arms_the_gates_source() {
16042 let _knobs = crate::speed::knob_write();
16043 if !have_ffmpeg() {
16044 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
16045 return;
16046 }
16047 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
16048 std::fs::create_dir_all(&dir).unwrap();
16049 let clip = dir.join("testsrc2.y4m");
16050 // 384x202: neither side is a multiple of 128, so the gate's centre
16051 // window is a real derivation and not the frame itself -- exactly the
16052 // shape film B has (3840x1608, never 3840x2160).
16053 let ok = Command::new("ffmpeg")
16054 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"])
16055 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
16056 .arg(&clip)
16057 .status()
16058 .expect("ffmpeg failed to run")
16059 .success();
16060 assert!(ok, "ffmpeg could not write the synthetic clip");
16061 let path = clip.to_str().unwrap();
16062
16063 // The window: superblock-aligned, centred, even offsets.
16064 let (vf, w, h) = crate::probe::gate_crop(path);
16065 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
16066
16067 let (seek, q) = ("00:00:01", 150u8);
16068 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
16069 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
16070 assert!(
16071 gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
16072 "the probe's source differs from the gate's at the same window"
16073 );
16074 let bytes = |src: &[Picture]| {
16075 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::new())
16076 .unwrap()
16077 .stream
16078 };
16079 assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes");
16080 // The two witnesses that both halves of the arming reach ffmpeg: the
16081 // seek, and the crop's own offset (the film-B defect in miniature --
16082 // the probe was reading `crop=..:568` of a 1608-high frame).
16083 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
16084 assert_ne!(
16085 bytes(&gate),
16086 bytes(&unseeked),
16087 "seeked and unseeked arming coded the same bytes -- the seek is inert"
16088 );
16089 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
16090 assert_ne!(
16091 bytes(&gate),
16092 bytes(&offset),
16093 "centred and top-aligned windows coded the same bytes -- the crop is inert"
16094 );
16095 std::fs::remove_dir_all(&dir).ok();
16096 }
16097
16098 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
16099 /// point inside the test binary, to compare against `examples/enc_probe`.
16100 #[test]
16101 #[ignore = "diagnostic: needs ffmpeg and a clip"]
16102 fn probe_parity_point() {
16103 let _knobs = crate::speed::knob_write();
16104 let g = |k: &str| std::env::var(k).unwrap();
16105 let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap();
16106 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
16107 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
16108 let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames);
16109 let fctx = &crate::decode::FrameCtx::new();
16110 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
16111 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
16112 for &b in &e.stream {
16113 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
16114 }
16115 eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
16116 e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid());
16117 }
16118}