forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb978eaaTahinli2 months ago2527 commits

encode.rs14227 lines, 636.8 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_typed,
46};
47
48/// The side of the larger of the two luma blocks this encoder codes, in
49/// samples.
50const BLOCK: usize = 32;
51
52/// The side of the smaller one, which a 32x32 block may be split into four of.
53const SUB: usize = 16;
54
55/// The side of a superblock, which is what the partition tree starts from.
56pub(crate) const SUPERBLOCK: usize = 64;
57
58// lane-sb128 r1: the superblock size in samples the intra-reach rules
59// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the
60// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and
61// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128
62// superblock changes every answer inside it (the tables themselves are
63// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
64// stays the encoder's own fixed 64.
65
66/// Sets the superblock size [`Reach`] answers against (64 or 128).
67pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
68 fctx.reach_sb_px.with(|c| c.set(px));
69}
70
71fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
72 fctx.reach_sb_px.with(|c| c.get())
73}
74
75/// How heavily the mode search weighs rate against squared error, in units of
76/// the quantizer's reconstruction step squared per bit.
77///
78/// Swept three times over his clips and three synthetic pictures
79/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
80/// the three lane reports). The first sweep, before the mode symbol was
81/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
82/// third sweep, after the levels were costed through the writer's own CDFs
83/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
84/// on film and -0.20% against -0.14% on screen capture.
85///
86/// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than
87/// those ladders, and 0.1 was far off the point: the rate term was carrying
88/// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom /
89/// vs rav1e for 1080p film, 2160p film, screen capture:
90///
91/// | lambda | 1080p | 2160p | screen |
92/// |--------|-------|-------|--------|
93/// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 |
94/// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 |
95/// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 |
96/// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
97/// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 |
98/// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 |
99/// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 |
100/// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 |
101/// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 |
102///
103/// and on the native 1920x1024 crops, which is the table that decides:
104///
105/// | lambda | film 1080p | film 2160p | screen |
106/// |--------|------------|------------|--------|
107/// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 |
108/// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 |
109/// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 |
110/// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 |
111///
112/// 0.0375 was the best point on two clips of three there and cost the "2160p
113/// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept
114/// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the
115/// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of
116/// whose cells have no intra cost -- no real film supported the point.
117///
118/// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL
119/// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs
120/// libaom / vs rav1e, everything else at the shipped defaults:
121///
122/// | lambda | bars 1080p | bars 2160p | film A | film B | screen |
123/// |--------|------------|------------|--------|--------|--------|
124/// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 |
125/// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 |
126/// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 |
127/// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 |
128/// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 |
129/// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 |
130///
131/// Real film wants roughly HALF the rate weight the bars asked for: the bowl
132/// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep
133/// against the shipped 0.05, while the bars rows walk the other way (they are
134/// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so
135/// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture
136/// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx
137/// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall.
138const LAMBDA_SCALE: f64 = 0.0275;
139
140/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
141/// picks it is the thing running. A release build has no such knob.
142fn lambda_scale() -> f64 {
143 let swept = std::env::var("EC_AV1_LAMBDA")
144 .ok()
145 .and_then(|v| v.parse::<f64>().ok());
146 match swept {
147 Some(scale) if cfg!(test) => scale,
148 _ => LAMBDA_SCALE,
149 }
150}
151
152/// How a key frame's lambda differs from an inter frame's: libaom weighs the
153/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
154/// of 128), because every later frame predicts from the key frame, so an error
155/// left in it is paid for over the whole group. This encoder has no temporal
156/// propagation model at all, and this factor is the cheapest stand-in for one.
157/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
158///
159/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
160/// libaom / vs rav1e:
161///
162/// | k_key | 1080p | 2160p | screen |
163/// |---|---|---|---|
164/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
165/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
166/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
167/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
168///
169/// The two films want the key frame coded finer and the screen capture wants
170/// the opposite, by about the same amount, and at native the whole lever is
171/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
172/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
173/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
174/// per-frame-type weight; the real lever here is temporal propagation
175/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
176/// predict from, not each frame.
177const KEY_LAMBDA_FACTOR: f64 = 1.0;
178
179/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
180fn key_lambda_factor() -> f64 {
181 match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) {
182 Some(k) if cfg!(test) => k,
183 _ => KEY_LAMBDA_FACTOR,
184 }
185}
186
187// Every frame's predicted coefficient bits since the last
188// `take_predicted_bits`, in coding order -- the encoder half of
189// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
190#[cfg(test)]
191thread_local! {
192 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
193}
194
195/// Records one frame's predicted coefficient bits.
196#[cfg(test)]
197fn record_predicted_bits(bits: f64) {
198 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
199}
200
201/// Takes (and clears) what the frames encoded on this thread were predicted to
202/// spend on coefficients.
203#[cfg(test)]
204pub(crate) fn take_predicted_bits() -> Vec<f64> {
205 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
206}
207
208/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
209const SPLIT_INTER_8: bool = true;
210
211/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
212/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
213/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
214/// turns it off for an A/B on one build.
215/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
216/// residual as one transform over the whole block or as the four transforms
217/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
218/// intra block inside the inter frame. ON since lane-av1tx2, which found why
219/// the streams desynced -- the writer counted the [`crate::decode::
220/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
221/// reader drops the term -- and measured the split search: BD-rate vs libaom
222/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
223/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
224/// A/B on one build.
225fn tx_select_inter() -> bool {
226 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
227 *ON.get_or_init(|| {
228 !matches!(
229 std::env::var("EC_AV1_TX_SELECT_INTER").as_deref(),
230 Ok("0") | Ok("off")
231 )
232 })
233}
234
235fn tx_select() -> bool {
236 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
237 *ON.get_or_init(|| {
238 !matches!(
239 std::env::var("EC_AV1_TX_SELECT").as_deref(),
240 Ok("0") | Ok("off")
241 )
242 })
243}
244
245fn split_inter_8() -> bool {
246 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
247 Some(v) if cfg!(test) => v != "0",
248 _ => SPLIT_INTER_8,
249 }
250}
251
252/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
253/// NEARESTMV candidate it always had.
254const LEAF_NEW_MV: bool = true;
255
256/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
257/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
258/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
259/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
260const EXTRA_REF_NEW_MV: bool = true;
261
262/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
263/// own best vector before that reference's `NEWMV` search is skipped: a
264/// factor on the search cost scale, `1.0` meaning "as good or better".
265/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
266/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
267/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
268/// extra searches drop from +27% to +4% of the base count -- and on screen
269/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
270/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
271/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
272/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
273/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
274/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
275/// own noise. 0.35 stays; the lever that did move at the new rate weight is
276/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
277const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
278
279/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
280fn extra_new_skip_margin() -> f64 {
281 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
282 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
283 _ => EXTRA_NEW_SKIP_MARGIN,
284 }
285}
286
287/// The margin on a LEAF's SECOND-reference motion search, the same early-out
288/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
289/// `NEWMV`: the search is skipped when that reference's own
290/// `NEAREST_NEARESTMV` vector already prices this many times better than the
291/// leaf's `LAST` search found. `0.0` never skips.
292///
293/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
294/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
295/// 2160p (38195 with no second-reference search at all):
296/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
297/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
298/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
299/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
300/// of its extra searches; past it the calls double for another -0.3/-0.5.
301/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
302/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
303/// so the margin is pure wall on that content (+10% searches at 0.8).
304///
305/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
306/// the native gate with local warp on, BD vs libaom / vs rav1e:
307///
308/// | margin | film 1080p | film 2160p | screen |
309/// |---|---|---|---|
310/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
311/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
312/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
313/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
314/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
315///
316/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
317/// with screen flat -- and it beats never-skipping, i.e. the early-out is
318/// still worth having, just at a looser margin than the old rate weight
319/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
320/// 32.6s at 2160p), which is the price of the extra second-reference
321/// searches.
322const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
323
324/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
325/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
326fn leaf_second_new_margin() -> f64 {
327 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
328 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
329 None => LEAF_SECOND_NEW_MARGIN,
330 }
331}
332
333/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
334fn leaf_second_new_mv() -> bool {
335 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
336 Some(v) => v != "0",
337 None => true,
338 }
339}
340
341/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
342/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
343/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
344/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
345/// was missing was the encoder ever forming one below 32x32.
346const LEAF_COMPOUND: bool = true;
347
348/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
349fn leaf_compound() -> bool {
350 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
351 Some(v) => v != "0",
352 None => LEAF_COMPOUND,
353 }
354}
355
356/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
357fn leaf_new_mv() -> bool {
358 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
359 Some(v) if cfg!(test) => v != "0",
360 _ => LEAF_NEW_MV,
361 }
362}
363
364/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
365/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
366/// the true frame edge cut through was ever split there; inside the frame
367/// every block was coded whole, which left the partition decision the key
368/// frame already makes unmade for eleven frames out of twelve.
369const SPLIT_INTER_BLOCKS: bool = true;
370
371/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
372/// measurement that keeps it is running (test builds only, like
373/// [`lambda_scale`]).
374fn split_inter_blocks() -> bool {
375 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
376 Some(v) if cfg!(test) => v != "0",
377 _ => SPLIT_INTER_BLOCKS,
378 }
379}
380
381/// Whether the encoder searches loop restoration at all (spec 7.17): one
382/// Wiener filter per 64x64 luma restoration unit, picked from
383/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
384/// test build, like [`lambda_scale`].
385const RESTORATION: bool = true;
386
387/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
388fn restoration_enabled() -> bool {
389 match std::env::var("EC_AV1_LR").ok() {
390 Some(v) if cfg!(test) => v != "0",
391 _ => RESTORATION,
392 }
393}
394
395/// libaom's `partition_search_breakout` shape: how many non-zero luma
396/// coefficients per 256 luma samples a block may code and still be judged
397/// well enough predicted that the split below it is not worth trying. `0`
398/// disables the breakout (only the existing all-skip prune applies), which
399/// is the default until the sweep below justifies otherwise.
400///
401/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
402/// is where this lane's wall would have gone: 1 cuts the three clips'
403/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
404/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
405/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
406/// encoder's inter quality lives, so `0` ships and the knob stays for a
407/// future explicit speed preset.
408const SPLIT_BREAKOUT_COEFFS: usize = 0;
409
410/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
411/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
412/// out under `threshold * lambda` is not offered the split at all, and a
413/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
414/// always, as before this lever.
415///
416/// The census is what points here: the split trial runs on nearly every
417/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
418/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
419/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
420/// points, so the gate has to read the block's own RD cost, not its levels.
421///
422/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
423/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
424/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
425/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
426/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
427/// the largest threshold whose BD stays inside the +0.3 keep rule on every
428/// clip.
429/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
430/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
431/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
432/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
433/// the screen wall). Neither clears the keep rule; 0.125 stays.
434const SPLIT_RD_THRESHOLD: f64 = 0.125;
435
436/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
437fn split_rd_threshold() -> f64 {
438 static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
439 *T.get_or_init(|| {
440 std::env::var("EC_AV1_SPLIT_RD")
441 .ok()
442 .and_then(|v| v.parse().ok())
443 .unwrap_or(SPLIT_RD_THRESHOLD)
444 })
445}
446
447/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
448/// [`split_rd_threshold`] withholds the split trial.
449fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
450 let t = split_rd_threshold();
451 t > 0.0 && cost < t * lambda * (side * side) as f64
452}
453
454/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
455/// build.
456fn split_breakout_coeffs() -> usize {
457 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
458 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
459 _ => SPLIT_BREAKOUT_COEFFS,
460 }
461}
462
463/// How often each partition decision was taken since the last
464/// [`take_partition_hits`], so a gate can report how often a new partition
465/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
466/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
467/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
468static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
469 std::sync::atomic::AtomicUsize::new(0),
470 std::sync::atomic::AtomicUsize::new(0),
471 std::sync::atomic::AtomicUsize::new(0),
472 std::sync::atomic::AtomicUsize::new(0),
473];
474
475/// Records one such decision.
476fn partition_hit(which: usize) {
477 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
478}
479
480/// Takes (and clears) the counts.
481#[cfg(test)]
482pub(crate) fn take_partition_hits() -> [usize; 4] {
483 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
484}
485
486/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
487/// rate-distortion trials the block search actually runs, by kind, and where
488/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
489/// default, and a measurement build rather than a speed one -- the census
490/// runs the SAD pre-pass the unpruned search otherwise skips.
491pub fn census_on() -> bool {
492 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
493 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
494}
495
496/// What each [`CENSUS`] counter counts.
497pub const CENSUS_KINDS: [&str; 11] = [
498 "intra blocks searched (key frame + inter leaves)",
499 "intra luma mode trials",
500 "chroma searches",
501 "chroma mode trials (each = 2 plane trials)",
502 "tx-depth trials (transform units, depth >= 1)",
503 "inter 32x32 blocks searched",
504 "inter block intra-mode trials",
505 "inter mv candidates (each = 3 mc trials)",
506 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
507 " of those, intra won",
508 " of those, the NEARESTMV trial coded no residual",
509];
510
511/// The census counters themselves, indexed by [`CENSUS_KINDS`].
512static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
513 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
514
515/// Where the RD winner sat in the SAD ranking, for the luma intra search and
516/// the chroma mode search -- what says whether a top-N prune would have kept
517/// the block the search actually chose.
518static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
519 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
520static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
521 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
522
523fn census_add(kind: usize, n: usize) {
524 if census_on() {
525 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
526 }
527}
528
529/// Reads (and clears) the census, so a driver can attribute it to its own encode.
530pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
531 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
532 (
533 std::array::from_fn(|i| take(&CENSUS[i])),
534 std::array::from_fn(|i| take(&LUMA_RANK[i])),
535 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
536 )
537}
538
539/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
540/// first -- the census's one shared rule, so the luma and chroma histograms
541/// mean the same thing.
542fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
543 scored
544 .iter()
545 .filter(|&&(score, mode)| {
546 mode != winner
547 && score
548 < scored
549 .iter()
550 .find(|&&(_, m)| m == winner)
551 .map_or(f64::INFINITY, |&(s, _)| s)
552 })
553 .count()
554}
555
556/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
557/// four cost less. Set from the measurement in the lane report.
558const SPLIT_BLOCKS: bool = true;
559
560/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
561/// by calling [`encode_key_frame_inner`] both ways.
562pub(crate) fn split_blocks() -> bool {
563 SPLIT_BLOCKS
564}
565
566/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
567/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
568/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
569/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
570/// stream's decode output actually carries 10-bit precision instead of
571/// silently losing its low 2 bits). The encoder only ever produces values in
572/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
573/// decision); `Plane::source` narrows right back to `u8` at its two
574/// construction sites, a lossless round trip for that range.
575#[derive(Clone, Debug, PartialEq, Eq)]
576pub struct Picture {
577 /// The picture's width in luma samples.
578 pub width: usize,
579 /// Its height in luma samples.
580 pub height: usize,
581 /// The luma plane, `width * height` samples in raster order.
582 pub y: Vec<u16>,
583 /// The U plane, at half the width and half the height.
584 pub u: Vec<u16>,
585 /// The V plane, the same shape as U.
586 pub v: Vec<u16>,
587}
588
589impl Picture {
590 /// A mid-grey picture of the given size.
591 #[must_use]
592 pub fn grey(width: usize, height: usize) -> Self {
593 Self {
594 width,
595 height,
596 y: vec![128; width * height],
597 u: vec![128; width * height / 4],
598 v: vec![128; width * height / 4],
599 }
600 }
601
602 pub(crate) fn check(&self) -> Result<()> {
603 if self.width == 0
604 || !self.width.is_multiple_of(BLOCK)
605 || !self.height.is_multiple_of(BLOCK)
606 || !self.height.is_multiple_of(BLOCK)
607 {
608 return Err(Error::unsupported(
609 "AV1 encode",
610 "the picture must be a whole number of 32x32 blocks in each direction",
611 ));
612 }
613 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
614 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
615 return Err(Error::unsupported(
616 "AV1 encode",
617 "each plane must carry one sample per position at 4:2:0",
618 ));
619 }
620 Ok(())
621 }
622
623 /// What the public entry points require of the picture they are handed,
624 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
625 /// needs a whole chroma sample per two luma ones) and one sample per
626 /// position on each plane.
627 pub(crate) fn check_even(&self) -> Result<()> {
628 if self.width == 0
629 || self.height == 0
630 || !self.width.is_multiple_of(2)
631 || !self.height.is_multiple_of(2)
632 {
633 return Err(Error::unsupported(
634 "AV1 encode",
635 "the picture's width and height must each be even and nonzero",
636 ));
637 }
638 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
639 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
640 return Err(Error::unsupported(
641 "AV1 encode",
642 "each plane must carry one sample per position at 4:2:0",
643 ));
644 }
645 Ok(())
646 }
647
648 /// This picture, padded by edge replication to the next whole number of
649 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
650 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
651 /// sequence (what the inter tile writer's partition needs on top of
652 /// that). Identity (a plain clone, not a copy through the replication
653 /// loop) when the picture is already that size — the multiple-of-32 (or
654 /// -64) fast path is unchanged.
655 pub(crate) fn padded_to(&self, align: usize) -> Picture {
656 let padded_width = self.width.next_multiple_of(align);
657 let padded_height = self.height.next_multiple_of(align);
658 if padded_width == self.width && padded_height == self.height {
659 return self.clone();
660 }
661 Picture {
662 width: padded_width,
663 height: padded_height,
664 y: pad_plane(
665 &self.y,
666 self.width,
667 self.height,
668 padded_width,
669 padded_height,
670 ),
671 u: pad_plane(
672 &self.u,
673 self.width / 2,
674 self.height / 2,
675 padded_width / 2,
676 padded_height / 2,
677 ),
678 v: pad_plane(
679 &self.v,
680 self.width / 2,
681 self.height / 2,
682 padded_width / 2,
683 padded_height / 2,
684 ),
685 }
686 }
687}
688
689/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
690/// (8-bit only, unchanged this round -- widening the encoder is out of this
691/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
692/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
693/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
694/// content (every value fits both ways), so this changes no encoder output.
695#[allow(clippy::too_many_arguments)]
696fn intra_predict_u8(
697 mode: u8,
698 angle_delta: i32,
699 above: Option<&[u8]>,
700 left: Option<&[u8]>,
701 corner: Option<u8>,
702 bw: usize,
703 bh: usize,
704 enable_edge_filter: bool,
705 smooth_neighbor: bool,
706 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
707) {
708 // Three heap allocations per call became three stack buffers: this runs
709 // once per mode per trial, and an edge is at most `bw + bh` samples while
710 // a block is at most `BLOCK * BLOCK`. Same samples either way.
711 let mut above_buf = [0u16; 2 * BLOCK];
712 let mut left_buf = [0u16; 2 * BLOCK];
713 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
714 // trial of every block, and a 4x4 block writes 32 bytes of it. The
715 // predictor fills every sample it is handed, so the zeros are dead
716 // either way -- size the scratch to the block instead of to the largest
717 // block there is.
718
719 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
720 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
721 *d = u16::from(v);
722 }
723 };
724 if let Some(s) = above {
725 widen(s, &mut above_buf);
726 }
727 if let Some(s) = left {
728 widen(s, &mut left_buf);
729 }
730 let above16 = above.map(|s| &above_buf[..s.len()]);
731 let left16 = left.map(|s| &left_buf[..s.len()]);
732 let mut run = |dst16: &mut [u16]| {
733 crate::intra::predict(
734 mode,
735 angle_delta,
736 above16,
737 left16,
738 corner.map(u16::from),
739 bw,
740 bh,
741 enable_edge_filter,
742 smooth_neighbor,
743 dst16, fctx,
744 );
745 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
746 *d = s as u8;
747 }
748 };
749 let n = bw * bh;
750 if n <= 64 {
751 run(&mut [0u16; 64][..n]);
752 } else if n <= 256 {
753 run(&mut [0u16; 256][..n]);
754 } else {
755 run(&mut [0u16; BLOCK * BLOCK][..n]);
756 }
757}
758
759/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
760/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
761/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
762fn filter_intra_predict_u8(
763 mode: usize,
764 above: Option<&[u8]>,
765 left: Option<&[u8]>,
766 corner: Option<u8>,
767 side: usize,
768 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
769) {
770 let mut above_buf = [0u16; 2 * BLOCK];
771 let mut left_buf = [0u16; 2 * BLOCK];
772 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
773 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
774 *d = u16::from(v);
775 }
776 };
777 if let Some(a) = above {
778 widen(a, &mut above_buf);
779 }
780 if let Some(l) = left {
781 widen(l, &mut left_buf);
782 }
783 let mut dst16 = [0u16; BLOCK * BLOCK];
784 let n = side * side;
785 crate::intra::predict_filter_intra(
786 mode,
787 above.map(|a| &above_buf[..a.len()]),
788 left.map(|l| &left_buf[..l.len()]),
789 corner.map(u16::from),
790 side,
791 side,
792 &mut dst16[..n], fctx,
793 );
794 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
795 *d = v as u8;
796 }
797}
798
799/// Pads one plane to `(padded_width, padded_height)` by repeating its last
800/// row and column, so the block coder always sees a whole number of blocks.
801/// [`crop_plane`] undoes this on the way back out.
802fn pad_plane<T: Copy + Default>(
803 source: &[T],
804 width: usize,
805 height: usize,
806 padded_width: usize,
807 padded_height: usize,
808) -> Vec<T> {
809 let mut out = vec![T::default(); padded_width * padded_height];
810 for row in 0..padded_height {
811 let src = source[row.min(height - 1) * width..][..width].as_ref();
812 let dst = &mut out[row * padded_width..][..padded_width];
813 dst[..width].copy_from_slice(src);
814 dst[width..].fill(src[width - 1]);
815 }
816 out
817}
818
819/// The top-left `width` x `height` region of a plane that is `padded_width`
820/// wide, which is the render-size crop [`Picture::padded`]'s replication
821/// exists to let a decoder undo.
822fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
823 let mut out = Vec::with_capacity(width * height);
824 for row in 0..height {
825 out.extend_from_slice(&source[row * padded_width..][..width]);
826 }
827 out
828}
829
830/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
831/// region a decoder produces, which is the public contract for what a caller
832/// sees back — the padded planes the encoder coded against never leave this
833/// module. Identity when the reconstruction is already that size.
834pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
835 let reconstruction = &encoded.reconstruction;
836 let cropped = if reconstruction.width == width && reconstruction.height == height {
837 reconstruction.clone()
838 } else {
839 Picture {
840 width,
841 height,
842 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
843 u: crop_plane(
844 &reconstruction.u,
845 reconstruction.width / 2,
846 width / 2,
847 height / 2,
848 ),
849 v: crop_plane(
850 &reconstruction.v,
851 reconstruction.width / 2,
852 width / 2,
853 height / 2,
854 ),
855 }
856 };
857 Encoded {
858 stream: encoded.stream.clone(),
859 modes: encoded.modes.clone(),
860 inter_block_share: encoded.inter_block_share,
861 reconstruction: cropped,
862 tile: encoded.tile.clone(),
863 mi_cols: encoded.mi_cols,
864 mi_rows: encoded.mi_rows,
865 base_q_idx: encoded.base_q_idx,
866 tx_select: encoded.tx_select,
867 switchable_motion_mode: encoded.switchable_motion_mode,
868 screen: encoded.screen,
869 start_cdfs: encoded.start_cdfs.clone(),
870 next_cdfs: encoded.next_cdfs.clone(),
871 loop_filter: encoded.loop_filter,
872 loop_restoration: encoded.loop_restoration,
873 allow_intrabc: encoded.allow_intrabc,
874 cdef: encoded.cdef,
875 }
876}
877
878/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
879/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
880#[derive(Clone)]
881pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
882
883impl std::fmt::Debug for CdfSnapshot {
884 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
885 f.write_str("CdfSnapshot")
886 }
887}
888
889/// What one call to [`encode_key_frame`] produced.
890#[derive(Clone, Debug)]
891pub struct Encoded {
892 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
893 /// OBU carrying one tile.
894 pub stream: Vec<u8>,
895 /// What a decoder will produce from `stream` — the encoder's own
896 /// reconstruction, which its prediction was built on.
897 pub reconstruction: Picture,
898 /// The luma intra mode each block was coded under, in the order the blocks
899 /// are coded — raster order among the quadrants of each superblock, and
900 /// among the four 16x16 blocks of a quadrant that was split.
901 pub modes: Vec<u8>,
902 /// The fraction of this frame's 32x32 blocks that were coded inter (any
903 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
904 /// for a key frame, which has no such choice — so a caller can tell a
905 /// frame with no motion worth coding from one that never got the chance.
906 pub inter_block_share: f64,
907 /// The tile payload alone, undecorated by any OBU framing, and the frame
908 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
909 /// `crate::decode`'s tests are the only reader; a real decoder gets these
910 /// off the wire by parsing `stream`'s OBUs instead.
911 pub(crate) tile: Vec<u8>,
912 pub(crate) mi_cols: u32,
913 pub(crate) mi_rows: u32,
914 pub(crate) base_q_idx: u8,
915 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
916 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
917 /// and reading it off `stream`'s header is what `decode_stream` does. A
918 /// test that decodes `tile` directly must pass this one along, or it reads
919 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
920 /// block.
921 pub(crate) tx_select: bool,
922 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
923 /// bit that makes every eligible single-reference inter block carry a
924 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
925 /// decoding `tile` directly must pass it along or it desyncs at the
926 /// first eligible block.
927 pub(crate) switchable_motion_mode: bool,
928 /// The CDF state this frame's tile writer started from -- the defaults
929 /// for a key frame and for the first inter frame, and the previous
930 /// frame's stored tables after that. A test that decodes `tile` directly
931 /// must feed the decoder this, exactly as `decode_stream` feeds it what
932 /// the frame's `primary_ref_frame` slot holds (same class as
933 /// `tx_select`: a header bit a raw tile decode cannot guess).
934 pub(crate) start_cdfs: CdfSnapshot,
935 /// What this frame stores into the slots it refreshes (spec 7.20,
936 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
937 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
938 /// started from when it is on.
939 pub(crate) next_cdfs: CdfSnapshot,
940 /// This frame header's chosen deblocking parameters
941 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
942 /// picture the decoder produces UNDER them, so a test that decodes
943 /// `tile` directly must pass these along, exactly as it must `tx_select`
944 /// (class: test asserts against a stale header).
945 pub(crate) loop_filter: LoopFilterParams,
946 /// This frame header's chosen CDEF parameters, threaded for the same
947 /// reason as `loop_filter`.
948 pub(crate) cdef: CdefParams,
949 /// This frame header's `allow_screen_content_tools`
950 /// ([`screen_content`]) -- every intra block of the tile carries the two
951 /// palette-mode symbols under it, so a raw tile decode that guessed
952 /// `false` would desync at the first block (same class as `tx_select`).
953 pub(crate) screen: bool,
954 /// This frame header's chosen loop restoration parameters, threaded for
955 /// the same reason as `loop_filter` -- and doubly so: the per-unit
956 /// filters themselves are coded in `tile`, so a decode of it under a
957 /// stale `RESTORE_NONE` header desyncs at the first superblock.
958 pub(crate) loop_restoration: LoopRestorationParams,
959 /// This frame header's `allow_intrabc` -- every intra block of the tile
960 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
961 /// guessed `false` would desync at the first block (same class as
962 /// `screen`/`tx_select`).
963 pub(crate) allow_intrabc: bool,
964}
965
966thread_local! {
967 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
968 /// for on the last key frame encoded on this thread -- read by the gates,
969 /// which print it beside the block counts (class `gate-blind-to-feature`).
970 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
971}
972
973/// [`IBC_SHARE`] for the last key frame encoded on this thread.
974#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
975pub(crate) fn intrabc_source_share() -> f64 {
976 IBC_SHARE.with(std::cell::Cell::get)
977}
978
979thread_local! {
980 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
981 /// header offers the per-frame `allow_screen_content_tools` bit at all.
982 /// Armed once by the key frame ([`encode_key_frame_inner`], from
983 /// [`screen_content`]) and read by every header builder after it, so that
984 /// the inter frames of a screen sequence lay their headers out the same
985 /// way the sequence header the key frame wrote says they do -- a per-call
986 /// parameter would have to thread through `inter_frame_headers`' four
987 /// public entry points and every hand-built-stream test that calls them.
988 /// A sequence with no screen content leaves this false and writes exactly
989 /// the bits it wrote before this lane.
990 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
991}
992
993thread_local! {
994 /// Overrides [`screen_content`] for the calling thread, which is what the
995 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
996 /// codes every block losslessly, so both arms of a mode ablation reach
997 /// infinite PSNR and the ablation measures nothing at all (the
998 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
999 /// variable cannot do this -- the tests run in one process, in parallel.
1000 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1001}
1002
1003thread_local! {
1004 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
1005 /// under, AFTER the content gate: the pyramid, or `None` for a stream
1006 /// that stayed flat. Read by the BD gates, which print the requested and
1007 /// the effective pyramid side by side -- a screen clip requests one and
1008 /// codes flat, and that difference is the gate (class
1009 /// `gate-blind-to-feature`).
1010 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
1011 const { std::cell::Cell::new(None) };
1012}
1013
1014/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
1015#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1016pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
1017 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
1018}
1019
1020#[cfg(test)]
1021pub(crate) fn force_screen(value: Option<bool>) {
1022 SCREEN_FORCE.with(|c| c.set(value));
1023}
1024
1025pub(crate) fn arm_seq_screen(on: bool) {
1026 SEQ_SCREEN.with(|c| c.set(on));
1027}
1028
1029fn seq_screen() -> bool {
1030 SEQ_SCREEN.with(std::cell::Cell::get)
1031}
1032
1033/// How many distinct colours a 16x16 luma block may hold and still count as
1034/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
1035/// `av1_set_screen_content_options` bound is 4, which separates nothing on
1036/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
1037/// the variance floor below on the five gate clips at BOTH the native crop
1038/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
1039/// the frame is the widest-margin split of those ten rows -- every
1040/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
1041/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
1042/// native and 17.9% scaled.
1043fn screen_colors() -> usize {
1044 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1045 *N.get_or_init(|| {
1046 std::env::var("EC_AV1_SCREEN_COLORS")
1047 .ok()
1048 .and_then(|v| v.parse().ok())
1049 .unwrap_or(16)
1050 })
1051}
1052
1053/// The reciprocal of the frame area those blocks must cover, in tenths --
1054/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
1055/// 8 (an eighth) is the midpoint of the two populations
1056/// `probe_screen_detect` measures at the colour bound and variance floor
1057/// around it. `EC_AV1_SCREEN_PCT`.
1058fn screen_pct() -> usize {
1059 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1060 *N.get_or_init(|| {
1061 std::env::var("EC_AV1_SCREEN_PCT")
1062 .ok()
1063 .and_then(|v| v.parse().ok())
1064 .unwrap_or(10)
1065 })
1066}
1067
1068/// The per-pixel variance a few-colour block must clear before it counts as
1069/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
1070/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
1071/// a smooth dark film frame is all few-colour blocks and reads as a desktop
1072/// capture -- which is exactly what this detector did until 2026-09-07, when
1073/// it called BOTH real films screen content on 48/48 frames, priced every
1074/// coefficient against the default CDFs and ran the palette search over
1075/// film. `probe_screen_detect`: at 16 colours the floor takes both films
1076/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
1077/// 23.6%.
1078fn screen_var() -> u64 {
1079 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1080 *N.get_or_init(|| {
1081 std::env::var("EC_AV1_SCREEN_VAR")
1082 .ok()
1083 .and_then(|v| v.parse().ok())
1084 .unwrap_or(16)
1085 })
1086}
1087
1088/// How many frames [`screen_content`] said yes/no to, so a gate can print
1089/// whether the detector fired at all (class `gate-blind-to-feature`).
1090pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
1091 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
1092
1093/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
1094/// the distinct colours of every 16x16 block and turn the screen-content
1095/// tools on when the blocks holding between 2 and [`screen_colors`] of them
1096/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
1097/// frame. `width` is the plane's
1098/// stride, `true_*` the frame's real (decodable) extent.
1099fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
1100 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
1101 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1102 return forced;
1103 }
1104 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
1105 let on = v != "0";
1106 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1107 return on;
1108 }
1109 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
1110 let mut counted = 0usize;
1111 for by in (0..true_height).step_by(blk) {
1112 for bx in (0..true_width).step_by(blk) {
1113 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
1114 let mut seen = [false; 256];
1115 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
1116 for row in 0..h {
1117 for col in 0..w {
1118 let v = y[(by + row) * width + bx + col];
1119 sum += u64::from(v);
1120 sq += u64::from(v) * u64::from(v);
1121 if !seen[usize::from(v)] {
1122 seen[usize::from(v)] = true;
1123 colors += 1;
1124 }
1125 }
1126 }
1127 // Per-pixel variance over the block's real (edge-clipped) extent.
1128 let n = (h * w) as u64;
1129 let var = (sq - sum * sum / n) / n;
1130 if colors > 1 && colors <= limit && var > floor {
1131 counted += 1;
1132 }
1133 }
1134 }
1135 let on = counted * blk * blk * screen_pct() > true_width * true_height;
1136 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1137 on
1138}
1139
1140/// Whether this SOURCE picture reads as screen content, for a caller that has
1141/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
1142/// gates its coding pyramid on this (a desktop capture keeps the flat
1143/// one-in-one-out structure the BD gate measured it on, camera material takes
1144/// the mini-GOP). The key frame runs the same detector again when it builds
1145/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
1146/// count, so this probe undoes its own tick and leaves the gate prints
1147/// reading one detection per coded frame.
1148pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
1149 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
1150 let on = screen_content(&y, picture.width, picture.width, picture.height);
1151 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1152 on
1153}
1154
1155/// The sequence and frame headers a picture of this size is coded under: one
1156/// tile, one transform size per block, no in-loop filter parameters yet
1157/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
1158/// CDEF strengths in once the tile is coded), no CDF adaptation
1159/// and no tool the tile writer does not code.
1160///
1161/// # Errors
1162/// Returns an error when the picture is larger than the 16-bit frame size the
1163/// sequence header carries.
1164pub fn key_frame_headers(
1165 width: usize,
1166 height: usize,
1167 base_q_idx: u8,
1168) -> Result<(SequenceHeader, FrameHeader)> {
1169 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
1170}
1171
1172/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
1173/// studio (limited) range: what this crate's sequence header carried before
1174/// [`crate::encoder`]'s facade could configure it, and what
1175/// [`key_frame_headers`] still asks for.
1176fn unspecified_color_config() -> ColorConfig {
1177 ColorConfig {
1178 bit_depth: 8,
1179 mono_chrome: false,
1180 num_planes: 3,
1181 color_primaries: 2,
1182 transfer_characteristics: 2,
1183 matrix_coefficients: 2,
1184 color_range: false,
1185 subsampling_x: 1,
1186 subsampling_y: 1,
1187 chroma_sample_position: ChromaSamplePosition::Unknown,
1188 separate_uv_delta_q: false,
1189 }
1190}
1191
1192/// [`key_frame_headers`] with the sequence header's colour config named
1193/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
1194/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
1195/// which is all a player picks a colour transform from and which
1196/// [`crate::encoder::Colour`] is the facade's own name for.
1197///
1198/// # Errors
1199/// The same as [`key_frame_headers`].
1200pub(crate) fn key_frame_headers_colour(
1201 width: usize,
1202 height: usize,
1203 base_q_idx: u8,
1204 color_config: ColorConfig,
1205) -> Result<(SequenceHeader, FrameHeader)> {
1206 let bits = |n: usize| -> Result<u32> {
1207 let n = u32::try_from(n).map_err(|_| too_large())?;
1208 if n == 0 || n > 1 << 16 {
1209 return Err(too_large());
1210 }
1211 Ok((32 - (n - 1).leading_zeros()).max(1))
1212 };
1213 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
1214 let (w, h) = (width as u32, height as u32);
1215 let seq = SequenceHeader {
1216 seq_profile: 0,
1217 operating_points: vec![OperatingPoint {
1218 seq_level_idx: 8,
1219 ..OperatingPoint::default()
1220 }],
1221 frame_width_bits,
1222 frame_height_bits,
1223 max_frame_width: w,
1224 max_frame_height: h,
1225 use_128x128_superblock: false,
1226 // lane-fintra: the encoder's intra search offers the five recursive
1227 // filter-intra modes on eligible blocks, so the sequence bit is set
1228 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
1229 // off and restores the streams this encoder wrote before the lane).
1230 enable_filter_intra: filter_intra_on(),
1231 enable_intra_edge_filter: false,
1232 enable_order_hint: true,
1233 order_hint_bits: 7,
1234 enable_superres: false,
1235 // spec 5.9.19: with the sequence bit set every frame header carries
1236 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
1237 // pair for the whole frame, chosen by `crate::filter_search` -- so no
1238 // `cdef_idx` literal is coded in the tile and a frame that wants no
1239 // CDEF simply carries zero strengths.
1240 enable_cdef: true,
1241 enable_restoration: true,
1242 // SELECT (2) when this sequence's key frame detected screen content
1243 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
1244 // is then coded in every frame header, and only the frames that want
1245 // the palette syntax set it. 0 -- the forced-off form, no bit at all
1246 // -- otherwise, which is what every non-screen stream this encoder
1247 // writes still carries.
1248 seq_force_screen_content_tools: if seq_screen() {
1249 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
1250 } else {
1251 0
1252 },
1253 seq_force_integer_mv: 0,
1254 color_config,
1255 still_picture: false,
1256 reduced_still_picture_header: false,
1257 timing_info: None,
1258 decoder_model_info: None,
1259 initial_display_delay_present_flag: false,
1260 operating_point: 0,
1261 operating_point_idc: 0,
1262 frame_id_numbers_present_flag: false,
1263 delta_frame_id_length: 0,
1264 additional_frame_id_length: 0,
1265 enable_interintra_compound: false,
1266 enable_masked_compound: false,
1267 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
1268 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
1269 // header is byte-identical to the streams before this lane.
1270 enable_warped_motion: warp_on(),
1271 enable_dual_filter: false,
1272 enable_jnt_comp: false,
1273 enable_ref_frame_mvs: false,
1274 film_grain_params_present: false,
1275 };
1276 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
1277 // own (true, unpadded) width and height, not from any block-grid
1278 // alignment — a decoder derives these straight from `frame_width`/
1279 // `frame_height` below, so this must match it exactly.
1280 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
1281 let header = FrameHeader {
1282 frame_type: FrameType::Key,
1283 frame_is_intra: true,
1284 show_frame: true,
1285 error_resilient_mode: true,
1286 // The tile writer keeps the same CDF state the decoder does and
1287 // updates it in the same order, so the frame lets the decoder adapt.
1288 disable_cdf_update: false,
1289 // Nothing reads the state this frame leaves behind: a key frame always
1290 // starts from the defaults, and this encoder emits one frame.
1291 disable_frame_end_update_cdf: true,
1292 force_integer_mv: true,
1293 refresh_frame_flags: 0xFF,
1294 primary_ref_frame: PRIMARY_REF_NONE,
1295 frame_width: w,
1296 frame_height: h,
1297 upscaled_width: w,
1298 render_width: w,
1299 render_height: h,
1300 mi_cols,
1301 mi_rows,
1302 tile_info: TileInfo {
1303 uniform_spacing: true,
1304 cols: 1,
1305 rows: 1,
1306 mi_col_starts: vec![0, mi_cols],
1307 mi_row_starts: vec![0, mi_rows],
1308 tile_size_bytes: 1,
1309 ..TileInfo::default()
1310 },
1311 quantization: QuantizationParams {
1312 base_q_idx,
1313 ..QuantizationParams::default()
1314 },
1315 tx_mode: TxMode::Largest,
1316 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
1317 // intra transform below 32x32, not only 16x16 -- the set this crate
1318 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
1319 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
1320 // so a decoder honouring the header picks the same CDF the writer
1321 // used only if this is set here too, not only on the inter variant
1322 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
1323 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
1324 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
1325 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
1326 // the arithmetic coder's `rng` register from the very first 8x8-leaf
1327 // luma transform onward with no symbol value ever differing.
1328 reduced_tx_set: true,
1329 ..FrameHeader::default()
1330 };
1331 Ok((seq, header))
1332}
1333
1334/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
1335/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
1336/// 1 still holds the key frame however long the GOP runs.
1337pub const GOLDEN_SLOT: u8 = 1;
1338
1339/// The frame header for a shown inter frame that predicts from the single
1340/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
1341/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
1342/// reused verbatim: an inter frame never changes the sequence.
1343///
1344/// # Errors
1345/// Returns an error under the same conditions as [`key_frame_headers`].
1346pub fn inter_frame_headers(
1347 width: usize,
1348 height: usize,
1349 base_q_idx: u8,
1350 order_hint: u32,
1351 last_slot: u8,
1352) -> Result<(SequenceHeader, FrameHeader)> {
1353 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
1354}
1355
1356/// [`inter_frame_headers`] with the three slots named apart: the one read as
1357/// `LAST_FRAME`, the one this frame refreshes, and the one read as
1358/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
1359/// so that the frame two back is still intact in the slot this one is about
1360/// to overwrite -- read before write, spec 7.20's decode order.
1361///
1362/// # Errors
1363/// As [`inter_frame_headers`].
1364pub fn inter_frame_headers_slots(
1365 width: usize,
1366 height: usize,
1367 base_q_idx: u8,
1368 order_hint: u32,
1369 last_slot: u8,
1370 self_slot: u8,
1371 altref_slot: u8,
1372) -> Result<(SequenceHeader, FrameHeader)> {
1373 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
1374 let header = FrameHeader {
1375 frame_type: FrameType::Inter,
1376 frame_is_intra: false,
1377 show_frame: true,
1378 error_resilient_mode: false,
1379 disable_cdf_update: false,
1380 // The tile writer hands its end-of-tile tables to the next frame
1381 // (`encode_sequence_with_ctx`), so the frame stores them the way the
1382 // decoder will load them (spec 7.20).
1383 disable_frame_end_update_cdf: false,
1384 force_integer_mv: false,
1385 order_hint,
1386 primary_ref_frame: 0,
1387 refresh_frame_flags: 1 << self_slot,
1388 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
1389 // names the slot this frame both predicts from and refreshes;
1390 // GOLDEN names slot 1, which the key frame wrote when it refreshed
1391 // all eight and which no inter frame ever overwrites, so it holds
1392 // the key frame's own picture for the whole GOP.
1393 ref_frame_idx: {
1394 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
1395 idx[3] = GOLDEN_SLOT;
1396 idx[6] = altref_slot;
1397 idx
1398 },
1399 allow_high_precision_mv: false,
1400 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
1401 // lane-av1obmc: with this bit set every single-reference inter block
1402 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
1403 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
1404 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
1405 // to the OBMC knob rather than always on: with every block choosing
1406 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
1407 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
1408 // and stays byte-identical to the streams before this lane.
1409 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
1410 // `allow_warped_motion` besides -- which is what makes an eligible
1411 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
1412 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
1413 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
1414 || warp_on(),
1415 allow_warped_motion: warp_on(),
1416 use_ref_frame_mvs: false,
1417 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
1418 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
1419 // set this crate carries a table for at 16x16 (see
1420 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
1421 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
1422 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
1423 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
1424 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
1425 // path) -- with this flag set, `get_tx_set`'s intra branch returns
1426 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
1427 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
1428 reduced_tx_set: true,
1429 ..key
1430 };
1431 Ok((seq, header))
1432}
1433
1434fn too_large() -> Error {
1435 Error::unsupported(
1436 "AV1 encode",
1437 "the picture is larger than a frame size can carry",
1438 )
1439}
1440
1441/// One plane of the picture being coded, and the reconstruction being built
1442/// beside it.
1443/// What one committed 4x4 cell left behind for the coefficient contexts of
1444/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
1445/// is the same state decode.rs records.
1446#[derive(Clone, Copy, Default, PartialEq, Eq)]
1447struct CoefCtx {
1448 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
1449 level: u8,
1450 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
1451 /// the DC itself was zero (tile.rs `dc_vote`).
1452 dc: i8,
1453}
1454
1455/// One plane's coefficient contexts, committed in CODING ORDER: the search
1456/// prices partition TREES, so the neighbour state a candidate reads has to be
1457/// whatever the blocks coded before it left -- the parent's committed
1458/// neighbours for a tree's first child, the just-committed sibling for the
1459/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
1460/// writer's two running bands is what makes that fall out: a trial commits
1461/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
1462/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
1463/// to its left is exactly what the tile writer's `Neighbours` bands will hold
1464/// when it gets there.
1465///
1466/// Before this map the pricer took both contexts as zero, which is exact for
1467/// a luma transform covering its whole block and the largest remaining row of
1468/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
1469#[derive(Default)]
1470struct CoefCtxMap {
1471 cells: Vec<CoefCtx>,
1472 stride: usize,
1473 /// Whether the transforms being priced right now are SMALLER than the
1474 /// block they sit in -- a `TxMode::Select` depth split
1475 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
1476 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
1477 /// trial cannot tell, and it is what decides whether luma reads context 0
1478 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
1479 tu_split: bool,
1480}
1481
1482struct Plane<'a> {
1483 source: &'a [u8],
1484 reconstruction: Vec<u8>,
1485 width: usize,
1486 height: usize,
1487 /// The frame's true, decodable extent in this plane's own units --
1488 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
1489 /// not `width`/`height` above, which is the padded coding-surface size.
1490 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
1491 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
1492 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
1493 /// this bound, even though the padded reconstruction buffer holds real
1494 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
1495 /// those instead of stopping here is what desyncs prediction at the true
1496 /// edge.
1497 true_width: usize,
1498 true_height: usize,
1499 /// This plane's own tile's pixel bounds, in this plane's units -- the
1500 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
1501 /// prediction never reaches across a tile edge even though the
1502 /// neighbouring tile's real samples sit right there in the shared
1503 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
1504 /// leaves every edge exactly as it was before tiles existed.
1505 tile_x0: usize,
1506 tile_y0: usize,
1507 tile_x1: usize,
1508 tile_y1: usize,
1509 /// [`CoefCtxMap`]: what the blocks already committed left for the
1510 /// coefficient contexts of the ones still being priced. Sized on the
1511 /// first commit, so a plane literal does not have to know its own extent
1512 /// twice.
1513 ctx: CoefCtxMap,
1514}
1515
1516impl Plane<'_> {
1517 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
1518 /// called at every superblock of the frame-raster search with the rect
1519 /// of the tile that superblock belongs to.
1520 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
1521 self.tile_x0 = x0;
1522 self.tile_y0 = y0;
1523 self.tile_x1 = x1.min(self.width);
1524 self.tile_y1 = y1.min(self.height);
1525 }
1526 /// The reconstructed samples a block at `(x, y)` predicts from: the row
1527 /// above it, the column to its left and the sample between them, each
1528 /// missing where the block sits against an edge of the frame.
1529 ///
1530 /// `reach` says whether the samples above the block's right and below its
1531 /// left are decoded, which is what a directional mode reads into; where
1532 /// they are not, or where the frame ends first, the edge is shorter and
1533 /// the predictor repeats its last sample, exactly as the decoder's clamp
1534 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
1535 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
1536 /// a free per mode per block, on the search's hottest path -- while an
1537 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
1538 /// samples, on the caller's stack.
1539 fn edges_into<'a>(
1540 &self,
1541 x: usize,
1542 y: usize,
1543 side: usize,
1544 reach: Reach,
1545 above_buf: &'a mut [u8; 2 * BLOCK],
1546 left_buf: &'a mut [u8; 2 * BLOCK],
1547 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
1548 // Even a block's *own* edge is clamped to the true frame bound, not
1549 // just a `reach` extension: libaom's `av1_predict_intra_block`
1550 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
1551 // this block's own right/bottom to the frame edge -- from
1552 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
1553 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
1554 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
1555 // samples the row/column above/left holds before the decoder starts
1556 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
1557 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
1558 // extent straddles that edge legally (`has_half`) -- the transform
1559 // still covers the whole block, but prediction does not get to read
1560 // real reconstructed pixels past the true edge for its own row/column,
1561 // only for the padded tail it invents.
1562 let own_across = x + side.min(self.true_width.saturating_sub(x));
1563 let across = if reach.above_right {
1564 own_across + side.min(self.true_width.saturating_sub(own_across))
1565 } else {
1566 own_across
1567 }
1568 .min(self.width);
1569 let own_down = y + side.min(self.true_height.saturating_sub(y));
1570 let down = if reach.below_left {
1571 own_down + side.min(self.true_height.saturating_sub(own_down))
1572 } else {
1573 own_down
1574 }
1575 .min(self.height);
1576 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
1577 // whose own origin already sits past the true edge -- only reachable
1578 // through a partition trial priced for comparison on a split this
1579 // frame's straddling quadrant will go on to refuse (see
1580 // `a_picture_off_the_block_grid_is_refused`), never through a block
1581 // this encoder actually commits. Such a block has no true-edge
1582 // samples above or left of it at all, same as `y == 0`/`x == 0`.
1583 let across = across.min(self.tile_x1);
1584 let down = down.min(self.tile_y1);
1585 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
1586 if let Some(n) = above_n {
1587 above_buf[..n]
1588 .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
1589 }
1590 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
1591 if let Some(n) = left_n {
1592 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
1593 *d = self.reconstruction[row * self.width + x - 1];
1594 }
1595 }
1596 let corner = (x > self.tile_x0 && y > self.tile_y0)
1597 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
1598 (
1599 above_n.map(|n| &above_buf[..n]),
1600 left_n.map(|n| &left_buf[..n]),
1601 corner,
1602 )
1603 }
1604
1605 /// Codes one block under one mode without committing it: hands back the
1606 /// levels, the block the decoder would reconstruct, the squared error
1607 /// against the source and an estimate of what the levels cost in bits.
1608 fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
1609 self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx)
1610 }
1611
1612 /// [`Self::trial`] under a named transform type -- what an intra chroma
1613 /// block gets, since chroma codes no `tx_type` symbol and the decoder
1614 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
1615 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
1616 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
1617 #[allow(clippy::too_many_arguments)]
1618 /// Sum of absolute differences between the source block at `(x, y)` and a
1619 /// `side x side` prediction, as the whole number it is.
1620 ///
1621 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
1622 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
1623 /// exactly, so no add here rounds and the order of the adds cannot change
1624 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
1625 /// integer division per sample -- is what lets the row walk vectorize.
1626 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
1627 let mut sad = 0u32;
1628 for row in 0..side {
1629 let source = &self.source[(y + row) * self.width + x..][..side];
1630 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
1631 sad += u32::from(s.abs_diff(p));
1632 }
1633 }
1634 f64::from(sad)
1635 }
1636
1637 /// Squared error between the source block at `(x, y)` and a reconstruction
1638 /// of it. Exact for the same reason [`Self::block_sad`] is: the largest
1639 /// total is `255^2 * 64 * 64`, under 2^28.
1640 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
1641 let mut sse = 0u64;
1642 for row in 0..side {
1643 let source = &self.source[(y + row) * self.width + x..][..side];
1644 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..side]) {
1645 let d = u32::from(s.abs_diff(r));
1646 sse += u64::from(d * d);
1647 }
1648 }
1649 sse as f64
1650 }
1651
1652 fn trial_typed(
1653 &self,
1654 at: At,
1655 mode: u8,
1656 // This block's `angle_delta_y`/`angle_delta_uv` (spec
1657 // `read_intra_angle_info`, -3..=3), zero for every non-directional
1658 // mode -- the predictor's own `angle_delta` argument.
1659 angle_delta: i32,
1660 base_q_idx: u8,
1661 deadzone: f64,
1662 tx_type: TxType,
1663 fctx: &crate::decode::FrameCtx,
1664 ) -> Trial {
1665 let At {
1666 x, y, side, reach, ..
1667 } = at;
1668 let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]);
1669 let (above, left, corner) =
1670 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
1671 // Per-candidate scratch on the search's hottest path, so both buffers
1672 // live on the stack -- `side` is at most `BLOCK` -- rather than
1673 // costing a malloc/free pair per trial (`mc_trial` already does this).
1674 let mut prediction = [0u8; BLOCK * BLOCK];
1675 let prediction = &mut prediction[..side * side];
1676 intra_predict_u8(
1677 mode,
1678 angle_delta,
1679 above,
1680 left,
1681 corner,
1682 side,
1683 side,
1684 false,
1685 false,
1686 prediction, fctx,
1687 );
1688
1689 let mut residual = [0i32; BLOCK * BLOCK];
1690 let residual = &mut residual[..side * side];
1691 for row in 0..side {
1692 for col in 0..side {
1693 residual[row * side + col] =
1694 i32::from(self.source[(y + row) * self.width + x + col])
1695 - i32::from(prediction[row * side + col]);
1696 }
1697 }
1698 #[cfg(test)]
1699 let t = stage_start();
1700 let levels =
1701 forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
1702 // lane-av1speed2: 60% of the transform units of an inter stream carry
1703 // no coefficient at all, and the square entry point re-inflates that
1704 // case into `side * side` zeros (one allocate-and-memset per trial)
1705 // only for the sum below to add them to the prediction. The `_wh`
1706 // entry hands back the empty all-zero marker instead, and a zero
1707 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
1708 // `p` for a `u8`, so the bytes are the same.
1709 let coded = dequant_and_inverse_typed_wh(
1710 &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type,
1711 );
1712 #[cfg(test)]
1713 stage_since(2, t);
1714
1715 let reconstruction: Vec<u8> = if coded.is_empty() {
1716 prediction.to_vec()
1717 } else {
1718 prediction
1719 .iter()
1720 .zip(&coded)
1721 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1722 .collect()
1723 };
1724 let sse = self.block_sse(x, y, side, &reconstruction);
1725 // What the levels cost is priced through the same CDFs the tile writer
1726 // will code them with, so the search ranks modes -- and the partition
1727 // trial ranks trees -- by the bits they actually spend.
1728 #[cfg(test)]
1729 let t = stage_start();
1730 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
1731 // What the search used before it could price a block exactly: a
1732 // level costs its magnitude's width plus a sign and a run. Kept
1733 // reachable from the sweep so the two rate terms can be compared
1734 // on one build.
1735 levels
1736 .iter()
1737 .filter(|&&level| level != 0)
1738 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1739 .sum()
1740 } else {
1741 {
1742 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
1743 crate::tile::coeff_bits(
1744 &levels,
1745 at.set,
1746 crate::decode::q_ctx_of(base_q_idx),
1747 skip_ctx,
1748 sign_ctx,
1749 )
1750 }
1751 };
1752 #[cfg(test)]
1753 stage_since(3, t);
1754 Trial {
1755 levels,
1756 reconstruction,
1757 sse,
1758 bits,
1759 }
1760 }
1761
1762 /// [`Self::trial`] with the prediction already built, so that an inter
1763 /// block's motion-compensated prediction can go through the same
1764 /// residual/quantize/reconstruct path an intra block's does. `skip`
1765 /// takes the prediction as the reconstruction outright, coding no
1766 /// residual at all — what a `NEARESTMV` block that names no coefficients
1767 /// codes.
1768 #[allow(clippy::too_many_arguments)]
1769 fn code_from_prediction(
1770 &self,
1771 x: usize,
1772 y: usize,
1773 side: usize,
1774 prediction: &[u8],
1775 skip: bool,
1776 base_q_idx: u8,
1777 deadzone: f64,
1778 set: TxbSet,
1779 ) -> Trial {
1780 if skip {
1781 let sse = self.block_sse(x, y, side, prediction);
1782 return Trial {
1783 levels: vec![0i32; side * side],
1784 reconstruction: prediction.to_vec(),
1785 sse,
1786 bits: 0.0,
1787 };
1788 }
1789 let mut residual = [0i32; BLOCK * BLOCK];
1790 let residual = &mut residual[..side * side];
1791 for row in 0..side {
1792 for col in 0..side {
1793 residual[row * side + col] =
1794 i32::from(self.source[(y + row) * self.width + x + col])
1795 - i32::from(prediction[row * side + col]);
1796 }
1797 }
1798 #[cfg(test)]
1799 let t = stage_start();
1800 let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone);
1801 // The same all-zero shortcut [`Self::trial_typed`] takes.
1802 let coded = dequant_and_inverse_typed_wh(
1803 &levels,
1804 side,
1805 side,
1806 8,
1807 i32::from(base_q_idx),
1808 0,
1809 0,
1810 TxType::DctDct,
1811 );
1812 #[cfg(test)]
1813 stage_since(2, t);
1814 let reconstruction: Vec<u8> = if coded.is_empty() {
1815 prediction.to_vec()
1816 } else {
1817 prediction
1818 .iter()
1819 .zip(&coded)
1820 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1821 .collect()
1822 };
1823 let sse = self.block_sse(x, y, side, &reconstruction);
1824 #[cfg(test)]
1825 let t = stage_start();
1826 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
1827 levels
1828 .iter()
1829 .filter(|&&level| level != 0)
1830 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1831 .sum()
1832 } else {
1833 {
1834 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
1835 crate::tile::coeff_bits(
1836 &levels,
1837 set,
1838 crate::decode::q_ctx_of(base_q_idx),
1839 skip_ctx,
1840 sign_ctx,
1841 )
1842 }
1843 };
1844 #[cfg(test)]
1845 stage_since(3, t);
1846 Trial {
1847 levels,
1848 reconstruction,
1849 sse,
1850 bits,
1851 }
1852 }
1853
1854 /// Codes this block's luma at transform depth `depth`: the
1855 /// `(side >> depth)^2` transform units in raster order, each predicted
1856 /// from the reconstruction the units before it left behind -- exactly
1857 /// what the decoder's multi-transform-unit branch does (decode.rs
1858 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
1859 /// reconstructed on its own. Commits the result and hands back the
1860 /// block-coordinate levels, the block's squared error and what its
1861 /// coefficients cost.
1862 fn code_tx_depth(
1863 &mut self,
1864 at: At,
1865 mode: u8,
1866 angle_delta: i32,
1867 depth: usize,
1868 search: &Search, fctx: &crate::decode::FrameCtx,
1869 ) -> (Vec<i32>, f64, f64) {
1870 let At { x, y, side, reach, .. } = at;
1871 let tx = side >> depth;
1872 let n = 1usize << depth;
1873 let set = match tx {
1874 32 => TxbSet::Luma32,
1875 16 => TxbSet::Luma16,
1876 8 => TxbSet::Luma8,
1877 _ => TxbSet::Luma4,
1878 };
1879 let mut levels = vec![0i32; side * side];
1880 census_add(4, n * n);
1881 // A unit smaller than its block reads the neighbour magnitude table
1882 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
1883 self.ctx.tu_split = n > 1;
1884 let (mut sse, mut bits) = (0.0, 0.0);
1885 for tu_row in 0..n {
1886 for tu_col in 0..n {
1887 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
1888 let tu = At {
1889 x: x + col_off,
1890 y: y + row_off,
1891 side: tx,
1892 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
1893 set,
1894 };
1895 let trial = self.trial(tu, mode, angle_delta, search.base_q_idx, search.deadzone, fctx);
1896 sse += trial.sse;
1897 bits += trial.bits;
1898 self.commit(tu.x, tu.y, tx, &trial);
1899 for row in 0..tx {
1900 levels[(row_off + row) * side + col_off..][..tx]
1901 .copy_from_slice(&trial.levels[row * tx..][..tx]);
1902 }
1903 }
1904 }
1905 self.ctx.tu_split = false;
1906 (levels, sse, bits)
1907 }
1908
1909 /// Writes a trial's reconstruction back into the plane, and the
1910 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
1911 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
1912 for row in 0..side {
1913 self.reconstruction[(y + row) * self.width + x..][..side]
1914 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
1915 }
1916 self.commit_ctx(x, y, side, &trial.levels);
1917 }
1918
1919 /// Publishes one committed transform's own context over every 4x4 cell it
1920 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
1921 /// which is what the writer will read when it reaches the next block.
1922 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
1923 if self.ctx.cells.is_empty() {
1924 self.ctx.stride = self.width.div_ceil(4);
1925 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
1926 }
1927 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
1928 let state = CoefCtx {
1929 level: cul,
1930 dc: match levels[0].signum() {
1931 0 => 0,
1932 -1 => -1,
1933 _ => 1,
1934 },
1935 };
1936 let n = (side / 4).max(1);
1937 // Only up to the frame's TRUE extent: the writer's own
1938 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
1939 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
1940 // and leaves the cells past it uncoded even mid-block, so a
1941 // straddling block publishes context for its inside part only.
1942 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
1943 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
1944 for row in 0..rows {
1945 let start = (y / 4 + row) * self.ctx.stride + x / 4;
1946 let end = (start + cols).min(self.ctx.cells.len());
1947 if start < end {
1948 self.ctx.cells[start..end].fill(state);
1949 }
1950 }
1951 }
1952
1953 /// A block committed without any residual at all ([`ibc_commit`]): the
1954 /// cells it covers coded nothing, and leaving an earlier trial's state
1955 /// there would price its neighbours off a block that was never coded.
1956 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
1957 self.commit_ctx(x, y, side, &[0i32]);
1958 }
1959
1960 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
1961 /// plane reads, off what the blocks before it in coding order committed
1962 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
1963 /// the above/left neighbours coded anything (tile.rs
1964 /// `write_block_planes`), luma reads context 0 when its transform covers
1965 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
1966 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
1967 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
1968 /// the same neighbours (tile.rs `dc_sign_ctx`).
1969 ///
1970 /// A neighbour outside this plane's own TILE does not exist, exactly as
1971 /// the writer's per-tile `Neighbours` bands start blank.
1972 ///
1973 /// CLOSED (lane-av1straddle): the decisions this price changes used to
1974 /// make `decode_stream_round_trips_an_odd_size_gop` and
1975 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
1976 /// fail at 216x96. Never this map: the writer coded the phantom
1977 /// transform units of a right-edge-straddling 32x32 (tile.rs
1978 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
1979 /// like decode.rs and libaom), which libdav1d and libaom both refused
1980 /// outright while a decision change was what first walked into it.
1981 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
1982 if self.ctx.cells.is_empty() {
1983 return (0, 0);
1984 }
1985 let n = (side / 4).max(1);
1986 let (cx, cy) = (x / 4, y / 4);
1987 let (mut top, mut left) = (0u8, 0u8);
1988 let mut vote = 0i32;
1989 if y > self.tile_y0 && cy > 0 {
1990 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
1991 top |= cell.level;
1992 vote += i32::from(cell.dc);
1993 }
1994 }
1995 if x > self.tile_x0 && cx > 0 {
1996 for row in 0..n {
1997 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
1998 left |= cell.level;
1999 vote += i32::from(cell.dc);
2000 }
2001 }
2002 let skip_ctx = if set.is_chroma() {
2003 usize::from(top != 0) + usize::from(left != 0)
2004 } else if self.ctx.tu_split {
2005 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
2006 } else {
2007 0
2008 };
2009 let sign_ctx = match vote.signum() {
2010 0 => 0,
2011 -1 => 1,
2012 _ => 2,
2013 };
2014 (skip_ctx, sign_ctx)
2015 }
2016
2017 /// The source samples of one square, contiguous — what a motion search
2018 /// compares its candidates' predictions against ([`motion::search`]'s
2019 /// `source`), since [`Self::source`] itself is the whole plane, strided
2020 /// by [`Self::width`].
2021 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
2022 rows_of(self.source, self.width, x, y, side)
2023 }
2024
2025 /// The reconstructed samples of one square, so that a partition trial can
2026 /// be undone.
2027 /// The reconstructed samples of one square AND the coefficient contexts
2028 /// its cells hold, so that a partition trial can be undone whole: a
2029 /// losing trial that left its own nz/DC state behind would price the
2030 /// blocks after it off a block the tile writer never codes.
2031 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
2032 (
2033 rows_of(&self.reconstruction, self.width, x, y, side),
2034 self.ctx_rows(x, y, side),
2035 )
2036 }
2037
2038 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
2039 if self.ctx.cells.is_empty() {
2040 return Vec::new();
2041 }
2042 let n = (side / 4).max(1);
2043 (0..n)
2044 .flat_map(|row| {
2045 let start = (y / 4 + row) * self.ctx.stride + x / 4;
2046 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
2047 })
2048 .collect()
2049 }
2050
2051 /// Puts a snapshot back.
2052 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
2053 for row in 0..side {
2054 self.reconstruction[(y + row) * self.width + x..][..side]
2055 .copy_from_slice(&saved.0[row * side..][..side]);
2056 }
2057 if saved.1.is_empty() {
2058 return;
2059 }
2060 let n = (side / 4).max(1);
2061 for row in 0..n {
2062 let start = (y / 4 + row) * self.ctx.stride + x / 4;
2063 let end = (start + n).min(self.ctx.cells.len());
2064 if start < end {
2065 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
2066 }
2067 }
2068 }
2069
2070 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
2071 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
2072 /// prescreen by the identical rule rather than a second one that could
2073 /// drift from it.
2074 fn intra_scores(
2075 &self,
2076 at: At,
2077 modes: &[u8],
2078 mode_bits: &[f64; 13],
2079 lambda: f64, fctx: &crate::decode::FrameCtx,
2080 ) -> Vec<(f64, u8)> {
2081 let At {
2082 x, y, side, reach, ..
2083 } = at;
2084 let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]);
2085 let (above, left, corner) =
2086 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2087 modes
2088 .iter()
2089 .map(|&mode| {
2090 let mut prediction = vec![0u8; side * side];
2091 intra_predict_u8(
2092 mode,
2093 0,
2094 above,
2095 left,
2096 corner,
2097 side,
2098 side,
2099 false,
2100 false,
2101 &mut prediction, fctx,
2102 );
2103 let sad = self.block_sad(x, y, side, &prediction);
2104 (sad + lambda * mode_bits[usize::from(mode)], mode)
2105 })
2106 .collect()
2107 }
2108
2109 /// Codes one block under every mode the search offers (or, when
2110 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
2111 /// pre-pass plus DC) and commits the one whose squared error and
2112 /// estimated rate come out cheapest.
2113 ///
2114 /// The prediction is built once per mode regardless -- the full RD trial
2115 /// needs it too -- so ranking modes by SAD on that same prediction before
2116 /// running the expensive part (forward transform, quantize, reconstruct,
2117 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
2118 /// only to sum.
2119 fn search_block(
2120 &mut self,
2121 at: At,
2122 search: &Search,
2123 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
2124 ) -> (Vec<Coeff>, u8, i32, f64) {
2125 let At {
2126 x, y, side, reach, ..
2127 } = at;
2128 let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]);
2129 let (above, left, corner) =
2130 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2131 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
2132 // the census reports it), so summing it under the default unpruned
2133 // search is `side * side` absolute differences per mode spent on a
2134 // number no one reads.
2135 let want_sad = search.top_k.is_some() || census_on();
2136 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
2137 .modes
2138 .iter()
2139 .map(|&mode| {
2140 let mut prediction = vec![0u8; side * side];
2141 intra_predict_u8(
2142 mode,
2143 0,
2144 above,
2145 left,
2146 corner,
2147 side,
2148 side,
2149 false,
2150 false,
2151 &mut prediction, fctx,
2152 );
2153 let sad = if want_sad {
2154 self.block_sad(x, y, side, &prediction)
2155 } else {
2156 0.0
2157 };
2158 (
2159 sad + search.lambda * mode_bits[usize::from(mode)],
2160 mode,
2161 prediction,
2162 )
2163 })
2164 .collect();
2165 if let Some(k) = search.top_k {
2166 if k < scored.len() {
2167 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
2168 let dc_entry = dc_pos.map(|i| scored.remove(i));
2169 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
2170 scored.truncate(if dc_entry.is_some() {
2171 k.saturating_sub(1)
2172 } else {
2173 k
2174 });
2175 if let Some(dc_entry) = dc_entry {
2176 scored.push(dc_entry);
2177 }
2178 }
2179 }
2180 let ranking: Vec<(f64, u8)> = if census_on() {
2181 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
2182 } else {
2183 Vec::new()
2184 };
2185 census_add(0, 1);
2186 census_add(1, scored.len());
2187 let mut best: Option<(f64, u8, Trial)> = None;
2188 for (_, mode, prediction) in scored {
2189 let trial = self.code_from_prediction(
2190 x,
2191 y,
2192 side,
2193 &prediction,
2194 false,
2195 search.base_q_idx,
2196 search.deadzone,
2197 at.set,
2198 );
2199 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
2200 if best
2201 .as_ref()
2202 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
2203 {
2204 best = Some((cost, mode, trial));
2205 }
2206 }
2207 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
2208 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
2209 // directional modes each carry a -3..=3 delta, three degrees a step,
2210 // which the writer has always coded as ZERO because nothing searched
2211 // it. Refined on the winning mode only -- libaom's own ordering, and
2212 // six extra trials on the directional blocks instead of on every
2213 // block times every mode. The edges are the ones the base angle
2214 // already read (`enable_intra_edge_filter` is off in this encoder's
2215 // sequence header, so no delta changes which samples exist), and the
2216 // predictor is the decoder's, `angle_delta` argument and all.
2217 let mut angle_delta = 0i32;
2218 // Not on a screen frame: measured on the 5-row native gate, the
2219 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
2220 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
2221 // synthetic edges land on the base angles, so every delta there buys
2222 // a symbol and no prediction. Same `search.screen` gate palette and
2223 // intrabc already stand behind.
2224 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
2225 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
2226 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
2227 let mut prediction = vec![0u8; side * side];
2228 for delta in [-3i32, -2, -1, 1, 2, 3] {
2229 intra_predict_u8(
2230 mode,
2231 delta,
2232 above,
2233 left,
2234 corner,
2235 side,
2236 side,
2237 false,
2238 false,
2239 &mut prediction, fctx,
2240 );
2241 let candidate = self.code_from_prediction(
2242 x,
2243 y,
2244 side,
2245 &prediction,
2246 false,
2247 search.base_q_idx,
2248 search.deadzone,
2249 at.set,
2250 );
2251 let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
2252 - zero_bits;
2253 let cost_d = candidate.sse
2254 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
2255 if cost_d < cost {
2256 cost = cost_d;
2257 angle_delta = delta;
2258 trial = candidate;
2259 }
2260 }
2261 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
2262 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2263 }
2264 if census_on() {
2265 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
2266 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2267 }
2268 self.commit(x, y, side, &trial);
2269 (coeffs(&trial.levels, side), mode, angle_delta, cost)
2270 }
2271}
2272
2273/// Where one block sits in its plane, and how far past its own edges its
2274/// prediction may read.
2275#[derive(Clone, Copy)]
2276struct At {
2277 x: usize,
2278 y: usize,
2279 side: usize,
2280 reach: Reach,
2281 /// Which of the tile writer's coefficient tables this block's levels are
2282 /// coded with, and so which the search prices them through.
2283 set: TxbSet,
2284}
2285
2286/// Which of the samples past a block's own edges the decoder has decoded by
2287/// the time it predicts the block, and so which a directional mode may read.
2288///
2289/// The decoder derives these from its `BlockDecoded` flags, which are cleared
2290/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
2291/// that map, this reads the answer the same way libaom and rav1e do: for a
2292/// block whose transform covers it whole, whether the samples above its right
2293/// (or below its left) are decoded depends only on where the block sits inside
2294/// its 64x64 superblock, which is a pinned table per block size.
2295#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2296pub(crate) struct Reach {
2297 pub(crate) above_right: bool,
2298 pub(crate) below_left: bool,
2299}
2300
2301/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
2302/// libaom): for a block that is neither in the superblock's top row nor its
2303/// rightmost column, whether the block above and to its right is coded before
2304/// it. Indexed by the block's position in the superblock, in blocks of its own
2305/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
2306/// 128, not this crate's 64 superblock -- bit by bit from the low end.
2307const HAS_TOP_RIGHT: [&[u8]; 4] = [
2308 &[255, 85, 119, 85, 127, 85, 119, 85],
2309 &[95, 87],
2310 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
2311 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
2312 &[
2313 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
2314 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
2315 ],
2316
2317 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
2318 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
2319 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
2320 // with side 4 outside a TX4 split; without their own row they clamped
2321 // into the 8x8 table and read above-right samples the decoder has not
2322 // written yet (all-zero pixels in the bottom-right triangle of a
2323 // directional 4x4 leaf).
2324 &[
2325 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
2326 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
2327 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
2328 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
2329 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
2330 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
2331 119, 119, 119, 119, 85, 85, 85, 85,
2332 ],
2333];
2334
2335/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
2336/// left.
2337const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
2338 &[84, 16, 84, 0, 84, 16, 84, 0],
2339 &[4, 4],
2340 // has_bl_8x8 (libaom av1/common/reconintra.c)
2341 &[
2342 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
2343 84, 85, 16, 17, 84, 85, 0, 0,
2344 ],
2345
2346 // has_bl_4x4 (same source, same order).
2347 &[
2348 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
2349 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,
2350 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
2351 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,
2352 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
2353 85, 85, 0, 0, 0, 0,
2354 ],
2355];
2356
2357/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
2358/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
2359/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
2360/// rather than in raster order, so the bottom-left square's top-right
2361/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
2362/// libaom switches tables on the partition type (`get_has_tr_table`); the
2363/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
2364/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
2365/// lane-part32 r5 caught reading undecoded samples.
2366const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
2367 // has_tr_vert_16x16
2368 &[255, 0, 119, 0, 127, 0, 119, 0],
2369 // has_tr_vert_32x32
2370 &[15, 7],
2371 // has_tr_vert_8x8
2372 &[
2373 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
2374 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
2375 ],
2376];
2377
2378/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
2379const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
2380 // has_bl_vert_16x16
2381 &[254, 16, 254, 0, 254, 16, 254, 0],
2382 // has_bl_vert_32x32
2383 &[14, 14],
2384 // has_bl_vert_8x8
2385 &[
2386 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
2387 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
2388 ],
2389];
2390
2391thread_local! {
2392 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
2393 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
2394 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
2395 /// threading one bool through this crate's already twenty-argument
2396 /// `decode_block` would touch every call site instead of the two arms
2397 /// that need it.
2398 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2399}
2400
2401/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
2402pub(crate) struct VertAbGuard(bool);
2403
2404impl Drop for VertAbGuard {
2405 fn drop(&mut self) {
2406 VERT_AB_PARTITION.with(|c| c.set(self.0));
2407 }
2408}
2409
2410/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
2411/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
2412/// so no byte is retyped). Each is indexed by
2413/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
2414/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
2415/// superblock grid; on this crate's 64-pixel superblock the highest index a
2416/// shape can reach stays inside its own table, so no wrap is involved.
2417///
2418/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
2419/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
2420/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
2421/// 10 of the 21 reachable superblock positions for above-right and 7 for
2422/// below-left.
2423/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
2424const 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];
2425/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
2426const 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];
2427/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
2428const 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];
2429/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
2430const 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];
2431/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
2432const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
2433/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
2434const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
2435/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
2436const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
2437/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
2438const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
2439/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
2440const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
2441/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
2442const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
2443/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
2444const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
2445/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
2446const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
2447/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
2448const HAS_TR_32X64: [u8; 1] = [127];
2449/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
2450const HAS_BL_32X64: [u8; 1] = [0];
2451/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
2452const HAS_TR_64X32: [u8; 1] = [19];
2453/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
2454const HAS_BL_64X32: [u8; 1] = [34];
2455/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
2456const 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];
2457/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
2458const 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];
2459/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
2460const 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];
2461/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
2462const 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];
2463/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
2464const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
2465/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
2466const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
2467/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
2468const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
2469/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
2470const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
2471/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
2472const HAS_TR_16X64: [u8; 2] = [255, 127];
2473/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
2474const HAS_BL_16X64: [u8; 2] = [0, 0];
2475/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
2476const HAS_TR_64X16: [u8; 2] = [3, 1];
2477/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
2478const HAS_BL_64X16: [u8; 2] = [42, 42];
2479
2480/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
2481fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
2482 match (bw, bh) {
2483 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
2484 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
2485 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
2486 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
2487 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
2488 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
2489 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
2490 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
2491 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
2492 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
2493 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
2494 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
2495 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
2496 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
2497 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
2498 }
2499}
2500
2501impl Reach {
2502 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
2503 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
2504 /// own answer is `block` -- a different rule from the standalone-block
2505 /// tables, because a unit's neighbours are mostly its own block's
2506 /// already-reconstructed units:
2507 /// * top-right: available while the unit to the right is still inside
2508 /// the block (`col_off + tx < bw`); otherwise only the block's top row
2509 /// of units reaches past it, through the block-level answer
2510 /// (libaom's `row_off > 0` branch returns exactly
2511 /// `col_off + txw < plane_bw`).
2512 /// * bottom-left: a unit outside the block's left column has none
2513 /// (libaom returns 0 for `col_off > 0`); inside the block
2514 /// (`row_off + tx < bh`) they are the left unit's, already
2515 /// reconstructed; the bottom row falls back to the block-level answer.
2516 pub(crate) fn of_tu(
2517 bw: usize,
2518 bh: usize,
2519 col_off: usize,
2520 row_off: usize,
2521 // The unit's own width and height in pixels; equal for a square
2522 // transform, different for the rect unit a 1:4 strip's first split
2523 // produces (lane-rectsplitx r1).
2524 tx_w: usize,
2525 tx_h: usize,
2526 block: Self,
2527 ) -> Self {
2528 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
2529 // order, so both libaom predicates special-case it (lane-sb128c r10);
2530 // without this the last unit column of every chunk of a 128x64 block
2531 // predicts from a chunk libaom has not decoded yet.
2532 let wide = bw > 64;
2533 Self {
2534 above_right: if row_off > 0 {
2535 // `has_top_right`'s `row_off > 0` branch: the offset is taken
2536 // modulo the 64-wide chunk, except for the one unit whose
2537 // top-right corner is the centre of a 128x128 block.
2538 if wide {
2539 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
2540 } else {
2541 col_off + tx_w < bw
2542 }
2543 } else if col_off + tx_w < bw {
2544 true
2545 } else {
2546 block.above_right
2547 },
2548 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
2549 // `has_bottom_left`: at the left edge of a right-hand chunk
2550 // the bottom-left pixels are in the already-coded left chunk,
2551 // provided they stay inside it.
2552 (row_off % 64) + tx_h < bh.min(64)
2553 } else if col_off > 0 {
2554 false
2555 } else if row_off + tx_h < bh {
2556 true
2557 } else {
2558 block.below_left
2559 },
2560 }
2561 }
2562
2563 /// What a block of `side` samples at `(x, y)` may read past its own edges,
2564 /// in a frame of `width` by `height`.
2565 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
2566 Self {
2567 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
2568 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
2569 }
2570 }
2571
2572 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
2573 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
2574 /// block's own width for the row stride and by its own height for the
2575 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
2576 /// unlike the square [`Self::of`] which uses one `side` for everything.
2577 pub(crate) fn of_rect(
2578 bw: usize,
2579 bh: usize,
2580 x: usize,
2581 y: usize,
2582 width: usize,
2583 height: usize, fctx: &crate::decode::FrameCtx,
2584 ) -> Self {
2585 Self {
2586 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
2587 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
2588 }
2589 }
2590
2591 /// [`Self::of`] for one transform unit of a square block whose transform
2592 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
2593 /// non-zero `row_off`/`col_off`): interior units answer from the block's
2594 /// own geometry, and only a unit on the block's top row (resp. left
2595 /// column) reaches the table -- which is the BLOCK's table read at the
2596 /// BLOCK's position, never a table row for the transform's size. Letting
2597 /// the unit stand in for a block of its own size agrees with libaom for
2598 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
2599 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
2600 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
2601 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
2602 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
2603 /// the transform covering the whole block, luma): everything before the
2604 /// table lookup is that function's own early-exit ladder.
2605 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2606 let sb_mi: usize = reach_sb_px(fctx) / 4;
2607 let (mi_row, mi_col) = (y / 4, x / 4);
2608 let bw_log2 = (bw / 4).trailing_zeros() as usize;
2609 let bh_log2 = (bh / 4).trailing_zeros() as usize;
2610 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
2611 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
2612 // Top row of the superblock: the top-right pixels are in the (already
2613 // decoded) superblock above.
2614 if blk_row == 0 {
2615 return true;
2616 }
2617 // Rightmost column: they fall in the superblock to the right.
2618 if ((blk_col + 1) << bw_log2) >= sb_mi {
2619 return false;
2620 }
2621 let table = rect_reach_tables(bw, bh).0;
2622 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
2623 }
2624
2625 /// libaom `has_top_right`'s own index arithmetic:
2626 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
2627 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
2628 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
2629 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
2630 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
2631 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
2632 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
2633 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
2634 (blk_row << (5 - bw_log2)) + blk_col
2635 }
2636
2637 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
2638 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2639 let sb_mi: usize = reach_sb_px(fctx) / 4;
2640 let (mi_row, mi_col) = (y / 4, x / 4);
2641 let bw_log2 = (bw / 4).trailing_zeros() as usize;
2642 let bh_log2 = (bh / 4).trailing_zeros() as usize;
2643 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
2644 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
2645 // Leftmost column of the superblock: the bottom-left pixels are in
2646 // the left superblock iff they stay inside its height.
2647 if blk_col == 0 {
2648 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
2649 }
2650 // Bottom row (and not the leftmost column): they fall in the
2651 // superblock below, which is not decoded yet.
2652 if ((blk_row + 1) << bh_log2) >= sb_mi {
2653 return false;
2654 }
2655 let table = rect_reach_tables(bw, bh).1;
2656 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
2657 }
2658
2659 /// Marks every [`Reach::of`] made until the returned guard drops as being
2660 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
2661 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
2662 /// unaffected: libaom's own comment says vertical rectangles keep their
2663 /// non-vert table, which is what [`Reach::of_rect`] already reads.
2664 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
2665 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
2666 /// can count the sub-block work that partition creates (lane-ab16).
2667 pub(crate) fn in_vert_ab() -> bool {
2668 VERT_AB_PARTITION.with(std::cell::Cell::get)
2669 }
2670
2671 pub(crate) fn vert_ab_partition() -> VertAbGuard {
2672 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
2673 }
2674
2675 /// Neither, which is all a mode that reads no further than its own edges
2676 /// needs.
2677 pub(crate) fn none() -> Self {
2678 Self {
2679 above_right: false,
2680 below_left: false,
2681 }
2682 }
2683
2684 /// `has_top_right` for a block whose transform covers it whole: the top
2685 /// row of a superblock reads into the superblock above, which is decoded;
2686 /// the rightmost column would read into the superblock to the right, which
2687 /// is not; and everything between is the table's to answer.
2688 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2689 let (row, col, per_side) = Self::position(side, x, y, fctx);
2690 if row == 0 {
2691 return true;
2692 }
2693 if col + 1 == per_side {
2694 return false;
2695 }
2696 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
2697 // (the clamp corner-cut that used to live here is gone); sides
2698 // 16/32/64 share row 0 exactly as libaom's tables repeat.
2699 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
2700 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
2701 // -- a reach over-estimate (extra above-right reference pixels),
2702 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
2703 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
2704 // NB: named `table_row`, not `row` -- `row` above is the block's
2705 // position inside the superblock and is what the bit index below
2706 // steps by (a merge that shadowed it desynced every block size).
2707 let table_row = Self::table(side);
2708 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
2709 HAS_TOP_RIGHT_VERT[table_row]
2710 } else {
2711 HAS_TOP_RIGHT[table_row]
2712 };
2713 Self::bit(
2714 table,
2715 (row * Self::table_stride(side) + col) % (table.len() * 8),
2716 )
2717 }
2718
2719 /// `has_bottom_left` for such a block: the leftmost column of a superblock
2720 /// reads into the superblock to its left, which is decoded only as far
2721 /// down as its own bottom; the bottom row would read into the superblock
2722 /// below, which is not decoded at all; and the table answers the rest.
2723 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2724 let (row, col, per_side) = Self::position(side, x, y, fctx);
2725 if col == 0 {
2726 return row * side + side < reach_sb_px(fctx);
2727 }
2728 if row + 1 == per_side {
2729 return false;
2730 }
2731 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
2732 // (the clamp corner-cut that used to live here is gone); sides
2733 // 16/32/64 share row 0 exactly as libaom's tables repeat.
2734 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
2735 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
2736 // -- a reach over-estimate (extra above-right reference pixels),
2737 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
2738 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
2739 // NB: named `table_row`, not `row` -- `row` above is the block's
2740 // position inside the superblock and is what the bit index below
2741 // steps by (a merge that shadowed it desynced every block size).
2742 let table_row = Self::table(side);
2743 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
2744 HAS_BOTTOM_LEFT_VERT[table_row]
2745 } else {
2746 HAS_BOTTOM_LEFT[table_row]
2747 };
2748 Self::bit(
2749 table,
2750 (row * Self::table_stride(side) + col) % (table.len() * 8),
2751 )
2752 }
2753
2754 /// Where a block sits inside its superblock, in blocks of its own size,
2755 /// and how many of them a superblock is across.
2756 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
2757 let sb = reach_sb_px(fctx);
2758 ((y % sb) / side, (x % sb) / side, sb / side)
2759 }
2760
2761 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
2762 /// these tables to its compile-time maximum superblock (128, spec
2763 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
2764 /// size an encode actually uses, so a block's row in the bit index steps
2765 /// by 128 / `side` even though this crate only ever codes a 64
2766 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
2767 /// here instead indexes the wrong bit for every block size but the one
2768 /// where 64 and 128 give the same stride.
2769 fn table_stride(side: usize) -> usize {
2770 128 / side
2771 }
2772
2773 /// Which of the three block sizes the encoder codes a table row is for.
2774 fn table(side: usize) -> usize {
2775 if side == BLOCK {
2776 1
2777 } else if side == 8 {
2778 2
2779 } else if side == 4 {
2780 3
2781 } else {
2782 0
2783 }
2784 }
2785
2786 /// One bit of a table, counting from the low end of its first byte.
2787 fn bit(table: &[u8], index: usize) -> bool {
2788 (table[index / 8] >> (index % 8)) & 1 != 0
2789 }
2790}
2791
2792/// What one symbol costs against a CDF, in bits.
2793/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
2794/// search, the frame header's `allow_warped_motion` and the sequence's
2795/// `enable_warped_motion`, all three together. ON by default since
2796/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
2797/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
2798/// bits -- back off for an A/B on one build.
2799pub(crate) fn warp_on() -> bool {
2800 static ON: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
2801 !matches!(crate::envflags::var("EC_AV1_WARP").as_deref(), Ok("0") | Ok("off"))
2802 });
2803 *ON
2804}
2805
2806/// The smallest LEAF an OBMC candidate is offered for, so the census can
2807/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
2808/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
2809/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
2810///
2811/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
2812/// (12 frames, four quantizers, the standing keep table):
2813///
2814/// | min side | film 1080p | film 2160p | screen |
2815/// |---|---|---|---|
2816/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
2817/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
2818/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
2819/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
2820///
2821/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
2822/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
2823/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
2824/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
2825/// that wins the local RD on five blocks in six and loses ladder bytes is
2826/// the `local-RD-on-references` class again, not a missing footprint.
2827///
2828/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
2829/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
2830/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
2831/// loss on the 1080p film became a 0.3-point win and the other two rows went
2832/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
2833/// of the "local win, ladder loss" it was charged with was the rate weight.
2834/// It still does not meet the keep rule (two down, one flat, both columns).
2835/// The tool stays OFF by default; the upgrade path is the price, not the size
2836/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
2837/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
2838/// 1080p film up, i.e. the same disagreement between the two gates).
2839///
2840/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
2841/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
2842/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
2843/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
2844/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
2845/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
2846/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
2847/// the margin's gain are the same bytes. It stays OFF.
2848fn obmc_min_side() -> usize {
2849 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2850 *N.get_or_init(|| {
2851 std::env::var("EC_AV1_OBMC_MIN")
2852 .ok()
2853 .and_then(|v| v.parse().ok())
2854 .unwrap_or(8)
2855 })
2856}
2857
2858/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
2859/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
2860/// same frame-CDF price the coefficients of a non-screen frame are estimated
2861/// with, not the static default table.
2862/// The same price for whichever alphabet the writer will really use for this
2863/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
2864/// (`allow_warped_motion` and at least one warp sample), otherwise the
2865/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
2866/// search pay it, so the alphabet cancels out of a comparison and only its
2867/// per-value spread decides.
2868fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
2869 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
2870 return 0.0;
2871 };
2872 match warp_alphabet {
2873 true => crate::tile::motion_mode_symbol_bits(row, motion),
2874 false => crate::tile::obmc_symbol_bits(row, motion == 1),
2875 }
2876}
2877
2878/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
2879/// candidate, the header's `allow_warped_motion` and the sequence's
2880/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
2881/// native keep table, against the same build with the knob off:
2882///
2883/// | clip | warp on | off |
2884/// |---|---|---|
2885/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
2886/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
2887/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
2888///
2889/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
2890/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
2891/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
2892/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
2893/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
2894/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
2895/// this is a measured loss, not an inert knob. Same shape as the OBMC
2896/// candidate above it (`obmc_min_side`): a local RD win that does not convert
2897/// into ladder bytes.
2898///
2899/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
2900/// because a tool whose gain is local and whose cost is the rate it adds is
2901/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
2902///
2903/// | clip | warp on | off (both at lambda 0.05) |
2904/// |---|---|---|
2905/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
2906/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
2907/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
2908///
2909/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
2910/// column inside 0.1 everywhere -- which reads as a keep rather than the
2911/// 0.7/0.9 loss it was.
2912///
2913/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
2914/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
2915/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
2916/// ran the conformance shape the lambda lane deferred: every warp stream
2917/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
2918/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
2919/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
2920/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
2921/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
2922/// `allow_warped_motion` and `enable_warped_motion` back off together.
2923///
2924/// The WARPED_CAUSAL prediction of one square single-reference block: the
2925/// decoder's own warp-sample walk (`decode::find_samples` +
2926/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
2927/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
2928/// grid -- never a second implementation of any of the three. `None` when the
2929/// block would code no motion_mode symbol at all, when it has no warp sample
2930/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
2931/// or when the projection is not filter-representable (the decoder would then
2932/// predict translationally, so the mode is pure cost).
2933#[allow(clippy::too_many_arguments)]
2934fn warp_prediction(
2935 grid: &MiGrid,
2936 (mi_row, mi_col): (usize, usize),
2937 (mi_rows, mi_cols): (usize, usize),
2938 (x, y): (usize, usize),
2939 side: usize,
2940 mv: (i32, i32),
2941 ref_frame: i8,
2942 ref_planes: [(&[u16], usize, usize, usize); 3],
2943 fctx: &crate::decode::FrameCtx,
2944) -> Option<[Vec<u8>; 3]> {
2945 let n4 = side / 4;
2946 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
2947 return None;
2948 }
2949 let mut samples = crate::decode::find_samples(
2950 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
2951 );
2952 if samples.is_empty() {
2953 return None;
2954 }
2955 if samples.len() > 1 {
2956 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
2957 }
2958 let params = crate::warp::find_projection(
2959 &samples,
2960 side as i32,
2961 side as i32,
2962 mv.1,
2963 mv.0,
2964 mi_row as i32,
2965 mi_col as i32,
2966 )?;
2967 let mut pred = [
2968 vec![0u16; side * side],
2969 vec![0u16; side * side / 4],
2970 vec![0u16; side * side / 4],
2971 ];
2972 // The translational prediction first, exactly as the decoder builds it,
2973 // then the affine one over the planes whose OWN block is at least 8x8
2974 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
2975 // 4x4 chroma stays translational).
2976 for (i, r) in ref_planes.into_iter().enumerate() {
2977 let luma_plane = i == 0;
2978 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
2979 let s = if luma_plane { side } else { side / 2 };
2980 mc::predict(
2981 r.0,
2982 r.1,
2983 r.2,
2984 r.3,
2985 mv_to_q4(px, mv.1, luma_plane),
2986 mv_to_q4(py, mv.0, luma_plane),
2987 s,
2988 s,
2989 &mut pred[i],
2990 fctx,
2991 );
2992 if crate::decode::warp_plane_allowed(s, s) {
2993 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
2994 crate::warp::warp_affine(
2995 &params,
2996 r.0,
2997 r.2 as i32,
2998 r.3 as i32,
2999 r.1 as i32,
3000 &mut pred[i],
3001 px as i32,
3002 py as i32,
3003 cside,
3004 cside,
3005 cside,
3006 sub,
3007 sub,
3008 fctx,
3009 );
3010 }
3011 }
3012 let [py_buf, pu_buf, pv_buf] = pred;
3013 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
3014 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
3015}
3016
3017pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
3018 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
3019 let width = cdf[symbol] - low;
3020 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
3021 // 32769 prices a symbol can carry; the `log2` behind each is computed
3022 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
3023 // profile -- this function is called for every symbol of every candidate
3024 // the RD search prices). Each entry is exactly the expression this used
3025 // to evaluate, so every price is bit-identical.
3026 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
3027 PRICES.get_or_init(|| {
3028 (0..=32768u32)
3029 .map(|w| -(f64::from(w) / 32768.0).log2())
3030 .collect()
3031 })[usize::from(width)]
3032}
3033
3034/// What the tile writer spends to say a block is coded in each of the thirteen
3035/// modes, given the modes of the blocks above it and to its left: the luma mode
3036/// symbol against the CDF those two neighbours pick, the angle delta a
3037/// directional mode carries, and the chroma mode symbol, whose CDF the luma
3038/// mode itself indexes.
3039///
3040/// Without this the search is blind to what a mode costs to name, which is not
3041/// a rounding error: a directional mode on a picture that does not run that way
3042/// is a rate loss the squared error never sees.
3043/// Codes one square of the picture as a single block: searches the luma mode,
3044/// codes both chroma planes DC, and hands back the block and what it cost --
3045/// squared error plus lambda times the bits its symbols spend.
3046/// How many halvings of a `side`-square block's transform the `tx_depth`
3047/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
3048/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
3049fn max_tx_depth(side: usize) -> usize {
3050 match side {
3051 8 => 1,
3052 16 | 32 => 2,
3053 _ => 0,
3054 }
3055}
3056
3057/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
3058/// Priced at context row 0 -- the writer picks the real row from its
3059/// neighbours' transform sizes, which the search has no view of; the term is
3060/// the same for every depth of one block either way, so it only shifts the
3061/// depth-0-versus-split margin, never the ordering between two splits.
3062fn tx_depth_bits(side: usize, depth: usize) -> f64 {
3063 match side {
3064 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
3065 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
3066 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
3067 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
3068 }
3069}
3070
3071/// How many blocks resolved to each `tx_depth`, the fire count that says
3072/// whether the depth search below reaches its candidates at all.
3073static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
3074 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
3075
3076/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
3077/// to its own encode.
3078#[cfg(test)]
3079pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
3080 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
3081}
3082
3083/// How many inter blocks resolved to each var-tx depth (0 = one transform
3084/// over the whole block, 1 = its four halves), the fire count a gate prints
3085/// to see the split search reach its candidates at all. Indexed
3086/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
3087/// says which of the four block classes the split reaches -- the 32x32 root
3088/// and the compound blocks are this lane's two new ones.
3089static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
3090 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
3091
3092/// Whether a 32x32 inter winner searches its own var-tx depth (the four
3093/// 16x16 units against the flat transform) instead of coding depth 0 blind.
3094/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
3095///
3096/// Rejected three times on the bars rows of the native gate (flat to +0.3).
3097/// lane-av1resweep re-judged it on the two REAL film crops at
3098/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
3099/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
3100///
3101/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
3102/// |---|---|---|---|
3103/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
3104/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
3105/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
3106/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
3107/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
3108///
3109/// The bars rows are ~90% zero-intra-cost cells, so the split never had
3110/// residual to reach there -- the tool was being judged on content that
3111/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
3112fn tx32_depth_search() -> bool {
3113 static ON: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
3114 !matches!(crate::envflags::var("EC_AV1_TX32_DEPTH").as_deref(), Ok("0") | Ok("off"))
3115 });
3116 *ON
3117}
3118
3119/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
3120/// trial units have to be predicted from BOTH references
3121/// ([`mc_trial_compound`]) or the split would re-predict them by single-
3122/// reference translation, which is not what the decoder reconstructs.
3123/// ON by default (the table on [`tx32_depth_search`]: on real film it is
3124/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
3125/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
3126/// `EC_AV1_COMP_VARTX`.
3127fn compound_var_tx() -> bool {
3128 static ON: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
3129 !matches!(crate::envflags::var("EC_AV1_COMP_VARTX").as_deref(), Ok("0") | Ok("off"))
3130 });
3131 *ON
3132}
3133
3134/// How many 32x32-and-below inter blocks each reference frame won, indexed by
3135/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
3136/// fire count a gate prints to see an extra reference reach a block at all
3137/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
3138/// chosen is a pyramid that costs bytes and buys nothing).
3139static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
3140 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
3141
3142/// Reads [`REF_FRAME_HITS`] and zeroes it.
3143#[cfg(test)]
3144pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
3145 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
3146}
3147
3148/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
3149#[cfg(test)]
3150pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
3151 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
3152}
3153
3154/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
3155/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
3156/// is one flag, depth 1 is a split root plus one unsplit flag per child
3157/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
3158/// or a 4x4 sub-size).
3159fn txfm_split_bits(side: usize, depth: usize) -> f64 {
3160 let max_tx = side.min(64);
3161 let ctx = |tx: usize| {
3162 crate::decode::txfm_partition_ctx_rect(
3163 crate::decode::TXFM_CTX_INIT,
3164 crate::decode::TXFM_CTX_INIT,
3165 side,
3166 tx,
3167 tx,
3168 )
3169 };
3170 if depth == 0 {
3171 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
3172 }
3173 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
3174 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
3175}
3176
3177/// The inter block's own var-tx decision, once its motion vector is settled:
3178/// its residual as ONE transform over the whole block, or as the four
3179/// transforms of half the side the tree's first halving names. The prediction
3180/// is the same motion compensation either way, so the split trial
3181/// re-transforms the identical residual in four pieces -- it wins where four
3182/// small transforms carry a locally varying residual cheaper than one big
3183/// one. Commits the winner into `luma` and hands back its block-coordinate
3184/// levels, the depth the writer codes and the cost the winner adds to (or
3185/// takes off) the caller's already-computed flat cost.
3186///
3187/// Only for a block wholly inside the frame: past the true edge the reader's
3188/// var-tx recursion skips the units that fall outside
3189/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
3190/// leave the residual units this writes unpaired.
3191#[allow(clippy::too_many_arguments)]
3192fn commit_inter_luma(
3193 luma: &mut Plane,
3194 (x, y): (usize, usize),
3195 side: usize,
3196 mv: (i32, i32),
3197 reference: (&[u16], usize, usize, usize),
3198 search: &Search,
3199 flat: &Trial,
3200 skip: bool,
3201 // A COMPOUND winner's second half: the vector and reference planes the
3202 // trial units are blended from ([`mc_trial_compound`], the decoder's own
3203 // `comp_group_idx == 0` average). `None` is the single-reference block.
3204 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
3205 fctx: &crate::decode::FrameCtx,
3206) -> (Vec<i32>, u8, f64) {
3207 let eligible = tx_select()
3208 && tx_select_inter()
3209 && !skip
3210 && side >= 16
3211 && (second.is_none() || compound_var_tx())
3212 && (side < BLOCK || tx32_depth_search())
3213 && x + side <= luma.true_width
3214 && y + side <= luma.true_height;
3215 if !eligible {
3216 luma.commit(x, y, side, flat);
3217 return (flat.levels.clone(), 0, 0.0);
3218 }
3219 let tx = side / 2;
3220 let set = if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter };
3221 let mut levels = vec![0i32; side * side];
3222 let (mut sse, mut bits) = (0.0, 0.0);
3223 let mut units = Vec::with_capacity(4);
3224 // The split units are smaller than their block, so their `txb_skip`
3225 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
3226 // each unit's own commit publishes what the next one reads, coding order.
3227 luma.ctx.tu_split = true;
3228 for tu_row in 0..2 {
3229 for tu_col in 0..2 {
3230 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
3231 let trial = match second {
3232 Some((mv1, ref1)) => mc_trial_compound(
3233 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
3234 search.base_q_idx, search.deadzone, set, fctx,
3235 ),
3236 None => mc_trial(
3237 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
3238 reference.3, false, search.base_q_idx, search.deadzone, set, fctx,
3239 ),
3240 };
3241 sse += trial.sse;
3242 bits += trial.bits;
3243 for row in 0..tx {
3244 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
3245 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3246 }
3247 units.push((tu_x, tu_y, trial));
3248 }
3249 }
3250 luma.ctx.tu_split = false;
3251 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));
3252 let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0));
3253 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
3254 if split_cost < flat_cost {
3255 for (tu_x, tu_y, trial) in &units {
3256 luma.commit(*tu_x, *tu_y, tx, trial);
3257 }
3258 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3259 return (levels, 1, split_cost - flat_cost);
3260 }
3261 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3262 luma.commit(x, y, side, flat);
3263 (flat.levels.clone(), 0, 0.0)
3264}
3265
3266/// The largest distinct-colour count a block may hold and still be offered a
3267/// palette candidate at all: past it the k-means quantisation costs more
3268/// error than the map saves rate, and every trial is wasted wall.
3269///
3270/// Swept on the gate's own screen capture (lane-av1pal2, the
3271/// `unswept-decision-constants` class): 32 (the value this lane inherited)
3272/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
3273/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
3274/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
3275/// binds on nothing this content holds. 128 ships: best BD against both
3276/// references and no wall cost at all (6.1s, the same as at 32, because the
3277/// blocks it newly admits are ones the RD then keeps).
3278/// `EC_AV1_PAL_MAXCOLORS`.
3279fn palette_max_colors() -> usize {
3280 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3281 *N.get_or_init(|| {
3282 std::env::var("EC_AV1_PAL_MAXCOLORS")
3283 .ok()
3284 .and_then(|v| v.parse().ok())
3285 .unwrap_or(128)
3286 })
3287}
3288
3289/// The palettes worth trying for one block's luma, in the shape libaom's
3290/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
3291/// distinct colours takes them ALL (the prediction is then exact and the
3292/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
3293/// one-dimensional Lloyd iteration seeded evenly across its range -- both
3294/// offered, because which wins is an RD question the caller answers.
3295/// `block` is `side*side` source samples, row-major.
3296fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
3297 let mut histogram = [0u32; 256];
3298 for &v in block {
3299 histogram[usize::from(v)] += 1;
3300 }
3301 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
3302 if present.len() < 2 {
3303 return Vec::new();
3304 }
3305 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
3306 let mut base = [0u16; 8];
3307 base[..colors.len()].copy_from_slice(colors);
3308 let map = block
3309 .iter()
3310 .map(|&v| {
3311 colors
3312 .iter()
3313 .enumerate()
3314 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
3315 .map(|(i, _)| i as u8)
3316 .expect("a palette holds at least two colours")
3317 })
3318 .collect();
3319 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
3320 };
3321 if present.len() <= 8 {
3322 return vec![exact(&present)];
3323 }
3324 if present.len() > palette_max_colors() {
3325 return Vec::new();
3326 }
3327 let (lo, hi) = (
3328 i32::from(present[0]),
3329 i32::from(present[present.len() - 1]),
3330 );
3331 let mut out = Vec::with_capacity(2);
3332 for n in [8usize, 4] {
3333 // Even seeding across the block's own range, then four Lloyd passes
3334 // over the histogram (256 bins, not `side*side` pixels).
3335 let mut centres: Vec<f64> = (0..n)
3336 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
3337 .collect();
3338 for _ in 0..4 {
3339 let mut sums = vec![0f64; n];
3340 let mut counts = vec![0u32; n];
3341 for (v, &count) in histogram.iter().enumerate() {
3342 if count == 0 {
3343 continue;
3344 }
3345 let k = (0..n)
3346 .min_by(|&a, &b| {
3347 (centres[a] - v as f64)
3348 .abs()
3349 .total_cmp(&(centres[b] - v as f64).abs())
3350 })
3351 .expect("n >= 2");
3352 sums[k] += (v as u32 * count) as f64;
3353 counts[k] += count;
3354 }
3355 for k in 0..n {
3356 if counts[k] > 0 {
3357 centres[k] = sums[k] / f64::from(counts[k]);
3358 }
3359 }
3360 }
3361 let mut colors: Vec<u16> = centres
3362 .iter()
3363 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
3364 .collect();
3365 colors.sort_unstable();
3366 colors.dedup();
3367 if colors.len() >= 2 {
3368 out.push(exact(&colors));
3369 }
3370 }
3371 out
3372}
3373
3374#[allow(clippy::too_many_arguments)]
3375// ---------------------------------------------------------------------------
3376// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
3377// validity). A key frame that detected screen content and finds enough exact
3378// repeats in its own source sets `allow_intrabc`, which the spec forces every
3379// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
3380// its place when the copied blocks pay back the deblock/CDEF/LR the frame
3381// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
3382// ---------------------------------------------------------------------------
3383
3384/// Whether intra block copy is offered at all. **Off by default** --
3385/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
3386/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
3387/// but on the gate's real screen capture it MEASURED WORSE: setting
3388/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
3389/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
3390/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
3391/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
3392/// that detected no screen content.
3393fn intrabc_enabled() -> bool {
3394 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
3395 return forced;
3396 }
3397 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3398 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
3399}
3400
3401thread_local! {
3402 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
3403 /// probe runs both arms in one process, and the suite is one process, so
3404 /// an environment variable cannot separate them (same reason
3405 /// [`SCREEN_FORCE`] exists).
3406 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
3407}
3408
3409#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3410pub(crate) fn force_intrabc(value: Option<bool>) {
3411 INTRABC_FORCE.with(|c| c.set(value));
3412}
3413
3414/// How many of a screen frame's 16x16 blocks must have an exact repeat
3415/// somewhere else in the source before `allow_intrabc` is worth the in-loop
3416/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
3417/// constant class: `probe_intrabc_threshold` measures the arm at several
3418/// values.
3419fn intrabc_pct() -> usize {
3420 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3421 *N.get_or_init(|| {
3422 std::env::var("EC_AV1_INTRABC_PCT")
3423 .ok()
3424 .and_then(|v| v.parse().ok())
3425 .unwrap_or(10)
3426 })
3427}
3428
3429/// The pixel grid intrabc source positions are hashed on
3430/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
3431/// which keeps the block-hash table (and so the search) linear in the frame
3432/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
3433/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
3434/// bilinear interpolation decode.rs applies but this encoder does not.
3435fn intrabc_step() -> usize {
3436 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3437 *N.get_or_init(|| {
3438 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
3439 .ok()
3440 .and_then(|v| v.parse().ok())
3441 .unwrap_or(4);
3442 if n % 2 == 0 { n.max(2) } else { 4 }
3443 })
3444}
3445
3446/// The side of the luma square the block-hash table is keyed on.
3447const IBC_HASH: usize = 16;
3448
3449/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
3450/// the current one the source's bottom-right corner must already be.
3451const INTRABC_DELAY_SB64: i32 = 4;
3452
3453/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
3454fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
3455 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
3456 for row in 0..IBC_HASH {
3457 let base = (y + row) * width + x;
3458 for &v in &plane[base..base + IBC_HASH] {
3459 h ^= u64::from(v);
3460 h = h.wrapping_mul(0x100_0000_01b3);
3461 }
3462 }
3463 h
3464}
3465
3466/// Every `intrabc_step()`-aligned position of `plane` inside
3467/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
3468fn ibc_index(
3469 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
3470 plane: &[u8],
3471 width: usize,
3472 (x0, y0): (usize, usize),
3473 (x1, y1): (usize, usize),
3474) {
3475 let step = intrabc_step();
3476 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
3477 return;
3478 }
3479 let mut y = y0.next_multiple_of(step);
3480 while y + IBC_HASH <= y1 {
3481 let mut x = x0.next_multiple_of(step);
3482 while x + IBC_HASH <= x1 {
3483 table
3484 .entry(ibc_hash(plane, width, x, y))
3485 .or_default()
3486 .push((x as u32, y as u32));
3487 x += step;
3488 }
3489 y += step;
3490 }
3491}
3492
3493/// Whether `screen`-detected source `y` repeats itself enough to be worth
3494/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
3495/// content appears at some other position, against [`intrabc_pct`]. Returns
3496/// the share as well, for the gate's own print.
3497fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
3498 if true_width < 4 * 64 || true_height < 2 * 64 {
3499 return (false, 0.0);
3500 }
3501 let mut table = std::collections::HashMap::new();
3502 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
3503 let (mut total, mut matched) = (0usize, 0usize);
3504 let mut by = 0;
3505 while by + IBC_HASH <= true_height {
3506 let mut bx = 0;
3507 while bx + IBC_HASH <= true_width {
3508 total += 1;
3509 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
3510 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
3511 matched += 1;
3512 }
3513 }
3514 bx += IBC_HASH;
3515 }
3516 by += IBC_HASH;
3517 }
3518 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
3519 (share * 100.0 >= intrabc_pct() as f64, share)
3520}
3521
3522/// One tile's intrabc search state: a block-hash table over the part of the
3523/// tile's own reconstruction that is already final (whole superblock rows --
3524/// the in-loop filters are off on this frame, so a coded superblock row never
3525/// changes again), plus the last DV chosen, which the RD price uses as its
3526/// predictor estimate.
3527struct Ibc {
3528 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
3529 /// source repeats exactly where a lossily coded reconstruction only
3530 /// nearly does, so an exact-match table over the reconstruction finds
3531 /// almost nothing. The candidate is then SCORED against the
3532 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
3533 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
3534 /// The tile's own luma rect, in samples.
3535 tile: (usize, usize, usize, usize),
3536 /// The DV the previous intrabc block of this tile took -- the *estimate*
3537 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
3538 /// against. The writer computes the true predictor off its own mi grid
3539 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
3540 /// a slightly mispriced candidate, never a wrong bitstream.
3541 last_dv: Option<(i32, i32)>,
3542 /// How many blocks took intrabc, and how many hash lookups found at least
3543 /// one valid candidate -- the gate's own fire counts.
3544 hits: usize,
3545 lookups: usize,
3546 found: usize,
3547}
3548
3549impl Ibc {
3550 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
3551 let mut table = std::collections::HashMap::new();
3552 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
3553 Self {
3554 table,
3555 tile,
3556 last_dv: None,
3557 hits: 0,
3558 lookups: 0,
3559 found: 0,
3560 }
3561 }
3562
3563 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
3564 /// (1/8 pel), with this lane's own extra restriction on top: the source
3565 /// must lie entirely in a COMPLETED superblock row, which is exactly the
3566 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
3567 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
3568 /// wavefront's own diagonal) are legal and not searched; the upgrade path
3569 /// is to index the current row's finished superblocks too.
3570 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
3571 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
3572 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
3573 return false;
3574 }
3575 let (tx0, ty0, tx1, ty1) = (
3576 self.tile.0 as i32,
3577 self.tile.1 as i32,
3578 self.tile.2 as i32,
3579 self.tile.3 as i32,
3580 );
3581 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
3582 let (w, h) = (w as i32, h as i32);
3583 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
3584 return false;
3585 }
3586 let active_sb_row = (y as i32 - ty0) >> 6;
3587 let active_sb_col = (x as i32 - tx0) >> 6;
3588 let src_sb_row = (sy + h - 1 - ty0) >> 6;
3589 let src_sb_col = (sx + w - 1 - tx0) >> 6;
3590 // This lane's own restriction (see the doc comment).
3591 if src_sb_row >= active_sb_row {
3592 return false;
3593 }
3594 let total = ((tx1 - tx0 - 1) >> 6) + 1;
3595 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64
3596 {
3597 return false;
3598 }
3599 // libaom's wavefront: only the top-left cone of the frame is legal.
3600 let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row);
3601 src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf
3602 }
3603}
3604
3605/// How many block searches ran, how many found at least one VALID candidate,
3606/// and how many won on rate-distortion -- the hash hit rate a gate prints
3607/// (class `gate-blind-to-feature`: "the search ran" and "the search found
3608/// something" and "the block took it" are three different claims).
3609static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
3610 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
3611
3612impl Drop for Ibc {
3613 fn drop(&mut self) {
3614 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
3615 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
3616 }
3617 }
3618}
3619
3620/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
3621/// its own encode.
3622#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3623pub(crate) fn take_intrabc_search() -> [usize; 3] {
3624 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
3625}
3626
3627/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
3628/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
3629/// infers rather than codes.
3630fn dv_component_bits(diff: i32) -> f64 {
3631 let z = diff.unsigned_abs() as i32 - 1;
3632 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
3633 let class = mv_class_of(z);
3634 bits += symbol_bits(&cdf::MV_CLASS, class);
3635 let local = z - mv_class_base(class);
3636 if class == 0 {
3637 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
3638 } else {
3639 let d = local >> 3;
3640 for i in 0..class {
3641 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
3642 }
3643 }
3644 bits
3645}
3646
3647/// What one block vector costs against `pred`, plus the `skip` and
3648/// `use_intrabc` flags the block carries and the ordinary intra block does
3649/// not pay in this currency.
3650fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
3651 let diff = (dv.0 - pred.0, dv.1 - pred.1);
3652 let joint = match (diff.0 != 0, diff.1 != 0) {
3653 (false, false) => 0,
3654 (false, true) => 1,
3655 (true, false) => 2,
3656 (true, true) => 3,
3657 };
3658 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
3659 if diff.0 != 0 {
3660 bits += dv_component_bits(diff.0);
3661 }
3662 if diff.1 != 0 {
3663 bits += dv_component_bits(diff.1);
3664 }
3665 bits
3666}
3667
3668/// The squared error of copying the `side`-square block at `(sx, sy)` of each
3669/// plane's reconstruction onto the source block at `(x, y)`, luma and both
3670/// chroma planes together -- what an intrabc block's whole (residual-free)
3671/// distortion is.
3672fn ibc_sse(
3673 luma: &Plane,
3674 chroma: &[Plane; 2],
3675 (x, y): (usize, usize),
3676 (sx, sy): (usize, usize),
3677 side: usize,
3678) -> f64 {
3679 let mut sse = 0.0f64;
3680 for row in 0..side {
3681 let src = &luma.source[(y + row) * luma.width + x..][..side];
3682 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..side];
3683 for (&s, &r) in src.iter().zip(rec) {
3684 let d = f64::from(i32::from(s) - i32::from(r));
3685 sse += d * d;
3686 }
3687 }
3688 let half = side / 2;
3689 for plane in chroma {
3690 for row in 0..half {
3691 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..half];
3692 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..half];
3693 for (&s, &r) in src.iter().zip(rec) {
3694 let d = f64::from(i32::from(s) - i32::from(r));
3695 sse += d * d;
3696 }
3697 }
3698 }
3699 sse
3700}
3701
3702/// Copies the `side`-square block at `(sx, sy)` of each plane's
3703/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
3704/// since it carries no residual (`skip`). Full-pel in both planes by
3705/// construction ([`intrabc_step`] keeps every DV even), which is what makes
3706/// this a plain copy where decode.rs runs the bilinear kernel over the same
3707/// samples.
3708fn ibc_commit(
3709 luma: &mut Plane,
3710 chroma: &mut [Plane; 2],
3711 (x, y): (usize, usize),
3712 (sx, sy): (usize, usize),
3713 side: usize,
3714) {
3715 for row in 0..side {
3716 let from = (sy + row) * luma.width + sx;
3717 let to = (y + row) * luma.width + x;
3718 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
3719 luma.reconstruction[to..to + side].copy_from_slice(&copied);
3720 }
3721 let half = side / 2;
3722 for plane in chroma {
3723 for row in 0..half {
3724 let from = (sy / 2 + row) * plane.width + sx / 2;
3725 let to = (y / 2 + row) * plane.width + x / 2;
3726 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
3727 plane.reconstruction[to..to + half].copy_from_slice(&copied);
3728 }
3729 plane.commit_ctx_zero(x / 2, y / 2, half);
3730 }
3731 luma.commit_ctx_zero(x, y, side);
3732}
3733
3734/// Searches this block's own DV: every hash-table position whose 16x16 luma
3735/// square equals the block's source square, plus the previous block's DV as a
3736/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
3737/// the winning `(dv, cost)`, or `None` when nothing valid was found.
3738fn ibc_search(
3739 ibc: &mut Ibc,
3740 luma: &Plane,
3741 chroma: &[Plane; 2],
3742 (x, y): (usize, usize),
3743 side: usize,
3744 lambda: f64,
3745) -> Option<((i32, i32), f64, (usize, usize))> {
3746 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
3747 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
3748 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
3749 let dv = (
3750 (sy as i32 - y as i32) * 8,
3751 (sx as i32 - x as i32) * 8,
3752 );
3753 if !ibc.dv_valid(x, y, side, side, dv) {
3754 return;
3755 }
3756 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
3757 if best.as_ref().is_none_or(|b| cost < b.1) {
3758 *best = Some((dv, cost, (sx, sy)));
3759 }
3760 };
3761 ibc.lookups += 1;
3762 let key = ibc_hash(luma.source, luma.width, x, y);
3763 // The table is filled in raster order, so the entries BEFORE this block's
3764 // own position are exactly the already-coded ones -- and the nearest of
3765 // them costs the fewest DV bits. Walking backwards from the block's own
3766 // slot is what makes the search look up-and-left; taking the newest
3767 // entries outright only ever finds candidates below and to the right,
3768 // every one of which `dv_valid` rejects.
3769 let hits: Vec<(u32, u32)> = ibc
3770 .table
3771 .get(&key)
3772 .map(|h| {
3773 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
3774 h[..end].iter().rev().take(32).copied().collect()
3775 })
3776 .unwrap_or_default();
3777 for (hx, hy) in hits {
3778 consider(&*ibc, hx as usize, hy as usize, &mut best);
3779 }
3780 if let Some(dv) = ibc.last_dv {
3781 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
3782 if sx >= 0 && sy >= 0 {
3783 consider(&*ibc, sx as usize, sy as usize, &mut best);
3784 }
3785 }
3786 if best.is_some() {
3787 ibc.found += 1;
3788 }
3789 best
3790}
3791
3792fn code_square(
3793 luma: &mut Plane,
3794 chroma: &mut [Plane; 2],
3795 (x, y): (usize, usize),
3796 side: usize,
3797 search: &Search,
3798 mode_bits: &[f64; 13],
3799 // The frame header's `tx_mode == TxMode::Select`: the block then searches
3800 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
3801 // transform over its whole side.
3802 tx_select: bool,
3803 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
3804 // header did not set `allow_intrabc`.
3805 ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx,
3806) -> (BlockCoeffs, f64) {
3807 let (luma_set, chroma_set) = if side == BLOCK {
3808 (TxbSet::Luma32, TxbSet::Chroma16)
3809 } else if side == 8 {
3810 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
3811 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
3812 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
3813 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
3814 // (this branch is still unreached), so leaving `Chroma8` here would
3815 // silently wire the wrong table the moment one does; `Chroma4` is
3816 // what a real caller needs.
3817 (TxbSet::Luma8, TxbSet::Chroma4)
3818 } else {
3819 (TxbSet::Luma16, TxbSet::Chroma8)
3820 };
3821 let at = At {
3822 x,
3823 y,
3824 side,
3825 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
3826 set: luma_set,
3827 };
3828 let (mut luma_coeffs, mode, angle_delta, mut cost) =
3829 luma.search_block(at, search, mode_bits, fctx);
3830 // The depth search runs on the mode the whole-block transform picked --
3831 // libaom's own ordering, and the reason it costs one extra pass per depth
3832 // rather than one per (mode, depth) pair.
3833 let mut tx_depth = 0u8;
3834 if tx_select && max_tx_depth(side) > 0 {
3835 let mut best = (
3836 cost + search.lambda * tx_depth_bits(side, 0),
3837 0usize,
3838 luma.snapshot(x, y, side),
3839 luma_coeffs,
3840 );
3841 for depth in 1..=max_tx_depth(side) {
3842 let (levels, sse, bits) = luma.code_tx_depth(at, mode, angle_delta, depth, search, fctx);
3843 let cost_d = sse
3844 + search.lambda
3845 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));
3846 if cost_d < best.0 {
3847 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
3848 }
3849 }
3850 luma.restore(x, y, side, &best.2);
3851 cost = best.0;
3852 tx_depth = best.1 as u8;
3853 luma_coeffs = best.3;
3854 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3855 }
3856 // The palette candidate is priced against the mode the luma search (and
3857 // its transform-depth search) already settled on, so a block only takes
3858 // one when it beats the best ordinary intra coding of the same pixels.
3859 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
3860 // prediction is the colour map, not the DC of its neighbours.
3861 let mut mode = mode;
3862 let mut angle_delta = angle_delta;
3863 let mut palette = None;
3864 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
3865 let source: Vec<u8> = (y..y + side)
3866 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
3867 .collect();
3868 let kept = luma.snapshot(x, y, side);
3869 for pal in palette_candidates(&source) {
3870 let n = usize::from(pal.size);
3871 let prediction: Vec<u8> = pal
3872 .map
3873 .iter()
3874 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
3875 .collect();
3876 let trial = luma.code_from_prediction(
3877 x,
3878 y,
3879 side,
3880 &prediction,
3881 false,
3882 search.base_q_idx,
3883 search.deadzone,
3884 luma_set,
3885 );
3886 let cost_p = trial.sse
3887 + search.lambda
3888 * (trial.bits
3889 + mode_bits[DC_PRED as usize]
3890 + crate::tile::palette_bits(&pal, side)
3891 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
3892 if cost_p < cost {
3893 cost = cost_p;
3894 mode = DC_PRED as u8;
3895 angle_delta = 0;
3896 tx_depth = 0;
3897 luma_coeffs = coeffs(&trial.levels, side);
3898 luma.commit(x, y, side, &trial);
3899 palette = Some(pal);
3900 }
3901 }
3902 if palette.is_none() {
3903 luma.restore(x, y, side, &kept);
3904 }
3905 }
3906
3907 // The five recursive filter-intra modes (spec 5.11.14), priced against
3908 // whatever the mode, transform-depth and palette searches settled on --
3909 // the same "one candidate loop after the incumbent is known" shape the
3910 // palette above uses. A block that takes one is `DC_PRED` with `tx_depth`
3911 // 0 and no palette by construction (`av1_filter_intra_allowed`), and its
3912 // luma transform types are coded from `fimode_to_intradir`'s row
3913 // (`crate::tile::tx_row`).
3914 let mut filter_intra: Option<u8> = None;
3915 if filter_intra_on()
3916 && palette.is_none()
3917 && let Some(class) = crate::decode::filter_intra_size_class(side)
3918 {
3919 let row = &cdf::FILTER_INTRA[class];
3920 // With the sequence bit on, EVERY `DC_PRED` block without a luma
3921 // palette carries the flag, so the incumbent pays its zero before the
3922 // comparison -- otherwise the candidate is charged a bit the block
3923 // spends either way (class `price-the-narrowing-not-the-table`).
3924 if mode == DC_PRED {
3925 cost += search.lambda * symbol_bits(row, 0);
3926 }
3927 let one_bits = symbol_bits(row, 1);
3928 let kept = luma.snapshot(x, y, side);
3929 let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]);
3930 let (above, left, corner) =
3931 luma.edges_into(x, y, side, at.reach, &mut above_buf, &mut left_buf);
3932 let mut prediction = vec![0u8; side * side];
3933 for fi in 0..5u8 {
3934 filter_intra_predict_u8(
3935 usize::from(fi),
3936 above,
3937 left,
3938 corner,
3939 side,
3940 &mut prediction, fctx,
3941 );
3942 let trial = luma.code_from_prediction(
3943 x,
3944 y,
3945 side,
3946 &prediction,
3947 false,
3948 search.base_q_idx,
3949 search.deadzone,
3950 luma_set,
3951 );
3952 let cost_f = trial.sse
3953 + search.lambda
3954 * (trial.bits
3955 + mode_bits[DC_PRED as usize]
3956 + one_bits
3957 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
3958 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
3959 if cost_f < cost {
3960 cost = cost_f;
3961 mode = DC_PRED;
3962 angle_delta = 0;
3963 tx_depth = 0;
3964 luma_coeffs = coeffs(&trial.levels, side);
3965 luma.commit(x, y, side, &trial);
3966 filter_intra = Some(fi);
3967 }
3968 }
3969 if filter_intra.is_none() {
3970 luma.restore(x, y, side, &kept);
3971 }
3972 }
3973
3974 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
3975 // planes; what it costs still counts towards the partition decision.
3976 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
3977 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
3978 cost += chroma_cost;
3979
3980 // The intrabc arm is priced against the WHOLE block -- luma and both
3981 // chroma planes, residual-free -- so it is compared after the chroma
3982 // search has added its own cost, not against the luma decision alone.
3983 if let Some(ibc) = ibc {
3984 if let Some((dv, cost_ibc, src)) =
3985 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
3986 {
3987 if cost_ibc < cost {
3988 ibc_commit(luma, chroma, (x, y), src, side);
3989 ibc.last_dv = Some(dv);
3990 ibc.hits += 1;
3991 return (
3992 BlockCoeffs {
3993 skip: true,
3994 dv: Some(dv),
3995 ..BlockCoeffs::default()
3996 },
3997 cost_ibc,
3998 );
3999 }
4000 }
4001 }
4002 (
4003 BlockCoeffs {
4004 u,
4005 v,
4006 luma: luma_coeffs,
4007 mode,
4008 uv_mode,
4009 tx_depth,
4010 palette,
4011 palette_uv,
4012 filter_intra,
4013 cfl_alphas,
4014 angle_delta_y: angle_delta as i8,
4015 ..BlockCoeffs::default()
4016 },
4017 cost,
4018 )
4019}
4020
4021/// The chroma modes the search offers, and the only ones it may offer: each
4022/// predicts from the row directly above and the column directly to the left
4023/// and nothing further, so none of them needs the above-right/below-left
4024/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
4025/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
4026/// reconstruction and its own alpha syntax; both are left out here.
4027const CHROMA_MODES: [u8; 7] = [
4028 DC_PRED,
4029 V_PRED,
4030 H_PRED,
4031 SMOOTH_PRED,
4032 SMOOTH_V_PRED,
4033 SMOOTH_H_PRED,
4034 PAETH_PRED,
4035];
4036
4037/// The thirteen intra mode names, for the chroma fire count's print.
4038#[cfg(test)]
4039const UV_MODE_NAMES: [&str; 14] = [
4040 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
4041 "SMOOTH_H", "PAETH", "CFL",
4042];
4043
4044/// How many blocks each chroma mode has won, indexed by the mode itself --
4045/// the fire count that says whether the search below reaches its candidates
4046/// at all (the `gate-blind-to-feature` class), printed once per gate run.
4047static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
4048 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
4049
4050/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
4051/// won, summed over both chroma planes -- the alpha histogram the gate prints
4052/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
4053/// magnitude only is a search that never left its first candidate).
4054static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
4055 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
4056
4057/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
4058/// zero on a CfL block", `1..=16` the magnitudes.
4059#[cfg(test)]
4060pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
4061 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
4062}
4063
4064/// How many directional luma blocks won at each `angle_delta_y`, indexed
4065/// `delta + 3` -- the histogram that says whether the refinement below ever
4066/// leaves zero (`gate-blind-to-feature`).
4067static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
4068 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
4069
4070/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
4071#[cfg(test)]
4072pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
4073 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
4074}
4075
4076/// Whether the luma search refines a directional winner's `angle_delta_y`
4077/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
4078fn angle_delta_on() -> bool {
4079 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4080 *ON.get_or_init(|| std::env::var("EC_AV1_ANGLE").as_deref() != Ok("0"))
4081}
4082
4083/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
4084/// switches it off, which is how the lane measured its own on/off pair).
4085fn cfl_on() -> bool {
4086 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4087 *ON.get_or_init(|| std::env::var("EC_AV1_CFL").as_deref() != Ok("0"))
4088}
4089
4090/// Whether the intra search offers the five recursive filter-intra modes at
4091/// all, and with them whether the sequence header sets `enable_filter_intra`
4092/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
4093/// its own on/off pair -- and how every byte pin written before it still
4094/// reproduces).
4095pub(crate) fn filter_intra_on() -> bool {
4096 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4097 *ON.get_or_init(|| std::env::var("EC_AV1_FILTER_INTRA").as_deref() != Ok("0"))
4098}
4099
4100/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
4101/// to its own encode.
4102#[cfg(test)]
4103pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
4104 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
4105}
4106
4107/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
4108/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
4109/// Returns each plane's levels, the mode, and what the pair cost (squared
4110/// error plus lambda times bits, the same currency the luma search speaks).
4111///
4112/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
4113/// which is what the luma mode decision was taken against, so what a
4114/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
4115/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
4116/// writer then has to code.
4117#[allow(clippy::too_many_arguments)]
4118/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
4119/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
4120/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
4121/// trials all seven, as before this lever.
4122///
4123/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
4124/// the search's largest trial population by far -- seven modes times two
4125/// planes for every intra block, against 3.7 luma trials -- and the RD
4126/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
4127/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
4128fn chroma_top_k() -> Option<usize> {
4129 static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
4130 *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() {
4131 Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0),
4132 None => CHROMA_TOP_K,
4133 })
4134}
4135
4136/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
4137/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
4138/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
4139/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
4140/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
4141/// BD swings by about a point in either direction as near-tie chroma modes
4142/// flip, which is the measurement's own sensitivity, not a trend: nothing
4143/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
4144/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
4145/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
4146/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
4147const CHROMA_TOP_K: Option<usize> = None;
4148
4149fn search_chroma(
4150 chroma: &mut [Plane; 2],
4151 // The luma plane's RECONSTRUCTION under this block, already committed by
4152 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
4153 luma: &Plane,
4154 (x, y): (usize, usize),
4155 side: usize,
4156 set: TxbSet,
4157 search: &Search,
4158 luma_mode: u8,
4159 fctx: &crate::decode::FrameCtx,
4160) -> (
4161 [Vec<Coeff>; 2],
4162 u8,
4163 f64,
4164 Option<crate::tile::PaletteUv>,
4165 Option<(i32, i32)>,
4166) {
4167 let at = At {
4168 x: x / 2,
4169 y: y / 2,
4170 side: side / 2,
4171 reach: Reach::none(),
4172 set,
4173 };
4174 // The census's cheap proxy for a chroma mode: the SAD of its prediction
4175 // summed over both planes, ranked by the same rule the luma histogram
4176 // uses. Only built under `EC_AV1_CENSUS`.
4177 // The SAD of each mode's prediction, summed over both planes -- the
4178 // census's ranking rule, and what [`chroma_top_k`] prunes by.
4179 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
4180 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
4181 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
4182 u.iter()
4183 .zip(v.iter())
4184 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
4185 .collect()
4186 };
4187 let modes: Vec<u8> = match chroma_top_k() {
4188 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
4189 _ => CHROMA_MODES.to_vec(),
4190 };
4191 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
4192 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
4193 let ranking: Vec<(f64, u8)> = if census_on() {
4194 sad_scores(chroma)
4195 } else {
4196 Vec::new()
4197 };
4198 census_add(2, 1);
4199 census_add(3, modes.len());
4200 let mut best: Option<(f64, u8, Trial, Trial)> = None;
4201 for mode in modes {
4202 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
4203 if (V_PRED..=D67_PRED).contains(&mode) {
4204 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
4205 }
4206 let tx_type = crate::decode::default_intra_tx_type(mode);
4207 let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
4208 let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
4209 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
4210 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
4211 best = Some((cost, mode, u, v));
4212 }
4213 }
4214 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
4215 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
4216 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
4217 // what keeps `u_colors` ascending and distinct the way
4218 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
4219 // each cluster's own mean, since the colour-index map is SHARED by the
4220 // two planes. Priced against the best ordinary chroma mode above, so a
4221 // block only takes one when it beats it; a palette block's chroma mode is
4222 // `UV_DC_PRED` by construction.
4223 let mut palette_uv = None;
4224 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
4225 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
4226 let plane_source = |p: &Plane| -> Vec<u8> {
4227 (at.y..at.y + at.side)
4228 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
4229 .collect()
4230 };
4231 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
4232 for pal in palette_candidates(&u_source) {
4233 let n = usize::from(pal.size);
4234 // V's base colour per cluster: the mean of the samples the shared
4235 // map assigns to it (an empty cluster cannot happen -- every
4236 // colour `palette_candidates` returns is some pixel's nearest).
4237 let mut sums = [0u32; 8];
4238 let mut counts = [0u32; 8];
4239 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
4240 let k = usize::from(i).min(n - 1);
4241 sums[k] += u32::from(sample);
4242 counts[k] += 1;
4243 }
4244 let mut v_colors = [0u16; 8];
4245 for k in 0..n {
4246 v_colors[k] = if counts[k] > 0 {
4247 ((sums[k] + counts[k] / 2) / counts[k]) as u16
4248 } else {
4249 0
4250 };
4251 }
4252 let candidate = crate::tile::PaletteUv {
4253 size: pal.size,
4254 u_colors: pal.colors,
4255 v_colors,
4256 map: pal.map,
4257 };
4258 let predict = |colors: &[u16; 8]| -> Vec<u8> {
4259 candidate
4260 .map
4261 .iter()
4262 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
4263 .collect()
4264 };
4265 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
4266 let u_trial = chroma[0].code_from_prediction(
4267 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
4268 );
4269 let v_trial = chroma[1].code_from_prediction(
4270 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
4271 );
4272 let cost_p = u_trial.sse
4273 + v_trial.sse
4274 + search.lambda
4275 * (u_trial.bits
4276 + v_trial.bits
4277 + crate::tile::palette_uv_bits(&candidate, side));
4278 if cost_p < cost {
4279 cost = cost_p;
4280 mode = DC_PRED;
4281 u = u_trial;
4282 v = v_trial;
4283 palette_uv = Some(candidate);
4284 }
4285 }
4286 }
4287 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
4288 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
4289 // nudges every sample by `alpha_q3` times the block's subsampled,
4290 // average-subtracted luma reconstruction. Offered only where
4291 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
4292 // and priced against the best ordinary chroma mode above, palette
4293 // included, so a block only takes it when it beats both.
4294 let mut cfl_alphas = None;
4295 if side <= 32 && cfl_on() {
4296 // The AC signal, through the decoder's own
4297 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
4298 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
4299 i32::from(luma.reconstruction[ly * luma.width + lx])
4300 });
4301 let dc_prediction = |plane: &Plane| -> Vec<u8> {
4302 let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]);
4303 let (above, left, corner) =
4304 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
4305 let mut prediction = vec![0u8; at.side * at.side];
4306 intra_predict_u8(
4307 DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
4308 fctx,
4309 );
4310 prediction
4311 };
4312 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
4313 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
4314 // add the residual -- which is what [`Plane::code_from_prediction`]
4315 // does with what this returns.
4316 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
4317 base.iter()
4318 .zip(ac.iter())
4319 .map(|(&b, &a)| {
4320 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
4321 })
4322 .collect()
4323 };
4324 // The least-squares alpha, then its two neighbours: minimising
4325 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
4326 // dot-product ratio, and the quantised optimum is one of the two
4327 // integers around it (the clamp and the Q6 rounding are what the SSE
4328 // check below re-decides). libaom sweeps all sixteen magnitudes under
4329 // full RD; three predictions per plane buy nearly the same alpha for a
4330 // thirtieth of the search.
4331 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
4332 let (mut num, mut den) = (0.0f64, 0.0f64);
4333 for row in 0..at.side {
4334 for col in 0..at.side {
4335 let i = row * at.side + col;
4336 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
4337 - f64::from(base[i]);
4338 num += d * f64::from(ac[i]);
4339 den += f64::from(ac[i]) * f64::from(ac[i]);
4340 }
4341 }
4342 if den == 0.0 {
4343 return 0;
4344 }
4345 let ideal = 64.0 * num / den;
4346 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
4347 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
4348 let alpha = alpha.clamp(-16, 16) as i32;
4349 if alpha == 0 {
4350 continue;
4351 }
4352 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
4353 if sse < best.0 {
4354 best = (sse, alpha);
4355 }
4356 }
4357 best.1
4358 };
4359 let picked = [
4360 pick_alpha(&chroma[0], &bases[0]),
4361 pick_alpha(&chroma[1], &bases[1]),
4362 ];
4363 if picked != [0, 0] {
4364 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
4365 let trial = |plane_idx: usize, alpha: i32| -> Trial {
4366 let prediction = if alpha == 0 {
4367 bases[plane_idx].clone()
4368 } else {
4369 apply(&bases[plane_idx], alpha)
4370 };
4371 chroma[plane_idx].code_from_prediction(
4372 at.x,
4373 at.y,
4374 at.side,
4375 &prediction,
4376 false,
4377 search.base_q_idx,
4378 search.deadzone,
4379 set,
4380 )
4381 };
4382 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
4383 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
4384 let combos: [(i32, i32); 3] = [
4385 (picked[0], picked[1]),
4386 (picked[0], 0),
4387 (0, picked[1]),
4388 ];
4389 for &(alpha_u, alpha_v) in &combos {
4390 if (alpha_u, alpha_v) == (0, 0) {
4391 continue;
4392 }
4393 let cu = trial(0, alpha_u);
4394 let cv = trial(1, alpha_v);
4395 let bits =
4396 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
4397 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
4398 if cost_cfl < cost {
4399 cost = cost_cfl;
4400 mode = crate::tile::UV_CFL_PRED as u8;
4401 u = cu;
4402 v = cv;
4403 palette_uv = None;
4404 cfl_alphas = Some((alpha_u, alpha_v));
4405 }
4406 }
4407 }
4408 }
4409 if let Some((alpha_u, alpha_v)) = cfl_alphas {
4410 for alpha in [alpha_u, alpha_v] {
4411 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
4412 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4413 }
4414 }
4415 if census_on() {
4416 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
4417 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4418 }
4419 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4420 chroma[0].commit(at.x, at.y, at.side, &u);
4421 chroma[1].commit(at.x, at.y, at.side, &v);
4422 (
4423 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
4424 mode,
4425 cost,
4426 palette_uv,
4427 cfl_alphas,
4428 )
4429}
4430
4431/// Codes one leaf of a straddling quadrant as whichever costs least of intra
4432/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
4433/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
4434/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
4435/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
4436/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
4437/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
4438/// attempted here: these leaves only ever fill the sliver of real content a
4439/// true edge lands in the middle of a larger block, not a leaf worth a full
4440/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
4441/// (see `write_inter_frame_leaf`'s doc comment).
4442#[allow(clippy::too_many_arguments)]
4443/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
4444/// as [`code_square_inter`] wants them: empty on a frame that codes no
4445/// `reference_select`, or when the leaf compound candidates are switched off.
4446/// One helper because THREE leaf call sites need it -- the split quadrants
4447/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
4448/// `&[]` and so coded no compound block anywhere along the frame's true edge.
4449#[allow(clippy::too_many_arguments)]
4450fn leaf_compound_stacks<'a>(
4451 grid: &MiGrid,
4452 mi_row: usize,
4453 mi_col: usize,
4454 bw4: usize,
4455 bh4: usize,
4456 mi_cols: usize,
4457 mi_rows: usize,
4458 reference_select: bool,
4459 golden: Option<&'a Picture>,
4460 altref: Option<&'a Picture>,
4461) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
4462 if !(reference_select && leaf_compound()) {
4463 return Vec::new();
4464 }
4465 [
4466 (crate::mvstack::GOLDEN_FRAME, golden),
4467 (crate::mvstack::ALTREF_FRAME, altref),
4468 ]
4469 .into_iter()
4470 .filter_map(|(r, pic)| {
4471 pic.map(|p| {
4472 (
4473 r,
4474 p,
4475 crate::mvstack::find_mv_stack_compound(
4476 grid, mi_row, mi_col, bw4, bh4,
4477 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
4478 grid.sign_bias_table(), &[(0, 0); 7], None,
4479 ),
4480 )
4481 })
4482 })
4483 .collect()
4484}
4485
4486/// The OBMC prediction of one square single-reference block: this block's own
4487/// translation prediction (`mc::predict`) with every bordering above/left
4488/// neighbour blended into the overlap strips by the DECODER's own plan and
4489/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
4490/// the search prices is what a decoder reconstructs -- never a second
4491/// implementation of the blend. `None` when the block has no overlappable
4492/// neighbour at all (the writer would then code no `motion_mode` symbol) or
4493/// when the plan cannot be built (a neighbour naming a reference this encode
4494/// does not hold).
4495#[allow(clippy::too_many_arguments)]
4496fn obmc_prediction(
4497 grid: &MiGrid,
4498 (mi_row, mi_col): (usize, usize),
4499 (mi_rows, mi_cols): (usize, usize),
4500 (x, y): (usize, usize),
4501 side: usize,
4502 mv: (i32, i32),
4503 refs: &[Option<&Picture>; 8],
4504 // This block's OWN reference planes, luma then both chroma, each as
4505 // (samples, stride, true width, true height).
4506 ref_planes: [(&[u16], usize, usize, usize); 3],
4507 frame_width: usize,
4508 fctx: &crate::decode::FrameCtx,
4509) -> Option<[Vec<u8>; 3]> {
4510 let n4 = side / 4;
4511 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
4512 return None;
4513 }
4514 let refpix = crate::decode::RefPix::ready(*refs);
4515 let plan = crate::decode::obmc_plan(
4516 grid,
4517 &[],
4518 &[],
4519 mi_row,
4520 mi_col,
4521 n4,
4522 n4,
4523 mi_rows,
4524 mi_cols,
4525 side,
4526 side,
4527 side,
4528 side / 2,
4529 x,
4530 y,
4531 x / 2,
4532 y / 2,
4533 &refpix,
4534 Some(mc::InterpFilterKind::Regular),
4535 frame_width,
4536 )
4537 .ok()?;
4538 let mut pred = [
4539 vec![0u16; side * side],
4540 vec![0u16; side * side / 4],
4541 vec![0u16; side * side / 4],
4542 ];
4543 for (i, r) in ref_planes.into_iter().enumerate() {
4544 let luma_plane = i == 0;
4545 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
4546 let s = if luma_plane { side } else { side / 2 };
4547 mc::predict(
4548 r.0,
4549 r.1,
4550 r.2,
4551 r.3,
4552 mv_to_q4(px, mv.1, luma_plane),
4553 mv_to_q4(py, mv.0, luma_plane),
4554 s,
4555 s,
4556 &mut pred[i],
4557 fctx,
4558 );
4559 }
4560 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
4561 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
4562 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4563 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4564}
4565
4566fn code_square_inter(
4567 luma: &mut Plane,
4568 chroma: &mut [Plane; 2],
4569 (x, y): (usize, usize),
4570 side: usize,
4571 search: &Search,
4572 mode_bits: &[f64; 13],
4573 reference: &Picture,
4574 stack: &MvStack,
4575 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
4576 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
4577 // `reference_select`, and at the straddling call sites).
4578 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
4579 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
4580 // (`record_mi`, in the writer's own coding order) and this leaf's place in
4581 // it -- what the OBMC candidate's eligibility walk and neighbour plan
4582 // read, the same state the tile writer reads when it codes the leaf's
4583 // `motion_mode` symbol.
4584 grid: &MiGrid,
4585 (mi_row, mi_col): (usize, usize),
4586 (mi_rows, mi_cols): (usize, usize),
4587 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
4588 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
4589 refs: &[Option<&Picture>; 8],
4590 fctx: &crate::decode::FrameCtx,
4591) -> (BlockCoeffs, f64) {
4592 let (intra_block, intra_cost) =
4593 code_square(
4594 luma,
4595 chroma,
4596 (x, y),
4597 side,
4598 search,
4599 mode_bits,
4600 tx_select() && tx_select_inter(),
4601 None,
4602 fctx,
4603 );
4604 let luma_set = if side == 8 {
4605 TxbSet::Luma8Inter
4606 } else {
4607 TxbSet::Luma16Inter
4608 };
4609 let chroma_set = if side == 8 {
4610 TxbSet::Chroma4
4611 } else {
4612 TxbSet::Chroma8
4613 };
4614
4615 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
4616 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
4617 let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
4618 + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
4619 + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
4620 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
4621 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
4622 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
4623
4624 let mv = stack.nearest_mv;
4625 let ref_luma = (
4626 &reference.y,
4627 reference.width,
4628 luma.true_width,
4629 luma.true_height,
4630 );
4631 let ref_u = (
4632 &reference.u,
4633 reference.width / 2,
4634 chroma[0].true_width,
4635 chroma[0].true_height,
4636 );
4637 let ref_v = (
4638 &reference.v,
4639 reference.width / 2,
4640 chroma[1].true_width,
4641 chroma[1].true_height,
4642 );
4643 let luma_trial = mc_trial(
4644 luma,
4645 x,
4646 y,
4647 side,
4648 mv,
4649 true,
4650 ref_luma.0,
4651 ref_luma.1,
4652 ref_luma.2,
4653 ref_luma.3,
4654 false,
4655 search.base_q_idx,
4656 search.deadzone,
4657 luma_set, fctx,
4658 );
4659 let u = mc_trial(
4660 &chroma[0],
4661 x / 2,
4662 y / 2,
4663 side / 2,
4664 mv,
4665 false,
4666 ref_u.0,
4667 ref_u.1,
4668 ref_u.2,
4669 ref_u.3,
4670 false,
4671 search.base_q_idx,
4672 search.deadzone,
4673 chroma_set, fctx,
4674 );
4675 let v = mc_trial(
4676 &chroma[1],
4677 x / 2,
4678 y / 2,
4679 side / 2,
4680 mv,
4681 false,
4682 ref_v.0,
4683 ref_v.1,
4684 ref_v.2,
4685 ref_v.3,
4686 false,
4687 search.base_q_idx,
4688 search.deadzone,
4689 chroma_set, fctx,
4690 );
4691 let skip = luma_trial.levels.iter().all(|&l| l == 0)
4692 && u.levels.iter().all(|&l| l == 0)
4693 && v.levels.iter().all(|&l| l == 0);
4694 let inter_cost = luma_trial.sse
4695 + u.sse
4696 + v.sse
4697 + search.lambda
4698 * (skip_bits(skip)
4699 + intra_inter_bits(true)
4700 + single_ref_bits
4701 + mode_bits_inter
4702 + if skip {
4703 0.0
4704 } else {
4705 luma_trial.bits + u.bits + v.bits
4706 });
4707
4708 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
4709 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
4710 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
4711 // scan's own coverage already reached as far) but a real gap at 4-mi
4712 // leaf geometry. r3 ported the extended scan and, while proving it a
4713 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
4714 // `mvstack.rs`), found and fixed a second bug the extended scan's
4715 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
4716 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
4717 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
4718 // regardless of whether it also casts a ref-frame-matching vote) --
4719 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
4720 // branches), which is what made 8-mi geometry a true no-op instead of
4721 // one that only held when every neighbour happened to be inter.
4722 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
4723 // only ever took the stack's NEARESTMV candidate or went intra, so a
4724 // 32x32 block splitting because its four quarters MOVE differently could
4725 // not code the movement it split for. Same candidate `search_inter_block`
4726 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
4727 // a vector the residual syntax can name -- at this leaf's own side.
4728 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
4729 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
4730 // re-price below can hand it back as the winner's own mode info.
4731 let nearest_info = InterInfo {
4732 ref1: None,
4733 mv1: (0, 0),
4734 ref_frame: crate::mvstack::LAST_FRAME,
4735 mode: InterMode::NearestMv,
4736 mv,
4737 ref_mv_idx: 0,
4738 };
4739 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
4740 // syntax, apart from its residual: the OBMC candidate re-prices the same
4741 // syntax against a different prediction, so both sides of that comparison
4742 // carry it.
4743 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
4744 // This leaf's own `NEWMV` vector, kept whether or not it won the
4745 // single-reference comparison: it seeds the compound half-new candidate
4746 // below, exactly as `search_inter_block` seeds its own from the searches
4747 // it already ran.
4748 let mut searched_new: Option<(i32, i32)> = None;
4749 // What that search cost, kept for the second reference's own early-out
4750 // below (`None` when this leaf ran no search at all).
4751 let mut searched_new_cost: Option<f64> = None;
4752 let source_block = luma.source_block(x, y, side);
4753 if leaf_new_mv() {
4754 let (seeds, seed_n) = mv_seeds(stack);
4755 let found = motion::search(
4756 ref_luma.0,
4757 ref_luma.1,
4758 ref_luma.2,
4759 ref_luma.3,
4760 &source_block,
4761 x,
4762 y,
4763 side,
4764 side,
4765 stack.pred_mv,
4766 &seeds[..seed_n],
4767 search.lambda, fctx,
4768 1,
4769 );
4770 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
4771 searched_new_cost = Some(found.cost);
4772 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {
4773 searched_new = Some(new_mv);
4774 // Same reuse as `search_inter_block`: a NEWMV equal to the
4775 // stack's NEARESTMV is the same three trials, already run above.
4776 let (luma_new, u_new, v_new) = if new_mv == mv {
4777 (luma_trial.clone(), u.clone(), v.clone())
4778 } else {
4779 (
4780 mc_trial(
4781 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
4782 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
4783 ),
4784 mc_trial(
4785 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
4786 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
4787 fctx,
4788 ),
4789 mc_trial(
4790 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
4791 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
4792 fctx,
4793 ),
4794 )
4795 };
4796 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
4797 && u_new.levels.iter().all(|&l| l == 0)
4798 && v_new.levels.iter().all(|&l| l == 0);
4799 let drl_bits = if stack.entries.len() > 1 {
4800 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
4801 } else {
4802 0.0
4803 };
4804 let cost_new = luma_new.sse
4805 + u_new.sse
4806 + v_new.sse
4807 + search.lambda
4808 * (skip_bits(skip_new)
4809 + intra_inter_bits(true)
4810 + single_ref_bits
4811 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
4812 + drl_bits
4813 + mv_bits
4814 + if skip_new {
4815 0.0
4816 } else {
4817 luma_new.bits + u_new.bits + v_new.bits
4818 });
4819 if cost_new < best.0 {
4820 single_syntax = intra_inter_bits(true)
4821 + single_ref_bits
4822 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
4823 + drl_bits
4824 + mv_bits;
4825 best = (
4826 cost_new,
4827 Some((
4828 luma_new,
4829 u_new,
4830 v_new,
4831 skip_new,
4832 InterInfo {
4833 ref1: None,
4834 mv1: (0, 0),
4835 ref_frame: crate::mvstack::LAST_FRAME,
4836 mode: InterMode::NewMv,
4837 mv: new_mv,
4838 ref_mv_idx: 0,
4839 },
4840 )),
4841 );
4842 }
4843 }
4844 }
4845
4846 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
4847 // `search_inter_block` prices for a whole 32x32 block:
4848 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
4849 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
4850 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
4851 // too. Priced with the same static-CDF approximation, plus the
4852 // compound-only syntax the writer emits.
4853 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
4854 let (ref1, g) = (*ref1, *g);
4855 let uni =
4856 (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1);
4857 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
4858 + if uni {
4859 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
4860 + symbol_bits(&cdf::COMP_REF[0][0], 0)
4861 + symbol_bits(&cdf::COMP_REF[0][1], 0)
4862 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
4863 } else {
4864 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
4865 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
4866 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
4867 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
4868 };
4869 let mode_ctx =
4870 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
4871 let mode_bits_of =
4872 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
4873 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
4874 (
4875 cstack.nearest_mv,
4876 mode_bits_of(0),
4877 InterInfo {
4878 ref_frame: crate::mvstack::LAST_FRAME,
4879 mode: InterMode::NearestNearestMv,
4880 mv: cstack.nearest_mv.0,
4881 mv1: cstack.nearest_mv.1,
4882 ref1: Some(ref1),
4883 ref_mv_idx: 0,
4884 },
4885 ),
4886 (
4887 ((0, 0), (0, 0)),
4888 mode_bits_of(6),
4889 InterInfo {
4890 ref_frame: crate::mvstack::LAST_FRAME,
4891 mode: InterMode::GlobalGlobalMv,
4892 mv: (0, 0),
4893 mv1: (0, 0),
4894 ref1: Some(ref1),
4895 ref_mv_idx: 0,
4896 },
4897 ),
4898 ];
4899 // Every compound MV residual here is priced against compound stack
4900 // entry 0, which is what `assign_compound_mv` predicts from at
4901 // `ref_mv_idx = 0` -- so it is also what the second-reference search
4902 // below seeds from and rounds to, and no candidate it finds can then
4903 // fail `mv_residual_bits`.
4904 let cbase = cstack
4905 .entries
4906 .first()
4907 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
4908 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
4909 // it a leaf could only name a stack vector for the second half, and
4910 // screen capture showed the consequence: every leaf compound block
4911 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
4912 // extra-reference `NEWMV`, when this reference's own
4913 // `NEAREST_NEARESTMV` vector already prices `margin` times better
4914 // than the `LAST` search of this same leaf did -- one candidate
4915 // evaluation standing in for a whole search.
4916 let margin = leaf_second_new_margin();
4917 let mut second_new: Option<(i32, i32)> = None;
4918 if leaf_second_new_mv() {
4919 let skip = margin > 0.0
4920 && searched_new_cost.is_some_and(|last| {
4921 motion::cost_at(
4922 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
4923 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
4924 ) * margin
4925 <= last
4926 });
4927 if !skip {
4928 let mut seeds = [(0, 0); 4];
4929 let mut seed_n = 1;
4930 for e in cstack.entries.iter().take(3) {
4931 seeds[seed_n] = e.mv1;
4932 seed_n += 1;
4933 }
4934 let found = motion::search(
4935 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
4936 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
4937 );
4938 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
4939 }
4940 }
4941 if let Some(new_mv) = searched_new {
4942 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
4943 ccands.push((
4944 (new_mv, cstack.nearest_mv.1),
4945 mode_bits_of(3) + b0,
4946 InterInfo {
4947 ref_frame: crate::mvstack::LAST_FRAME,
4948 mode: InterMode::NewNearestMv,
4949 mv: new_mv,
4950 mv1: cstack.nearest_mv.1,
4951 ref1: Some(ref1),
4952 ref_mv_idx: 0,
4953 },
4954 ));
4955 }
4956 }
4957 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
4958 // searches this leaf ran, each residual priced against `cbase`.
4959 if let Some(mv1) = second_new {
4960 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
4961 ccands.push((
4962 (cstack.nearest_mv.0, mv1),
4963 mode_bits_of(2) + b1,
4964 InterInfo {
4965 ref_frame: crate::mvstack::LAST_FRAME,
4966 mode: InterMode::NearestNewMv,
4967 mv: cstack.nearest_mv.0,
4968 mv1,
4969 ref1: Some(ref1),
4970 ref_mv_idx: 0,
4971 },
4972 ));
4973 if let Some((new_mv, b0)) =
4974 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
4975 {
4976 ccands.push((
4977 (new_mv, mv1),
4978 mode_bits_of(7) + b0 + b1,
4979 InterInfo {
4980 ref_frame: crate::mvstack::LAST_FRAME,
4981 mode: InterMode::NewNewMv,
4982 mv: new_mv,
4983 mv1,
4984 ref1: Some(ref1),
4985 ref_mv_idx: 0,
4986 },
4987 ));
4988 }
4989 }
4990 }
4991 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
4992 ccands.dedup_by_key(|c| c.0);
4993 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
4994 let g_u = (
4995 g.u.as_slice(),
4996 g.width / 2,
4997 chroma[0].true_width,
4998 chroma[0].true_height,
4999 );
5000 let g_v = (
5001 g.v.as_slice(),
5002 g.width / 2,
5003 chroma[1].true_width,
5004 chroma[1].true_height,
5005 );
5006 for (mvs, bits, info) in ccands {
5007 let luma_c = mc_trial_compound(
5008 luma, x, y, side, mvs, true,
5009 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
5010 search.base_q_idx, search.deadzone, luma_set, fctx,
5011 );
5012 let u_c = mc_trial_compound(
5013 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
5014 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
5015 search.base_q_idx, search.deadzone, chroma_set, fctx,
5016 );
5017 let v_c = mc_trial_compound(
5018 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
5019 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
5020 search.base_q_idx, search.deadzone, chroma_set, fctx,
5021 );
5022 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
5023 && u_c.levels.iter().all(|&l| l == 0)
5024 && v_c.levels.iter().all(|&l| l == 0);
5025 let cost_c = luma_c.sse
5026 + u_c.sse
5027 + v_c.sse
5028 + search.lambda
5029 * (skip_bits(skip_c)
5030 + intra_inter_bits(true)
5031 + bits
5032 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
5033 if cost_c < best.0 {
5034 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
5035 }
5036 }
5037 }
5038
5039 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
5040 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
5041 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
5042 // the writer codes no symbol for one. The prediction is the decoder's own
5043 // plan and blend over the neighbours this leaf's `grid` already carries
5044 // (published by `record_mi` in the writer's coding order), so the
5045 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
5046 // offered this only at 32x32, which is not where libaom cashes its OBMC
5047 // gain.
5048 let mut motion_won = 0u8;
5049 let single = match &best.1 {
5050 None => Some(nearest_info),
5051 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
5052 Some(_) => None,
5053 };
5054 if let Some(info) = single.filter(|i| {
5055 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
5056 && i.ref_frame == crate::mvstack::LAST_FRAME
5057 }) {
5058 let planes = [
5059 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
5060 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
5061 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
5062 ];
5063 // Which alphabet this block's writer will code the symbol against
5064 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
5065 // 3-symbol one only under `allow_warped_motion` and at least one warp
5066 // sample. Mirrored here so the candidates are priced against the
5067 // table the tile really narrows.
5068 let warp_alphabet = warp_on()
5069 && crate::decode::num_proj_ref(
5070 grid,
5071 mi_row,
5072 mi_col,
5073 side / 4,
5074 side / 4,
5075 mi_cols,
5076 mi_rows,
5077 info.ref_frame,
5078 fctx,
5079 ) >= 1;
5080 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
5081 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
5082 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
5083 if let Some(pred) = obmc_prediction(
5084 grid,
5085 (mi_row, mi_col),
5086 (mi_rows, mi_cols),
5087 (x, y),
5088 side,
5089 info.mv,
5090 refs,
5091 planes,
5092 reference.width,
5093 fctx,
5094 ) {
5095 candidates.push((1, pred));
5096 }
5097 }
5098 if warp_alphabet {
5099 if let Some(pred) = warp_prediction(
5100 grid,
5101 (mi_row, mi_col),
5102 (mi_rows, mi_cols),
5103 (x, y),
5104 side,
5105 info.mv,
5106 info.ref_frame,
5107 planes,
5108 fctx,
5109 ) {
5110 candidates.push((2, pred));
5111 }
5112 }
5113 for (motion, pred) in candidates {
5114 let luma_o = luma.code_from_prediction(
5115 x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
5116 );
5117 let u_o = chroma[0].code_from_prediction(
5118 x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
5119 chroma_set,
5120 );
5121 let v_o = chroma[1].code_from_prediction(
5122 x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
5123 chroma_set,
5124 );
5125 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
5126 && u_o.levels.iter().all(|&l| l == 0)
5127 && v_o.levels.iter().all(|&l| l == 0);
5128 let cost_o = luma_o.sse
5129 + u_o.sse
5130 + v_o.sse
5131 + search.lambda
5132 * (skip_bits(skip_o)
5133 + single_syntax
5134 + mm(motion)
5135 + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
5136 // The incumbent pays the motion_mode symbol IT would code, so
5137 // both sides of the comparison carry that syntax.
5138 if cost_o < best.0 + search.lambda * mm(motion_won) {
5139 motion_won = motion;
5140 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
5141 }
5142 }
5143 }
5144
5145 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
5146 if cost < intra_cost {
5147 // A compound winner commits the flat trial it was priced from:
5148 // `commit_inter_luma`'s var-tx trial set is single-reference
5149 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
5150 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
5151 // predicting each half-side trial from BOTH references, verified
5152 // byte-identical to this when its split is disabled) and MEASURED
5153 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
5154 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
5155 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
5156 // compound block's residual is small enough that the four extra
5157 // per-unit txb_skip/eob symbols cost more ladder bytes than this
5158 // encoder's static-CDF estimate prices them at, so the local RD
5159 // win does not convert. lane-av1txbits REBUILT it on top of a
5160 // search that prices against the tables the frame is really
5161 // written with (`tile::arm_pricing_cdfs`, the estimate error on
5162 // these very blocks measured down from +31% to +3%) and measured
5163 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
5164 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
5165 // same build without it. The static-CDF estimate was NOT what
5166 // held the compound var-tx trial back. The flat trial stays.
5167 // An OBMC winner commits the flat trial too: `commit_inter_luma`
5168 // re-predicts each var-tx unit by plain translation, which is not
5169 // the prediction this candidate was priced from.
5170 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
5171 // 0.05 (both rejections above were measured at 0.1, the weight
5172 // the lambda lane showed was 2x too heavy): a compound winner is
5173 // offered the same var-tx split, its units predicted from BOTH
5174 // references (`mc_trial_compound`). RE-MEASURED native: film
5175 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
5176 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
5177 // one row 0.2 down, two flat, short of the two-down-one-flat keep
5178 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
5179 // rather than change the default on a single 0.2 row. It fires:
5180 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
5181 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
5182 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
5183 // 1.3/1.2 down there, which is where the upgrade path is if this
5184 // is picked up again.
5185 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
5186 refs[r as usize].map(|g| {
5187 (
5188 info.mv1,
5189 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
5190 )
5191 })
5192 });
5193 let (levels, tx_depth, dcost) = if motion_won != 0
5194 || (info.ref1.is_some() && second.is_none())
5195 {
5196 luma.commit(x, y, side, &luma_new);
5197 (luma_new.levels.clone(), 0, 0.0)
5198 } else {
5199 commit_inter_luma(
5200 luma, (x, y), side, info.mv,
5201 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
5202 search, &luma_new, skip_new, second, fctx,
5203 )
5204 };
5205 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
5206 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
5207 return (
5208 BlockCoeffs {
5209 angle_delta_y: 0,
5210 cfl_alphas: None,
5211 filter_intra: None,
5212 luma: coeffs(&levels, side),
5213 u: coeffs(&u_new.levels, side / 2),
5214 v: coeffs(&v_new.levels, side / 2),
5215 mode: DC_PRED as u8,
5216 uv_mode: DC_PRED,
5217 skip: skip_new,
5218 eight: None,
5219 dv: None,
5220 palette: None,
5221 palette_uv: None,
5222 tx_depth,
5223 inter: Some(info),
5224 motion_mode: motion_won,
5225 },
5226 cost + dcost,
5227 );
5228 }
5229 }
5230
5231 census_add(8, 1);
5232 if skip {
5233 census_add(10, 1);
5234 }
5235 if inter_cost >= intra_cost {
5236 census_add(9, 1);
5237 }
5238 if inter_cost < intra_cost {
5239 let (levels, tx_depth, dcost) = commit_inter_luma(
5240 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,
5241 );
5242 chroma[0].commit(x / 2, y / 2, side / 2, &u);
5243 chroma[1].commit(x / 2, y / 2, side / 2, &v);
5244 (BlockCoeffs {
5245 angle_delta_y: 0,
5246 cfl_alphas: None,
5247 filter_intra: None,
5248 luma: coeffs(&levels, side),
5249 u: coeffs(&u.levels, side / 2),
5250 v: coeffs(&v.levels, side / 2),
5251 mode: DC_PRED as u8,
5252 uv_mode: DC_PRED,
5253 skip,
5254 eight: None,
5255 dv: None,
5256 palette: None,
5257 palette_uv: None,
5258 tx_depth,
5259 motion_mode: 0,
5260 inter: Some(InterInfo {
5261 ref1: None,
5262 mv1: (0, 0),
5263 ref_frame: crate::mvstack::LAST_FRAME,
5264 mode: InterMode::NearestMv,
5265 mv,
5266 ref_mv_idx: 0,
5267 }),
5268 }, inter_cost + dcost)
5269 } else {
5270 (intra_block, intra_cost)
5271 }
5272}
5273
5274/// Publishes one coded inter-frame block into the `mi` grid the next block's
5275/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
5276/// block casts no vote but is still a coded cell (see `code_square_inter`'s
5277/// note on `processed_rows`/`processed_cols`).
5278fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option<InterInfo>) {
5279 let info = match inter {
5280 Some(info) => MiInfo {
5281 is_inter: true,
5282 ref_frame: info.ref_frame,
5283 // A COMPOUND block votes with BOTH of its references and both of
5284 // its vectors, exactly as the tile writer publishes it: recording
5285 // a compound block as a single-reference one here left the
5286 // encoder's own grid disagreeing with the writer's from the first
5287 // compound block on, so every later stack it searched against was
5288 // not the stack the decoder derives.
5289 ref_frame1: info.ref1.unwrap_or(NO_REF1),
5290 mv1: mv16(info.mv1),
5291 mv: mv16(info.mv),
5292 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
5293 // side, compound modes 2/3/7 on the other.
5294 is_new_mv: matches!(
5295 info.mode,
5296 InterMode::NewMv
5297 | InterMode::NewNewMv
5298 | InterMode::NearestNewMv
5299 | InterMode::NewNearestMv
5300 ),
5301 size,
5302 size_h: size,
5303 is_global_mv0: false,
5304 is_global_mv1: false,
5305 },
5306 None => MiInfo {
5307 is_inter: false,
5308 ref_frame: -1,
5309 ref_frame1: NO_REF1,
5310 mv1: (0, 0),
5311 mv: (0, 0),
5312 is_new_mv: false,
5313 size,
5314 size_h: size,
5315 is_global_mv0: false,
5316 is_global_mv1: false,
5317 },
5318 };
5319 for dr in 0..usize::from(size) {
5320 for dc in 0..usize::from(size) {
5321 grid.set(mi_row + dr, mi_col + dc, info);
5322 }
5323 }
5324}
5325
5326/// The reconstructed samples one 32x32 square covers in all three planes, so
5327/// that a partition trial can be undone.
5328/// One square of a plane, row-major, the inverse of [`Plane::restore`].
5329///
5330/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
5331/// which allocated and freed a `Vec` per row of every block it copied --
5332/// `Plane::snapshot` runs once per partition trial.
5333fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
5334 let mut out = vec![0u8; side * side];
5335 for row in 0..side {
5336 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
5337 }
5338 out
5339}
5340
5341fn snapshot(
5342 luma: &Plane,
5343 chroma: &[Plane; 2],
5344 (x, y): (usize, usize),
5345 side: usize,
5346) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
5347 [
5348 luma.snapshot(x, y, side),
5349 chroma[0].snapshot(x / 2, y / 2, side / 2),
5350 chroma[1].snapshot(x / 2, y / 2, side / 2),
5351 ]
5352}
5353
5354/// Puts such a snapshot back.
5355fn restore(
5356 luma: &mut Plane,
5357 chroma: &mut [Plane; 2],
5358 (x, y): (usize, usize),
5359 side: usize,
5360 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
5361) {
5362 luma.restore(x, y, side, &saved[0]);
5363 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
5364 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
5365}
5366
5367/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
5368/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
5369/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
5370/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
5371/// rule shared with the key-frame path, not a second one that could diverge.
5372fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
5373 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
5374 let dc_entry = dc_pos.map(|i| scored.remove(i));
5375 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
5376 scored.truncate(if dc_entry.is_some() {
5377 top_k.saturating_sub(1)
5378 } else {
5379 top_k
5380 });
5381 if let Some(dc_entry) = dc_entry {
5382 scored.push(dc_entry);
5383 }
5384 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
5385 modes.iter().copied().filter(|m| keep.contains(m)).collect()
5386}
5387
5388fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
5389 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
5390 [INTRA_MODE_CTX[usize::from(left_mode)]];
5391 std::array::from_fn(|mode| {
5392 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
5393 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
5394 } else {
5395 0.0
5396 };
5397 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
5398 })
5399}
5400
5401/// What the luma mode search picks between, and under what terms.
5402#[derive(Clone, Copy)]
5403struct Search<'a> {
5404 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
5405 /// luma search then offers a palette candidate beside the intra modes.
5406 screen: bool,
5407 base_q_idx: u8,
5408 deadzone: f64,
5409 lambda: f64,
5410 modes: &'a [u8],
5411 /// How many of `modes` the full RD trial (forward transform, quantize,
5412 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
5413 /// pre-pass on the prediction residual alone plus DC (always kept, since
5414 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
5415 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
5416 /// mode through full RD, unchanged from before this lever.
5417 top_k: Option<usize>,
5418}
5419
5420/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged
5421/// (the default, until a lever's quality gate justifies pruning by default);
5422/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers.
5423fn prune_top_k() -> Option<usize> {
5424 #[cfg(test)]
5425 {
5426 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
5427 return k;
5428 }
5429 }
5430 let swept = std::env::var("EC_AV1_PRUNE_K")
5431 .ok()
5432 .and_then(|v| v.parse::<usize>().ok());
5433 match swept {
5434 Some(k) if cfg!(test) => Some(k),
5435 _ => PRUNE_TOP_K,
5436 }
5437}
5438
5439// A per-thread override [`prune_top_k`] checks first, so one test can sweep
5440// `top_k` in-process without mutating the environment (forbidden here --
5441// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
5442#[cfg(test)]
5443thread_local! {
5444 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
5445 const { std::cell::Cell::new(None) };
5446}
5447
5448#[cfg(test)]
5449fn set_test_top_k_override(value: Option<usize>) {
5450 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
5451}
5452
5453/// The default: unpruned, thirteen full trials per block, same as before this
5454/// lever. Set from the sweep in the lane report if the quality gate clears it.
5455const PRUNE_TOP_K: Option<usize> = None;
5456
5457/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
5458/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
5459/// quality gates were measured separately and may land on different
5460/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
5461/// [`EC_AV1_PRUNE_K`] or the key-frame path.
5462fn prune_top_k_inter() -> Option<usize> {
5463 #[cfg(test)]
5464 {
5465 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
5466 return k;
5467 }
5468 }
5469 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
5470 .ok()
5471 .and_then(|v| v.parse::<usize>().ok());
5472 match swept {
5473 Some(k) if cfg!(test) => Some(k),
5474 _ => INTER_PRUNE_TOP_K,
5475 }
5476}
5477
5478// A per-thread override [`prune_top_k_inter`] checks first, same reason as
5479// [`TEST_TOP_K_OVERRIDE`].
5480#[cfg(test)]
5481thread_local! {
5482 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
5483 const { std::cell::Cell::new(None) };
5484}
5485
5486#[cfg(test)]
5487fn set_test_top_k_override_inter(value: Option<usize>) {
5488 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
5489}
5490
5491/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
5492/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
5493/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
5494/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
5495/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
5496/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
5497/// pruning them costs less quality here.
5498const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
5499
5500// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
5501// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
5502// inter frame's cost can be attributed to a bucket without changing what
5503// the search actually does. Index: 0 = whole-call time inside
5504// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
5505// [`crate::mc::predict`] (every call, from the motion search's own
5506// candidates and from a committed inter block's final prediction alike),
5507// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
5508#[cfg(test)]
5509thread_local! {
5510 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
5511 std::cell::Cell::new(0),
5512 std::cell::Cell::new(0),
5513 std::cell::Cell::new(0),
5514 std::cell::Cell::new(0),
5515 ];
5516}
5517
5518/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
5519/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
5520/// per transform trial and per `mc::predict` call whether or not anyone was
5521/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
5522/// The clock is now read only when [`crate::par::stage_times`] is on, which
5523/// is what prints the breakdown in the first place.
5524#[cfg(test)]
5525pub(crate) fn stage_start() -> Option<std::time::Instant> {
5526 crate::par::stage_times().then(std::time::Instant::now)
5527}
5528
5529#[cfg(test)]
5530pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
5531 if let Some(t) = t {
5532 stage_add(bucket, t.elapsed());
5533 }
5534}
5535
5536#[cfg(test)]
5537pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
5538 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
5539}
5540
5541#[cfg(test)]
5542fn stage_reset() {
5543 crate::par::set_stage_times(true);
5544 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
5545}
5546
5547#[cfg(test)]
5548fn stage_read() -> [std::time::Duration; 4] {
5549 crate::par::set_stage_times(false);
5550 STAGE_NS.with(|c| {
5551 c.each_ref()
5552 .map(|cell| std::time::Duration::from_nanos(cell.get()))
5553 })
5554}
5555
5556/// One mode's coding of one block, before it is committed.
5557#[derive(Clone)]
5558struct Trial {
5559 levels: Vec<i32>,
5560 reconstruction: Vec<u8>,
5561 sse: f64,
5562 bits: f64,
5563}
5564
5565/// The non-zero levels of a block, as the tile writer takes them.
5566fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
5567 levels
5568 .iter()
5569 .enumerate()
5570 .filter(|&(_, &level)| level != 0)
5571 .map(|(i, &level)| Coeff {
5572 row: (i / side) as u8,
5573 col: (i % side) as u8,
5574 level,
5575 })
5576 .collect()
5577}
5578
5579thread_local! {
5580 /// The tile grid the next frame is coded with, as `(TileColsLog2,
5581 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
5582 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
5583 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
5584 /// one tile per frame, what every caller that never arms anything gets
5585 /// and what every stream this crate wrote before tiles existed carries.
5586 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
5587}
5588
5589/// Arms this thread's next frame encodes with a tile grid (log2 counts).
5590pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
5591 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
5592}
5593
5594fn armed_tiles() -> (u32, u32) {
5595 let armed = TILE_LOG2.with(std::cell::Cell::get);
5596 if armed != (0, 0) {
5597 return armed;
5598 }
5599 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
5600 // (which codes through `encode_sequence`, not the facade) can measure what
5601 // a tile grid costs without a knob of its own -- same shape as
5602 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
5603 match std::env::var("EC_AV1_TILES").ok() {
5604 Some(v) if cfg!(test) => {
5605 let mut f = v.split(':');
5606 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
5607 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
5608 (cols, rows)
5609 }
5610 _ => armed,
5611 }
5612}
5613
5614/// Codes a frame's `tiles` tiles, each entirely on its own (see
5615/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
5616/// the crate's own pool, and hands back their payloads in tile order plus
5617/// whatever `code` returned for tile `store` -- the CDF state
5618/// `context_update_tile_id` names. The result cannot depend on the thread
5619/// count: each job writes one tile from the frame's own starting tables into
5620/// its own slot.
5621fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
5622where
5623 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
5624{
5625 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
5626 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
5627 let threads = crate::par::tile_threads().min(tiles);
5628 let mut slots: Vec<Slot> = Vec::new();
5629 if threads <= 1 {
5630 for index in 0..tiles {
5631 slots.push(Some(code(index)));
5632 }
5633 } else {
5634 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
5635 {
5636 let batch = crate::par::Batch::new("ec-av1-tile");
5637 for (from, to) in crate::par::bands(tiles, threads) {
5638 let done = &done;
5639 let code = &code;
5640 batch.submit(move || {
5641 for index in from..to {
5642 let coded = code(index);
5643 done.lock().expect("tile slots")[index] = Some(coded);
5644 }
5645 });
5646 }
5647 }
5648 slots = done.into_inner().expect("tile slots");
5649 }
5650 let mut out = Vec::with_capacity(tiles);
5651 let mut stored = None;
5652 for (index, slot) in slots.into_iter().enumerate() {
5653 let (bytes, cdfs) = slot.expect("every tile was coded")?;
5654 if index == store {
5655 stored = cdfs;
5656 }
5657 out.push(bytes);
5658 }
5659 Ok((out, stored))
5660}
5661
5662/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
5663/// workers, and returns the results in tile order. The counterpart of
5664/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
5665/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
5666/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
5667/// availability is already tile-relative (`clip_planes_to_tile`,
5668/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
5669/// other tiles have run -- gated by
5670/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
5671/// covers the search as well as the write.
5672///
5673/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
5674/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
5675/// does it for the decoder's filter bands.
5676fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
5677where
5678 T: Send,
5679 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
5680{
5681 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
5682 let threads = crate::par::tile_threads().min(tiles);
5683 if threads <= 1 {
5684 return (0..tiles).map(|index| job(index, fctx)).collect();
5685 }
5686 type Slot<T> = Option<Result<T>>;
5687 let done: std::sync::Mutex<Vec<Slot<T>>> =
5688 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
5689 {
5690 let batch = crate::par::Batch::new("ec-av1-tile-search");
5691 for (from, to) in crate::par::bands(tiles, threads) {
5692 let done = &done;
5693 let job = &job;
5694 let ctx = crate::decode::filter_ctx_copy(fctx);
5695 batch.submit(move || {
5696 for index in from..to {
5697 let searched = job(index, &ctx);
5698 done.lock().expect("tile slots")[index] = Some(searched);
5699 }
5700 });
5701 }
5702 }
5703 done.into_inner()
5704 .expect("tile slots")
5705 .into_iter()
5706 .map(|slot| slot.expect("every tile was searched"))
5707 .collect()
5708}
5709
5710/// One tile job's own copy of a plane: the frame's source, a blank
5711/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
5712/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
5713/// of the frame's reconstruction because a tile's prediction never reads a
5714/// sample outside its own rectangle, and every sample inside it is written
5715/// before it is read.
5716fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
5717 Plane {
5718 source,
5719 reconstruction: vec![128; source.len()],
5720 width,
5721 height,
5722 true_width,
5723 true_height,
5724 tile_x0: 0,
5725 tile_y0: 0,
5726 tile_x1: width,
5727 tile_y1: height,
5728 ctx: CoefCtxMap::default(),
5729 }
5730}
5731
5732/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
5733/// the frame's plane, through the [`crate::par::Shared`] every job holds.
5734///
5735/// corner-cut: the disjointness that makes the aliasing sound is the caller's
5736/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
5737/// rectangles partition it -- checked end-to-end by
5738/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
5739/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
5740/// row-range `split_at_mut` plumbing through `Plane`, which would have to
5741/// thread an origin offset through every prediction and transform call site
5742/// for the same bytes.
5743#[allow(unsafe_code)]
5744fn copy_rect(
5745 dst: crate::par::Shared<'_, Vec<u8>>,
5746 src: &[u8],
5747 stride: usize,
5748 x0: usize,
5749 y0: usize,
5750 x1: usize,
5751 y1: usize,
5752) {
5753 // SAFETY: this job touches only its own tile rectangle (see above).
5754 let dst = unsafe { dst.get() };
5755 for y in y0..y1 {
5756 let (a, b) = (y * stride + x0, y * stride + x1);
5757 dst[a..b].copy_from_slice(&src[a..b]);
5758 }
5759}
5760
5761/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
5762/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
5763/// tables the frame stores (spec 7.20), which is what
5764/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
5765/// below publish.
5766fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
5767 ec_av1_syntax::TileInfo {
5768 uniform_spacing: true,
5769 cols: layout.cols(),
5770 rows: layout.rows(),
5771 cols_log2: layout.cols_log2,
5772 rows_log2: layout.rows_log2,
5773 mi_col_starts: layout.mi_col_starts(),
5774 mi_row_starts: layout.mi_row_starts(),
5775 context_update_tile_id: layout.largest_tile() as u32,
5776 tile_size_bytes,
5777 }
5778}
5779
5780/// Clips the three planes' intra edge reads to `rect`, the tile the
5781/// superblock about to be searched belongs to (the encoder side of the
5782/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
5783/// raster order -- which is a linear extension of every tile's own coding
5784/// order, so a block still only ever predicts from samples already
5785/// reconstructed -- and only availability is tile-relative.
5786fn clip_planes_to_tile(
5787 luma: &mut Plane<'_>,
5788 chroma: &mut [Plane<'_>; 2],
5789 rect: crate::tile::TileRect,
5790) {
5791 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
5792 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
5793 luma.set_tile(x0, y0, x1, y1);
5794 for plane in chroma.iter_mut() {
5795 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
5796 }
5797}
5798
5799/// Encodes one picture as a key frame.
5800///
5801/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
5802/// picks its coefficient CDFs from one of four q contexts by that index.
5803/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
5804/// smaller values trade fidelity for rate.
5805///
5806/// The picture may be any even width and height: the encoder pads it by edge
5807/// replication to a whole number of 32x32 blocks internally, and the frame it
5808/// writes crops back to the picture's own size (`render_width`/
5809/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
5810/// own size, never the padded one.
5811///
5812/// # Errors
5813/// Returns an error when the picture's width or height is zero or odd, or
5814/// when its planes are not 4:2:0 of that size.
5815/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
5816/// stream. The per-frame decode state this needs lives for exactly this call.
5817///
5818/// # Errors
5819/// Returns an error under the same conditions
5820/// [`encode_key_frame_with_modes`] does.
5821pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
5822 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
5823}
5824
5825/// [`encode_key_frame`] with the per-block intra modes given rather than
5826/// searched.
5827///
5828/// # Errors
5829/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
5830/// is empty, or when a block's coefficients do not fit the coded frame.
5831pub fn encode_key_frame_with_modes(
5832 picture: &Picture,
5833 base_q_idx: u8,
5834 deadzone: f64,
5835 modes: &[u8],
5836) -> Result<Encoded> {
5837 encode_key_frame_with_modes_with_ctx(
5838 picture,
5839 base_q_idx,
5840 deadzone,
5841 modes,
5842 &crate::decode::FrameCtx::new(),
5843 )
5844}
5845
5846/// Codes `pictures` as one key frame followed by inter frames.
5847///
5848/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
5849/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
5850/// `show_existing_frame` header, so `stream` is in CODING order while
5851/// `frames` stays in display order (`EncodedSequence::coding_order` is the
5852/// map). Screen content codes flat, decided once per sequence by the same
5853/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
5854/// puts every stream back on the flat path for an A/B.
5855///
5856/// # Errors
5857/// Returns an error under the same conditions [`encode_key_frame`] and the
5858/// inter frame path do.
5859pub fn encode_sequence(
5860 pictures: &[Picture],
5861 base_q_idx: u8,
5862 deadzone: f64,
5863) -> Result<EncodedSequence> {
5864 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
5865}
5866
5867pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
5868 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
5869}
5870
5871/// Encodes one picture as a key frame, choosing each block's luma mode from
5872/// `modes` alone.
5873///
5874/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
5875/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
5876/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
5877/// uses.
5878///
5879/// # Errors
5880/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
5881/// names a mode [`crate::intra::predict`] does not predict.
5882pub(crate) fn encode_key_frame_with_modes_with_ctx(
5883 picture: &Picture,
5884 base_q_idx: u8,
5885 deadzone: f64,
5886 modes: &[u8], fctx: &crate::decode::FrameCtx,
5887) -> Result<Encoded> {
5888 picture.check_even()?;
5889 let padded = picture.padded_to(BLOCK);
5890 let encoded = encode_key_frame_inner(
5891 &padded,
5892 base_q_idx,
5893 deadzone,
5894 modes,
5895 split_blocks(),
5896 (picture.width, picture.height),
5897 unspecified_color_config(), fctx,
5898 )?;
5899 Ok(crop_encoded(&encoded, picture.width, picture.height))
5900}
5901
5902/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
5903/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
5904/// already padded to a whole number of 32x32 blocks; `render` is the real
5905/// (pre-pad) size the frame header tells a decoder to crop back to.
5906pub(crate) fn encode_key_frame_inner(
5907 picture: &Picture,
5908 base_q_idx: u8,
5909 deadzone: f64,
5910 modes: &[u8],
5911 split_blocks: bool,
5912 render: (usize, usize),
5913 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
5914) -> Result<Encoded> {
5915 picture.check()?;
5916 if modes.is_empty() {
5917 return Err(Error::unsupported(
5918 "AV1 encode",
5919 "a mode search needs at least one mode to choose from",
5920 ));
5921 }
5922 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
5923 return Err(Error::unsupported(
5924 "AV1 encode",
5925 format!("intra mode {bad} is not one the encoder predicts"),
5926 ));
5927 }
5928 // The header carries the frame's true (unpadded) size as `frame_width`/
5929 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
5930 // `mi_rows` derived from that same true size (spec `compute_image_size`).
5931 // `render_width`/`render_height` come out equal to it too, so
5932 // `render_and_frame_size_different` is false and no render_size bits are
5933 // written, mirroring libaom/rav1e: the padded `picture` below is only the
5934 // internal coding surface, never what the header names.
5935 // Screen-content detection runs on the SOURCE luma, before any header is
5936 // built: it decides this sequence's `seq_force_screen_content_tools` (and
5937 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
5938 // this frame's own `allow_screen_content_tools`.
5939 let screen = screen_content(
5940 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
5941 picture.width,
5942 (picture.width).min(render.0),
5943 (picture.height).min(render.1),
5944 );
5945 arm_seq_screen(screen);
5946 // A key frame's writer really does start from the defaults, and a search
5947 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
5948 // disarm, or a key frame's bits would depend on which thread searched it.
5949 crate::tile::arm_pricing_cdfs(None, false);
5950 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
5951 // forces deblocking, CDEF and loop restoration OFF for this frame
5952 // (frame.rs:194/210/252/272), so it is only set when the source repeats
5953 // itself enough for the copied blocks to pay that back
5954 // ([`intrabc_worth_it`]).
5955 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
5956 // grid across every tile while this writer builds one per tile, so a
5957 // multi-tile allow_intrabc frame would predict its DVs off a different
5958 // grid than the decoder does. corner-cut, ceiling named: the upgrade
5959 // path is a frame-scoped grid shared by the tile writers.
5960 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
5961 intrabc_worth_it(
5962 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
5963 picture.width,
5964 picture.width.min(render.0),
5965 picture.height.min(render.1),
5966 )
5967 } else {
5968 (false, 0.0)
5969 };
5970 IBC_SHARE.with(|c| c.set(ibc_share));
5971 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
5972 header.allow_screen_content_tools = screen;
5973 header.allow_intrabc = allow_intrabc;
5974 header.render_width = render.0 as u32;
5975 header.render_height = render.1 as u32;
5976 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
5977 // its luma transform below its own side (`crate::tile::write_luma_select`).
5978 // Set here rather than in `key_frame_headers_colour` so the header
5979 // builders' other callers -- the hand-built tile writers, which code no
5980 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
5981 let tx_select = tx_select();
5982 if tx_select {
5983 header.tx_mode = TxMode::Select;
5984 }
5985 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
5986
5987 // Prediction reads no further than this, in each plane's own units --
5988 // see `Plane::true_width`/`true_height`.
5989 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
5990 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
5991 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
5992 // design (see `intra_predict_u8`'s doc comment), so narrow the source
5993 // once here.
5994 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
5995 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
5996 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
5997 let mut luma = Plane {
5998 source: &picture_y8,
5999 reconstruction: vec![128; picture_y8.len()],
6000 width: picture.width,
6001 height: picture.height,
6002 true_width,
6003 true_height,
6004 tile_x0: 0,
6005 tile_y0: 0,
6006 tile_x1: picture.width,
6007 tile_y1: picture.height,
6008 ctx: CoefCtxMap::default(),
6009 };
6010 let mut chroma = [
6011 Plane {
6012 source: &picture_u8,
6013 reconstruction: vec![128; picture_u8.len()],
6014 width: picture.width / 2,
6015 height: picture.height / 2,
6016 true_width: true_width / 2,
6017 true_height: true_height / 2,
6018 tile_x0: 0,
6019 tile_y0: 0,
6020 tile_x1: picture.width / 2,
6021 tile_y1: picture.height / 2,
6022 ctx: CoefCtxMap::default(),
6023 },
6024 Plane {
6025 source: &picture_v8,
6026 reconstruction: vec![128; picture_v8.len()],
6027 width: picture.width / 2,
6028 height: picture.height / 2,
6029 true_width: true_width / 2,
6030 true_height: true_height / 2,
6031 tile_x0: 0,
6032 tile_y0: 0,
6033 tile_x1: picture.width / 2,
6034 tile_y1: picture.height / 2,
6035 ctx: CoefCtxMap::default(),
6036 },
6037 ];
6038
6039 // The search trades a bit for the squared error it saves, in the units the
6040 // reconstruction is measured in: one step of the quantizer, squared.
6041 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
6042 let search = Search {
6043 base_q_idx,
6044 deadzone,
6045 lambda: lambda_scale() * key_lambda_factor() * step * step,
6046 modes,
6047 top_k: prune_top_k(),
6048 screen,
6049 };
6050
6051 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
6052 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
6053 // which may be fewer columns/rows than the padded picture has room for
6054 // -- a block whose origin sits past the true bound is not coded at all,
6055 // matching what a decoder derives from `frame_width`/`frame_height` and
6056 // so never visits either.
6057 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
6058 let (cols, rows) = (cols as usize, rows as usize);
6059 // The luma mode of the block above and of the block to the left, which is
6060 // what picks the CDF the next block's mode is coded against -- the same
6061 // bookkeeping the tile writer keeps, so that the search is costing the
6062 // symbol the writer will actually write.
6063 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
6064 // because a 32x32 block may be split into four 16x16 ones.
6065 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
6066 // This frame's tile grid (one tile unless the facade armed more).
6067 let layout =
6068 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
6069 header.tile_info = tile_info_of(&layout, 1);
6070 // The filter search re-decodes this frame's tiles; the decoder derives
6071 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
6072 // `mi_row_starts`), which is what makes the writer's rects and the
6073 // reader's the same rects.
6074 let header_tile_info = header.tile_info.clone();
6075 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
6076 // once over the whole frame. Each tile job builds its own reconstruction
6077 // planes and its own `above_mode`/`left_mode` bands, which is also what
6078 // the tile writer reads -- a tile resets its neighbour contexts (spec
6079 // 5.11.1), so a block at a tile's left edge must cost its mode against
6080 // the default context, not against whatever the tile to its west left in
6081 // that row. At one tile the bands are the frame's, exactly as before.
6082 let (frame_width, frame_height) = (picture.width, picture.height);
6083 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
6084 let [cb, cr] = &mut chroma;
6085 let chroma_out = [
6086 crate::par::Shared::new(&mut cb.reconstruction),
6087 crate::par::Shared::new(&mut cr.reconstruction),
6088 ];
6089 let search_tile = |index: usize,
6090 fctx: &crate::decode::FrameCtx|
6091 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
6092 crate::tile::arm_pricing_cdfs(None, false);
6093 let rect = layout.rect(index);
6094 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
6095 let mut chroma = [
6096 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
6097 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
6098 ];
6099 clip_planes_to_tile(&mut luma, &mut chroma, rect);
6100 let mut above_mode = vec![DC_PRED; cols * 2];
6101 let mut left_mode = vec![DC_PRED; rows * 2];
6102 let mut ibc = allow_intrabc.then(|| {
6103 Ibc::new(
6104 (
6105 rect.mi_col0 as usize * 4,
6106 rect.mi_row0 as usize * 4,
6107 (rect.mi_col1 as usize * 4).min(true_width),
6108 (rect.mi_row1 as usize * 4).min(true_height),
6109 ),
6110 &picture_y8,
6111 frame_width,
6112 )
6113 });
6114 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
6115 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
6116 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
6117 let mut modes = Vec::with_capacity(4);
6118 // The quadrants of a superblock are coded in the order the decoder
6119 // walks them, which for a 64x64 split into 32x32 blocks is raster
6120 // order among the quadrants that are inside the frame.
6121 let mut blocks = Vec::with_capacity(4);
6122 for quadrant in 0..4 {
6123 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
6124 if col >= cols || row >= rows {
6125 continue;
6126 }
6127 let (x, y) = (col * BLOCK, row * BLOCK);
6128 let (c0, r0) = (col * 2, row * 2);
6129 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
6130
6131 // spec `decode_partition`'s hasRows/hasCols recomputed at this
6132 // 32x32 block's own half (see `crate::tile::has_half`): the
6133 // true frame edge can fall inside a quadrant a superblock-level
6134 // check already let through. A quadrant that fails either may
6135 // not be left whole; a 16x16 sub-block that fails either (once
6136 // split) is a leaf this writer has no rectangular transform
6137 // for, so the search must not pick a split that would need one.
6138 let (has_cols32, has_rows32) = (
6139 crate::tile::has_half(
6140 col as u32 * crate::tile::BLOCK_MI,
6141 crate::tile::BLOCK_MI,
6142 header.mi_cols,
6143 ),
6144 crate::tile::has_half(
6145 row as u32 * crate::tile::BLOCK_MI,
6146 crate::tile::BLOCK_MI,
6147 header.mi_rows,
6148 ),
6149 );
6150 let whole_legal = has_cols32 && has_rows32;
6151 // A 16x16 sub-block's own hasCols/hasRows (spec
6152 // `decode_partition`, recomputed at this leaf's own half):
6153 // either axis false is a straddling leaf this writer codes as
6154 // the 8x8 leaves that are inside it
6155 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
6156 // false is the same split with the partition symbol inferred
6157 // rather than coded -- no rectangular transform is needed
6158 // (lane-av1rect).
6159 let sub_half = |sr: usize, sc: usize| {
6160 (
6161 crate::tile::has_half(
6162 sc as u32 * crate::tile::SUB_MI,
6163 crate::tile::SUB_MI,
6164 header.mi_cols,
6165 ),
6166 crate::tile::has_half(
6167 sr as u32 * crate::tile::SUB_MI,
6168 crate::tile::SUB_MI,
6169 header.mi_rows,
6170 ),
6171 )
6172 };
6173 // What the whole 32x32 costs, including the partition symbol
6174 // that says it is not split.
6175 let (whole, mut cost_whole) = code_square(
6176 &mut luma,
6177 &mut chroma,
6178 (x, y),
6179 BLOCK,
6180 &search,
6181 &mode_bits(above_mode[c0], left_mode[r0]),
6182 tx_select,
6183 ibc.as_mut(), fctx,
6184 );
6185 cost_whole += search.lambda * partition_bits(BLOCK, false);
6186 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
6187
6188 // What four 16x16 blocks cost instead, each searched against
6189 // the reconstruction the ones before it left.
6190 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
6191 let mut split = Vec::with_capacity(4);
6192 let mut cost_split = search.lambda
6193 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
6194 let mut split_modes = Vec::with_capacity(4);
6195 for sub in 0..4 {
6196 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
6197 // Same filter as the writer's `sub_positions` (spec
6198 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
6199 // return): a sub-block whose own origin sits past the
6200 // true frame is never coded, so it must not be searched
6201 // or pushed onto `split` either, or the writer's block
6202 // count will not match what it is prepared to name.
6203 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
6204 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
6205 {
6206 continue;
6207 }
6208 let (has_cols16, has_rows16) = sub_half(sr, sc);
6209 if has_cols16 && has_rows16 {
6210 let (block, cost) = code_square(
6211 &mut luma,
6212 &mut chroma,
6213 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
6214 SUB,
6215 &search,
6216 &mode_bits(above_mode[sc], left_mode[sr]),
6217 tx_select,
6218 ibc.as_mut(), fctx,
6219 );
6220 cost_split += cost;
6221 split_modes.push(block.mode);
6222 above_mode[sc] = block.mode;
6223 left_mode[sr] = block.mode;
6224 split.push(block);
6225 } else {
6226 // A straddling 16x16: two (or, at a true corner, one)
6227 // 8x8 leaves, in the raster order `write_leaf8`'s
6228 // caller expects. Both leaves cost against the SAME
6229 // enclosing-slot mode context (see
6230 // `crate::tile::write_leaf8`'s doc), and neither
6231 // updates `above_mode`/`left_mode` at this SUB slot --
6232 // the writer never does either, so the search must
6233 // not diverge from what it will actually read next.
6234 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
6235 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
6236 let mut leaves = Vec::with_capacity(2);
6237 for i in 0..4 {
6238 let leaf_x = x_sub + (i % 2) * 8;
6239 let leaf_y = y_sub + (i / 2) * 8;
6240 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
6241 continue;
6242 }
6243 let (leaf, cost) = code_square(
6244 &mut luma,
6245 &mut chroma,
6246 (leaf_x, leaf_y),
6247 8,
6248 &search,
6249 &leaf_mode_bits,
6250 tx_select,
6251 None, fctx,
6252 );
6253 cost_split += cost;
6254 split_modes.push(leaf.mode);
6255 leaves.push(leaf);
6256 }
6257 split.push(BlockCoeffs {
6258 eight: Some(leaves),
6259 ..BlockCoeffs::default()
6260 });
6261 }
6262 }
6263
6264 // A split whose subs are all whole 16x16 is a real quality
6265 // alternative to `whole`, exactly as before. Through r14, a
6266 // split carrying an 8x8-leaf sub was only ever forced
6267 // (`!whole_legal`), never chosen on cost, because the leaf
6268 // path was not yet proven against a real decoder; r15 proved
6269 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
6270 // the read path (`decode_leaf8`), so leaf8 can now win on
6271 // cost anywhere, same as any other split.
6272 if !whole_legal || (split_blocks && cost_split < cost_whole) {
6273 modes.extend_from_slice(&split_modes);
6274 blocks.push(Quadrant::Split(split));
6275 } else {
6276 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
6277 for cell in 0..2 {
6278 above_mode[c0 + cell] = whole.mode;
6279 left_mode[r0 + cell] = whole.mode;
6280 }
6281 modes.push(whole.mode);
6282 blocks.push(Quadrant::Whole(whole));
6283 }
6284 }
6285 coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes));
6286 }
6287 }
6288 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
6289 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
6290 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
6291 for (&out, tile) in chroma_out.iter().zip(&chroma) {
6292 copy_rect(
6293 out,
6294 &tile.reconstruction,
6295 frame_width / 2,
6296 x0 / 2,
6297 y0 / 2,
6298 x1.div_ceil(2),
6299 y1.div_ceil(2),
6300 );
6301 }
6302 Ok(coded)
6303 };
6304 let searched = search_tiles(layout.count(), fctx, search_tile)?;
6305 // Back into frame raster order: the tile writer indexes `superblocks` by
6306 // the frame's own superblock index, and `modes` is the coding order the
6307 // ablation drivers read.
6308 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
6309 for (at, superblock, block_modes) in searched.into_iter().flatten() {
6310 in_order[at] = Some((superblock, block_modes));
6311 }
6312 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
6313 let mut modes = Vec::with_capacity(cols * rows);
6314 for slot in in_order {
6315 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
6316 superblocks.push(superblock);
6317 modes.extend_from_slice(&block_modes);
6318 }
6319
6320 #[cfg(test)]
6321 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
6322 // A key frame always starts from the defaults (`primary_ref_frame` is
6323 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
6324 // set, so what it stores into the slots it refreshes is exactly those
6325 // defaults again (spec 7.20's `started_from` arm) -- the first inter
6326 // frame after it therefore starts from the defaults too.
6327 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
6328 let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
6329 let start_cdfs = CdfSnapshot(cdfs);
6330 // The luma restoration-unit grid this frame's `lr_params` implies
6331 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
6332 // swallowed by the one before it), for the tile writer's own per-unit
6333 // walk.
6334 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
6335 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
6336 // Every tile is coded from this frame's OWN starting tables and leaves
6337 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
6338 // loop-restoration reference and its neighbour contexts), so the tiles
6339 // are independent of each other and of the order they are written in.
6340 let code_tiles = |bits: u8,
6341 sb_cols: usize,
6342 grid: &[u8],
6343 units: &[Option<crate::restoration::WienerInfo>]|
6344 -> Result<Vec<Vec<u8>>> {
6345 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
6346 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
6347 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
6348 let mut cdfs = start_cdfs.0.clone();
6349 crate::tile::arm_screen(screen);
6350 crate::tile::arm_filter_intra(filter_intra_on());
6351 crate::tile::arm_intrabc(allow_intrabc);
6352 crate::tile::arm_pricing_cdfs(None, false);
6353 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
6354 mi_cols,
6355 mi_rows,
6356 base_q_idx,
6357 &superblocks,
6358 tx_select,
6359 &mut cdfs,
6360 layout.rect(index),
6361 )?;
6362 Ok((bytes, None))
6363 })?;
6364 Ok(out)
6365 };
6366 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
6367 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
6368 // the tile just coded back to the decoder under each candidate (see
6369 // `crate::filter_search`), and keep the filtered picture that wins as
6370 // the reconstruction -- what a decoder outputs, and what the next
6371 // frame predicts from.
6372 pick_and_apply_filters(
6373 &mut header,
6374 &mut luma,
6375 &mut chroma,
6376 [&picture_y8, &picture_u8, &picture_v8],
6377 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
6378 // and loop restoration off and codes none of their parameters
6379 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
6380 // the encoder's reconstruction is already what a decoder produces.
6381 !allow_intrabc,
6382 &mut tiles,
6383 search.lambda,
6384 fctx,
6385 // Every re-code starts from this frame's OWN starting tables, never
6386 // from where the first write left them: the second tile is the same
6387 // symbol sequence plus new ones, so it must adapt from the same
6388 // point the decoder will.
6389 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
6390 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
6391 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
6392 crate::decode::decode_key_frame_tiles_lr(
6393 &payloads,
6394 &header_tile_info,
6395 h.mi_cols,
6396 h.mi_rows,
6397 base_q_idx,
6398 h.frame_width,
6399 h.frame_height,
6400 seq.enable_filter_intra,
6401 cdef,
6402 lf,
6403 tx_select,
6404 h.reduced_tx_set,
6405 h.allow_screen_content_tools,
6406 h.allow_intrabc,
6407 lr,
6408 fctx,
6409 )
6410 },
6411 )?;
6412 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
6413 header.tile_info.tile_size_bytes = tile_size_bytes;
6414 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
6415 let mut stream = temporal_delimiter();
6416 stream.extend_from_slice(&sequence_header_obu(&seq)?);
6417 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
6418
6419 let [u, v] = chroma;
6420 Ok(Encoded {
6421 stream,
6422 modes,
6423 inter_block_share: 0.0,
6424 reconstruction: Picture {
6425 width: luma.width,
6426 height: luma.height,
6427 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6428 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6429 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6430 },
6431 tile,
6432 mi_cols: header.mi_cols,
6433 mi_rows: header.mi_rows,
6434 base_q_idx,
6435 tx_select,
6436 // A key frame codes no inter block, so no motion_mode symbol.
6437 switchable_motion_mode: false,
6438 screen,
6439 next_cdfs: start_cdfs.clone(),
6440 start_cdfs,
6441 loop_filter: header.loop_filter,
6442 cdef: header.cdef,
6443 loop_restoration: header.loop_restoration,
6444 allow_intrabc,
6445 })
6446}
6447
6448/// Chooses this frame's deblocking levels and CDEF strengths, writes them
6449/// into `header` and
6450/// replaces the frame's own region of the encoder's reconstruction with the
6451/// filtered picture the decoder produced under them
6452/// ([`crate::filter_search::pick_deblock`]).
6453///
6454/// `search == false` leaves the header at level 0 (deblocking off) and the
6455/// reconstruction untouched: the caller's stream is one this crate's own
6456/// decoder cannot read back, so there is nothing to search against.
6457///
6458/// # Errors
6459/// The decoder's own error, when it refuses the tile the encoder just wrote
6460/// -- that is an encoder defect, not a filter one, so it is propagated
6461/// rather than swallowed into "no deblocking".
6462fn pick_and_apply_filters(
6463 header: &mut FrameHeader,
6464 luma: &mut Plane<'_>,
6465 chroma: &mut [Plane<'_>; 2],
6466 source: [&[u8]; 3],
6467 search: bool,
6468 // The coded tiles, one payload per tile of the frame's grid, replaced in
6469 // place when the search chooses a per-64x64 `cdef_idx` list
6470 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
6471 // tile is written a second time under `recode` and the winner
6472 // re-decoded from them.
6473 tiles: &mut Vec<Vec<u8>>,
6474 lambda: f64,
6475 fctx: &crate::decode::FrameCtx,
6476 recode: impl Fn(
6477 u8,
6478 usize,
6479 &[u8],
6480 &[Option<crate::restoration::WienerInfo>],
6481 ) -> Result<Vec<Vec<u8>>>,
6482 decode: impl Fn(
6483 &LoopFilterParams,
6484 &CdefParams,
6485 &FrameHeader,
6486 &[Vec<u8>],
6487 &LoopRestorationParams,
6488 ) -> Result<Picture>,
6489) -> Result<()> {
6490 if !search {
6491 return Ok(());
6492 }
6493 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
6494 let hdr = header.clone();
6495 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
6496 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
6497 let damping = 3 + (header.quantization.base_q_idx >> 6);
6498 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
6499 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
6500 let none_lr = LoopRestorationParams::default();
6501 // Every candidate scores the same coded tile: decode it once and re-run
6502 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
6503 // the encoder's profile before this). The per-64x64 error the CDEF
6504 // preset search reads comes off the REPLAYED picture, which is the same
6505 // picture a decode produces -- that is what the replay is pinned on.
6506 crate::decode::clear_filter_replay();
6507 // lane-av1fpar: the per-tile search is over, so every core is idle from
6508 // here to the end of the frame -- band each candidate's deblock/CDEF
6509 // replay, the capture decode's own filter chain and the loop-restoration
6510 // passes across the same workers the search used.
6511 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
6512 let ft = crate::par::timer(crate::par::S_FILTER);
6513 let search_result = crate::filter_search::pick_filters(
6514 |lf, cdef| {
6515 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
6516 return Ok(picture);
6517 }
6518 crate::decode::arm_filter_replay();
6519 let _t = crate::par::timer(crate::par::S_FIRST);
6520 decode(lf, cdef, &hdr, tiles, &none_lr)
6521 },
6522 source,
6523 luma.width,
6524 (fw, fh),
6525 damping,
6526 (sb_cols, sb_rows),
6527 lambda,
6528 );
6529 drop(ft);
6530 let (lf, cdef, idx_grid, picture) = search_result?;
6531 header.loop_filter = lf;
6532 header.cdef = cdef;
6533 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
6534 // in the frame header, so a re-decode under candidate parameters cannot
6535 // search them the way deblocking and CDEF are searched above. What the
6536 // decoder hands back instead is its own filter chain's intermediates
6537 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
6538 // those, through the decoder's own Wiener kernel.
6539 //
6540 // The capture rides the decode this stage was already going to do: the
6541 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
6542 // decode of the tile as it stands. That decode's header still says
6543 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
6544 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
6545 // an approximation inside the SEARCH only; the reconstruction this
6546 // function ends up splicing is always a real decode of the real tile.
6547 let lr_on = restoration_enabled();
6548 // The `cdef_idx` literals live in the tile payload, so a frame that
6549 // chose a per-64x64 preset list codes its tiles a second time.
6550 if !idx_grid.is_empty() {
6551 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
6552 }
6553 // lane-av1cap: that re-coded tile used to be DECODED here as well --
6554 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
6555 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
6556 // and the picture this function splices. Both come out of ONE more
6557 // replay of the winning parameters on the same captured pre-filter
6558 // planes every candidate was scored on: the same two filter kernels, on
6559 // the same input, in the same order, so the same bytes. Re-coding the
6560 // tile does not move the reconstruction the replay holds -- `cdef_idx`
6561 // is an equiprobable literal, so it adapts no CDF and changes no
6562 // residual.
6563 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
6564 #[cfg(test)]
6565 let replay_was_used = replayed.is_some();
6566 let (mut filtered, mut stages) = match replayed {
6567 Some((picture, stages)) => (picture, stages),
6568 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
6569 // refuses): every candidate was a full decode, so the winner's own
6570 // picture stands, and the stages still need a capturing decode.
6571 None => {
6572 fctx.capture_stages.set(lr_on);
6573 let picture = if idx_grid.is_empty() && !lr_on {
6574 picture
6575 } else {
6576 let _t = crate::par::timer(crate::par::S_CAPTURE);
6577 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
6578 };
6579 fctx.capture_stages.set(false);
6580 (picture, crate::decode::take_filter_stages(fctx))
6581 }
6582 };
6583 #[cfg(test)]
6584 if crate::decode::verify_final_replay() && replay_was_used {
6585 fctx.capture_stages.set(lr_on);
6586 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
6587 fctx.capture_stages.set(false);
6588 let want_stages = crate::decode::take_filter_stages(fctx);
6589 assert!(
6590 (want.width, want.height) == (filtered.width, filtered.height)
6591 && want.y == filtered.y
6592 && want.u == filtered.u
6593 && want.v == filtered.v,
6594 "the final filter replay is not the capture decode it stands in for",
6595 );
6596 // Only the frame's own cropped region: the plane is padded to the
6597 // superblock grid and the columns past the mi extent are written by
6598 // nothing (the decoder's plane pool leaves whatever the last frame
6599 // put there), while the restoration search reads strictly inside
6600 // `fw x fh` -- `restoration::lr_sample` clamps its column to
6601 // `plane_w - 1` and its row to the frame's, and
6602 // `filter_search::pick_restoration`'s own SSE walk never leaves the
6603 // crop either.
6604 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
6605 for row in 0..h {
6606 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
6607 assert!(
6608 x == y,
6609 "{what}: the replayed filter stages are not the ones the capture \
6610 decode returns (row {row} of {h}, width {w}, stride {stride})",
6611 );
6612 }
6613 };
6614 match (&want_stages, &stages) {
6615 (Some(a), Some(b)) => {
6616 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
6617 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
6618 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
6619 region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked");
6620 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
6621 }
6622 }
6623 (None, None) => {}
6624 _ => panic!("one path captured filter stages and the other did not"),
6625 }
6626 }
6627 // lane-av1cap2: the capture stays live past the restoration search --
6628 // `crate::decode::replay_restoration` filters the same post-CDEF plane
6629 // rather than decoding the re-coded tile. Cleared at the end instead.
6630 let mut lr = LoopRestorationParams::default();
6631 if lr_on {
6632 let mut want = LoopRestorationParams {
6633 loop_restoration_size: [64, 64, 64],
6634 uses_lr: true,
6635 ..LoopRestorationParams::default()
6636 };
6637 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
6638 let lrt = crate::par::timer(crate::par::S_LR);
6639 let units = match stages.take() {
6640 Some(stages) => crate::filter_search::pick_restoration(
6641 &stages,
6642 source[0],
6643 luma.width,
6644 (fw, fh),
6645 &want,
6646 lambda,
6647 fctx,
6648 ),
6649 None => Vec::new(),
6650 };
6651 // A frame no unit restores keeps `RESTORE_NONE` on every plane
6652 // rather than paying ~1 bit per 64x64 for a tile full of
6653 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
6654 // clip whose units never take a filter).
6655 drop(lrt);
6656 if units.iter().any(Option::is_some) {
6657 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
6658 let _t = crate::par::timer(crate::par::S_CAPTURE);
6659 // lane-av1cap2: that re-coded tile used to be DECODED here to
6660 // reach the restored reference frame -- 5.6% of a 4K frame,
6661 // for a filter that reads nothing of the tile but the per-unit
6662 // Wiener filters this stage just chose. Run the decoder's own
6663 // restoration kernel on the replay's post-CDEF plane instead
6664 // (`crate::decode::replay_restoration`), with the real
6665 // post-deblock stripe borders.
6666 match crate::decode::replay_restoration(&want, &units, fctx) {
6667 Some(y) => {
6668 #[cfg(test)]
6669 let margin = fctx
6670 .last_frame_wide_margin
6671 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
6672 #[cfg(test)]
6673 if crate::decode::verify_final_replay() {
6674 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
6675 assert!(
6676 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
6677 && want_pic.u == filtered.u
6678 && want_pic.v == filtered.v,
6679 "the restoration replay moved a chroma plane or the picture size",
6680 );
6681 assert!(
6682 want_pic.y == y,
6683 "the restoration replay is not the decode of the re-coded tile",
6684 );
6685 assert!(
6686 fctx.last_frame_wide_margin
6687 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
6688 == margin,
6689 "the restoration replay's wide-margin luma is not the decode's",
6690 );
6691 }
6692 filtered.y = y;
6693 }
6694 // Nothing captured: the winner came out of a full decode,
6695 // so this one does too.
6696 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
6697 }
6698 *tiles = coded;
6699 lr = want;
6700 }
6701 }
6702 crate::decode::clear_filter_replay();
6703 header.loop_restoration = lr;
6704 let dec_cw = filtered.width.div_ceil(2);
6705 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
6706 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
6707 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
6708 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
6709 Ok(())
6710}
6711
6712/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
6713/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
6714/// since every block this crate's inter tile writer codes is 32x32.
6715const SIZE_GROUP_32: usize = 3;
6716
6717/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
6718/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
6719/// stack this encoder builds is ever asked to predict against.
6720const LAST_FRAME: i8 = 1;
6721
6722/// What an inter frame's intra branch spends to name each of the thirteen
6723/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
6724/// context, since an inter frame's intra blocks do not read their
6725/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
6726/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
6727/// state, so it is built once per frame.
6728fn inter_mode_bits() -> [f64; 13] {
6729 std::array::from_fn(|mode| {
6730 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
6731 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
6732 } else {
6733 0.0
6734 };
6735 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
6736 + angle
6737 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
6738 })
6739}
6740
6741/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
6742/// [`mc::predict`] takes, in the units of the plane it predicts into.
6743///
6744/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
6745/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
6746/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
6747/// domain. `luma` picks which.
6748fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
6749 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
6750}
6751
6752/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
6753/// that module): the magnitude an `MV_CLASS_n` component's own bits start
6754/// counting from.
6755fn mv_class_base(class: usize) -> i32 {
6756 if class == 0 { 0 } else { 2i32 << (class + 2) }
6757}
6758
6759/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
6760/// `tile::mv_class_of`.
6761fn mv_class_of(z: i32) -> usize {
6762 let mut class = 0;
6763 while class < 10 && mv_class_base(class + 1) <= z {
6764 class += 1;
6765 }
6766 class
6767}
6768
6769/// What [`crate::tile::write_mv_component`] (private to that module) would
6770/// spend coding one non-zero motion vector component, against the same
6771/// static default CDFs the writer starts a frame from — the same
6772/// static-table approximation [`mode_bits`] costs the luma mode symbol
6773/// through, not the tile writer's own adapting state, which this encoder has
6774/// no way to read without duplicating it block for block.
6775///
6776/// Returns `None` when `diff` needs the eighth-pel precision this crate's
6777/// frames never carry (`allow_high_precision_mv` is always off), which is
6778/// what [`round_to_valid_mv`] exists to avoid ever happening.
6779fn mv_component_bits(diff: i32) -> Option<f64> {
6780 let mag = diff.unsigned_abs() as i32;
6781 let z = mag - 1;
6782 if z & 1 == 0 {
6783 return None;
6784 }
6785 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
6786 let class = mv_class_of(z);
6787 bits += symbol_bits(&cdf::MV_CLASS, class);
6788 let local = z - mv_class_base(class);
6789 if class == 0 {
6790 let bit = (local >> 3) & 1;
6791 let fr = (local >> 1) & 3;
6792 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
6793 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
6794 } else {
6795 let d = local >> 3;
6796 let fr = (local >> 1) & 3;
6797 for i in 0..class {
6798 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
6799 }
6800 bits += symbol_bits(&cdf::MV_FR, fr as usize);
6801 }
6802 Some(bits)
6803}
6804
6805/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
6806/// own -- a second motion search per block against that reference's picture,
6807/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
6808/// off in a test build (what the lane measured both arms with).
6809fn extra_ref_new_mv() -> bool {
6810 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
6811 Some(v) if cfg!(test) => v != "0",
6812 _ => EXTRA_REF_NEW_MV,
6813 }
6814}
6815
6816/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
6817/// flat slot plan (`inter_frame_headers_slots`): every reference but
6818/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
6819/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
6820/// frame two back when there is one (otherwise it, too, names the key frame's
6821/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
6822pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
6823 let last = order_hint.wrapping_sub(1) & 0x7f;
6824 let alt = if has_altref {
6825 order_hint.wrapping_sub(2) & 0x7f
6826 } else {
6827 key_hint
6828 };
6829 [last, last, last, key_hint, last, last, alt]
6830}
6831
6832/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
6833/// header bit that lets each block choose between a single and a compound
6834/// reference. Off by default until compound prediction is measured to pay;
6835/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
6836/// runs as), and every block still codes SINGLE, so the only cost is one
6837/// `comp_mode` symbol per inter block.
6838const REFERENCE_SELECT: bool = true;
6839
6840/// [`REFERENCE_SELECT`], with the test-build environment override.
6841pub(crate) fn reference_select() -> bool {
6842 match std::env::var("EC_AV1_COMPOUND").ok() {
6843 Some(v) if cfg!(test) => v != "0",
6844 _ => REFERENCE_SELECT,
6845 }
6846}
6847
6848/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
6849/// per entry past `start`, `1` to advance and `0` to stop, at most two.
6850fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
6851 let mut bits = 0.0;
6852 let mut idx = start;
6853 while idx < start + 2 && stack.entries.len() > idx + 1 {
6854 let advance = idx < target;
6855 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
6856 if !advance {
6857 break;
6858 }
6859 idx += 1;
6860 }
6861 bits
6862}
6863
6864/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
6865/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
6866/// `assign_mv`), so the same vector costs a different residual from each.
6867fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
6868 let mut best: Option<(f64, u8)> = None;
6869 for idx in 0..3usize {
6870 if idx > 0 && stack.entries.len() <= idx {
6871 break;
6872 }
6873 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
6874 if let Some(b) = mv_residual_bits(mv, base) {
6875 let total = b + drl_bits_for(stack, 0, idx);
6876 if best.is_none_or(|(t, _)| total < t) {
6877 best = Some((total, idx as u8));
6878 }
6879 }
6880 }
6881 best
6882}
6883
6884/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
6885/// zero vector and the stack's own candidates. A neighbour block's vector is
6886/// where this block's motion most often already is, which is what pays for
6887/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
6888/// vs libaom for 0.2 s off a 6 s ladder).
6889fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
6890 let mut seeds = [(0, 0); 4];
6891 let mut n = 1;
6892 for e in stack.entries.iter().take(3) {
6893 seeds[n] = e.mv;
6894 n += 1;
6895 }
6896 (seeds, n)
6897}
6898
6899/// What [`crate::tile::write_mv`] (private to that module) would spend
6900/// coding `mv` as a residual against `pred`: the joint symbol naming which
6901/// components differ, then each differing component. `None` under the same
6902/// condition [`mv_component_bits`] returns `None`.
6903/// How many frames back `ref_frame` sits from the frame being coded, off the
6904/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
6905/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
6906/// what [`crate::motion::search`] scales its starting step by.
6907fn ref_distance(ref_frame: i8) -> u32 {
6908 let (bits, order_hint, hints) = crate::tile::order_hints();
6909 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
6910 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
6911 .unsigned_abs()
6912 .max(1);
6913 if crate::envflags::env_flag!("EC_TRACE_DIST") {
6914 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
6915 }
6916 d
6917}
6918
6919fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
6920 let diff = (mv.0 - pred.0, mv.1 - pred.1);
6921 let joint = match (diff.0 != 0, diff.1 != 0) {
6922 (false, false) => 0,
6923 (false, true) => 1,
6924 (true, false) => 2,
6925 (true, true) => 3,
6926 };
6927 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
6928 for d in [diff.0, diff.1] {
6929 if d != 0 {
6930 bits += mv_component_bits(d)?;
6931 }
6932 }
6933 Some(bits)
6934}
6935
6936/// Rounds `mv` so that its residual against `pred` is one
6937/// [`crate::tile::write_mv_component`] can actually code: each component's
6938/// difference is either zero or has an even magnitude (the eighth-pel bit
6939/// `allow_high_precision_mv` off always infers as one forces the coded
6940/// magnitude odd one step further in, which comes out even here since this
6941/// crate's motion search works in whole units of that same step). Rounding
6942/// down keeps every coded MV — and so every `nearest_mv` a later block's
6943/// stack votes with — built from an even displacement from `(0, 0)`, so the
6944/// invariant holds without this function seeing the whole stack.
6945fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
6946 let round = |m: i32, p: i32| {
6947 let diff = m - p;
6948 let mag = diff.unsigned_abs() as i32;
6949 let even = mag - mag % 2;
6950 if even == 0 {
6951 p
6952 } else {
6953 p + even * diff.signum()
6954 }
6955 };
6956 (round(mv.0, pred.0), round(mv.1, pred.1))
6957}
6958
6959/// Predicts one `side`-square block by motion compensation from `reference`
6960/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
6961#[allow(clippy::too_many_arguments)]
6962fn mc_trial(
6963 plane: &Plane,
6964 x: usize,
6965 y: usize,
6966 side: usize,
6967 mv: (i32, i32),
6968 luma: bool,
6969 reference: &[u16],
6970 stride: usize,
6971 ref_width: usize,
6972 ref_height: usize,
6973 skip: bool,
6974 base_q_idx: u8,
6975 deadzone: f64,
6976 set: TxbSet, fctx: &crate::decode::FrameCtx,
6977) -> Trial {
6978 let x_q4 = mv_to_q4(x, mv.1, luma);
6979 let y_q4 = mv_to_q4(y, mv.0, luma);
6980 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
6981 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
6982 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
6983 // lane-av1speed: both buffers are per-candidate scratch on the hottest
6984 // path in the encoder, so they live on the stack -- `side` is at most
6985 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
6986 // per motion-compensated trial otherwise.
6987 let mut prediction16 = [0u16; BLOCK * BLOCK];
6988 let prediction16 = &mut prediction16[..side * side];
6989 mc::predict(
6990 reference,
6991 stride,
6992 ref_width,
6993 ref_height,
6994 x_q4,
6995 y_q4,
6996 side,
6997 side,
6998 prediction16, fctx,
6999 );
7000 let mut prediction = [0u8; BLOCK * BLOCK];
7001 let prediction = &mut prediction[..side * side];
7002 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
7003 *dst = src as u8;
7004 }
7005 plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)
7006}
7007
7008/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
7009/// references predict into the `CONV_BUF` intermediate domain
7010/// ([`mc::predict_compound_intermediate`]) and are blended by
7011/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
7012/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
7013/// block, so the encoder's reconstruction is the decoder's.
7014#[allow(clippy::too_many_arguments)]
7015fn mc_trial_compound(
7016 plane: &Plane,
7017 x: usize,
7018 y: usize,
7019 side: usize,
7020 (mv0, mv1): ((i32, i32), (i32, i32)),
7021 luma: bool,
7022 ref0: (&[u16], usize, usize, usize),
7023 ref1: (&[u16], usize, usize, usize),
7024 base_q_idx: u8,
7025 deadzone: f64,
7026 set: TxbSet, fctx: &crate::decode::FrameCtx,
7027) -> Trial {
7028 let mut inter0 = [0i32; BLOCK * BLOCK];
7029 let mut inter1 = [0i32; BLOCK * BLOCK];
7030 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
7031 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
7032 mc::predict_compound_intermediate(
7033 r.0,
7034 r.1,
7035 r.2,
7036 r.3,
7037 mv_to_q4(x, mv.1, luma),
7038 mv_to_q4(y, mv.0, luma),
7039 mc::REF_NO_SCALE,
7040 side,
7041 side,
7042 mc::InterpFilterKind::Regular,
7043 mc::InterpFilterKind::Regular,
7044 dst,
7045 );
7046 }
7047 let mut blended16 = [0u16; BLOCK * BLOCK];
7048 let blended16 = &mut blended16[..side * side];
7049 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
7050 let mut prediction = [0u8; BLOCK * BLOCK];
7051 let prediction = &mut prediction[..side * side];
7052 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
7053 *dst = src as u8;
7054 }
7055 plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set)
7056}
7057
7058/// Codes one 32x32 block of an inter frame as whichever costs least of: each
7059/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
7060/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
7061/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
7062/// coding a real residual (`skip: false`) whenever one prices out cheaper
7063/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
7064/// missing inter `tx_type` symbol (the desync this function's candidates
7065/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
7066/// fixed.
7067///
7068/// The symbol costs this ranks candidates by use fixed contexts (0) for
7069/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
7070/// contexts for those come from its own neighbour bookkeeping
7071/// (`tile::Neighbours`), which is private to that module and not worth
7072/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
7073/// `drl_mode` contexts come straight from `stack`, which is exact, because
7074/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
7075/// the tile writer derives from the same grid state.
7076#[allow(clippy::too_many_arguments)]
7077fn search_inter_block(
7078 luma: &mut Plane,
7079 chroma: &mut [Plane; 2],
7080 (x, y): (usize, usize),
7081 search: &Search,
7082 mode_bits: &[f64; 13],
7083 reference: &Picture,
7084 stack: &MvStack,
7085 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
7086 // for the whole GOP, with the stack this block derives against it. Only
7087 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
7088 // second motion search would double the wall of the stage that already
7089 // owns most of it.
7090 extra: &[(i8, &Picture, &MvStack)],
7091 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
7092 // the caller off the same MI grid the tile writer will (empty unless the
7093 // frame carries `reference_select`).
7094 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
7095 // lane-av1obmc: the mi grid this search's neighbours were published into
7096 // (`record_mi`) and this block's own place in it -- what the OBMC
7097 // candidate's eligibility walk and neighbour plan read, the same state
7098 // the tile writer will read when it codes the `motion_mode` symbol.
7099 grid: &MiGrid,
7100 (mi_row, mi_col): (usize, usize),
7101 (mi_rows, mi_cols): (usize, usize),
7102 fctx: &crate::decode::FrameCtx,
7103) -> (BlockCoeffs, f64) {
7104 // `luma_set` is the INTRA candidates' table; the two inter candidates
7105 // below price their coefficients through `TxbSet::Luma32Inter`, which is
7106 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
7107 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
7108 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
7109 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
7110
7111 // skip / intra_inter symbol costs at a fixed context -- see this
7112 // function's doc comment.
7113 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
7114 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
7115 // `write_single_ref`'s own tree, at the fixed context this pricer uses
7116 // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN
7117 // p1=0,p3=1,p5=1.
7118 let single_ref_bits = |ref_frame: i8| {
7119 symbol_bits(&cdf::SINGLE_REF[0][0], 0)
7120 + if ref_frame == crate::mvstack::GOLDEN_FRAME {
7121 symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1)
7122 } else {
7123 symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0)
7124 }
7125 };
7126
7127 struct Candidate {
7128 cost: f64,
7129 luma: Trial,
7130 u: Trial,
7131 v: Trial,
7132 mode: u8,
7133 skip: bool,
7134 inter: Option<InterInfo>,
7135 /// The mode/mv syntax this candidate pays for, apart from its
7136 /// residual -- what the OBMC candidate below has to re-pay when it
7137 /// re-prices the winner's prediction.
7138 mode_bits: f64,
7139 }
7140 let mut best: Option<Candidate> = None;
7141 let mut consider = |candidate: Candidate| {
7142 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
7143 best = Some(candidate);
7144 }
7145 };
7146
7147 // The chroma trial an intra candidate prices does not depend on `mode`
7148 // at all -- both planes always code `DC_PRED` here (a coding choice this
7149 // search inherited, not this loop's to second-guess) at the same `reach:
7150 // Reach::none()` -- so it is the same call with the same inputs on every
7151 // one of the thirteen iterations below; run it once and reuse the result
7152 // rather than repeat an already-priced transform/quantize/entropy call
7153 // twelve times for nothing (bit-identical: the value each iteration
7154 // reads back is exactly what it used to recompute).
7155 let u_trial = chroma[0].trial(
7156 At {
7157 x: x / 2,
7158 y: y / 2,
7159 side: BLOCK / 2,
7160 reach: Reach::none(),
7161 set: chroma_set,
7162 },
7163 DC_PRED,
7164 0,
7165 search.base_q_idx,
7166 search.deadzone, fctx,
7167 );
7168 let v_trial = chroma[1].trial(
7169 At {
7170 x: x / 2,
7171 y: y / 2,
7172 side: BLOCK / 2,
7173 reach: Reach::none(),
7174 set: chroma_set,
7175 },
7176 DC_PRED,
7177 0,
7178 search.base_q_idx,
7179 search.deadzone, fctx,
7180 );
7181
7182 let intra_modes: Vec<u8> = match search.top_k {
7183 Some(k) if k < search.modes.len() => {
7184 let scored = luma.intra_scores(
7185 At {
7186 x,
7187 y,
7188 side: BLOCK,
7189 reach,
7190 set: luma_set,
7191 },
7192 search.modes,
7193 mode_bits,
7194 search.lambda, fctx,
7195 );
7196 prune_by_sad(search.modes, scored, k)
7197 }
7198 _ => search.modes.to_vec(),
7199 };
7200 census_add(5, 1);
7201 census_add(6, intra_modes.len());
7202 for &mode in &intra_modes {
7203 let luma_trial = luma.trial(
7204 At {
7205 x,
7206 y,
7207 side: BLOCK,
7208 reach,
7209 set: luma_set,
7210 },
7211 mode,
7212 0,
7213 search.base_q_idx,
7214 search.deadzone, fctx,
7215 );
7216 let u = u_trial.clone();
7217 let v = v_trial.clone();
7218 let cost = luma_trial.sse
7219 + u.sse
7220 + v.sse
7221 + search.lambda
7222 * (luma_trial.bits
7223 + u.bits
7224 + v.bits
7225 + mode_bits[usize::from(mode)]
7226 + skip_bits(false)
7227 + intra_inter_bits(false));
7228 consider(Candidate {
7229 cost,
7230 luma: luma_trial,
7231 u,
7232 v,
7233 mode,
7234 skip: false,
7235 inter: None,
7236 mode_bits: mode_bits[usize::from(mode)],
7237 });
7238 }
7239
7240 // The reference frame buffer a spec decoder holds is exactly the true
7241 // (unpadded) coded extent -- a superblock whose partition stops early at
7242 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
7243 // beyond it, so those samples are never part of the decoded picture.
7244 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
7245 // reference sample position clamp), not to this crate's own
7246 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
7247 // here would let a fractional-pel read past the true edge pick up this
7248 // encoder's own uncoded padding instead of the true edge's replicated
7249 // value a decoder computes.
7250 let ref_luma = (
7251 &reference.y,
7252 reference.width,
7253 luma.true_width,
7254 luma.true_height,
7255 );
7256 let ref_u = (
7257 &reference.u,
7258 reference.width / 2,
7259 chroma[0].true_width,
7260 chroma[0].true_height,
7261 );
7262 let ref_v = (
7263 &reference.v,
7264 reference.width / 2,
7265 chroma[1].true_width,
7266 chroma[1].true_height,
7267 );
7268 // Every single-reference mode the writer can code (spec 5.11.24's symbol
7269 // chain, mirrored by `tile::write_inter_mode`), priced with the static
7270 // CDFs at this block's own stack contexts. A candidate is a motion
7271 // vector plus the cheapest syntax that reaches it, so two modes landing
7272 // on the same vector share one set of trials: the added modes cost
7273 // mode-bit arithmetic, not another motion compensation.
7274 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
7275 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
7276 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
7277 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
7278 // the loop cannot reach is never offered below -- every candidate's
7279 // index is one this same loop walks to.
7280 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
7281 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME);
7282 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
7283 (
7284 stack.nearest_mv,
7285 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
7286 InterInfo {
7287 ref1: None,
7288 mv1: (0, 0),
7289 ref_frame: crate::mvstack::LAST_FRAME,
7290 mode: InterMode::NearestMv,
7291 mv: stack.nearest_mv,
7292 ref_mv_idx: 0,
7293 },
7294 ),
7295 // GLOBALMV is the identity model's zero vector -- this encoder writes
7296 // no `gm_params` -- and the cheapest syntax of the four on the static
7297 // content where that vector is also the right one.
7298 (
7299 (0, 0),
7300 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
7301 InterInfo {
7302 ref1: None,
7303 mv1: (0, 0),
7304 ref_frame: crate::mvstack::LAST_FRAME,
7305 mode: InterMode::GlobalMv,
7306 mv: (0, 0),
7307 ref_mv_idx: 0,
7308 },
7309 ),
7310 ];
7311 let near_bits =
7312 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
7313 for idx in 1..=2usize {
7314 if let Some(e) = stack.entries.get(idx) {
7315 cands.push((
7316 e.mv,
7317 near_bits + drl_bits(1, idx),
7318 InterInfo {
7319 ref1: None,
7320 mv1: (0, 0),
7321 ref_frame: crate::mvstack::LAST_FRAME,
7322 mode: InterMode::NearMv,
7323 mv: e.mv,
7324 ref_mv_idx: idx as u8,
7325 },
7326 ));
7327 }
7328 }
7329
7330 let source_block = luma.source_block(x, y, BLOCK);
7331 let (seeds, seed_n) = mv_seeds(stack);
7332 #[cfg(test)]
7333 let t = stage_start();
7334 let found = motion::search(
7335 ref_luma.0,
7336 ref_luma.1,
7337 ref_luma.2,
7338 ref_luma.3,
7339 &source_block,
7340 x,
7341 y,
7342 BLOCK,
7343 BLOCK,
7344 stack.pred_mv,
7345 &seeds[..seed_n],
7346 search.lambda, fctx,
7347 1,
7348 );
7349 #[cfg(test)]
7350 stage_since(0, t);
7351 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
7352 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
7353 // the same vector costs a different residual from each: take the index
7354 // whose residual plus DRL bits is cheapest, not entry 0 by default.
7355 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
7356 cands.push((
7357 mv,
7358 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
7359 InterInfo {
7360 ref1: None,
7361 mv1: (0, 0),
7362 ref_frame: crate::mvstack::LAST_FRAME,
7363 mode: InterMode::NewMv,
7364 mv,
7365 ref_mv_idx,
7366 },
7367 ));
7368 }
7369
7370 // Each extra reference's own `NEWMV` vector, for the compound
7371 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
7372 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
7373 for &(ref_frame, g, gstack) in extra {
7374 let g_ref_bits = single_ref_bits(ref_frame);
7375 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
7376 cands.push((
7377 gstack.nearest_mv,
7378 g_ref_bits
7379 + g_not_new
7380 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
7381 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
7382 InterInfo {
7383 ref1: None,
7384 mv1: (0, 0),
7385 ref_frame,
7386 mode: InterMode::NearestMv,
7387 mv: gstack.nearest_mv,
7388 ref_mv_idx: 0,
7389 },
7390 ));
7391 cands.push((
7392 (0, 0),
7393 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
7394 InterInfo {
7395 ref1: None,
7396 mv1: (0, 0),
7397 ref_frame,
7398 mode: InterMode::GlobalMv,
7399 mv: (0, 0),
7400 ref_mv_idx: 0,
7401 },
7402 ));
7403 // A motion search of this reference's own: without it, GOLDEN/ALTREF
7404 // can only be coded at a vector some neighbour already found, which
7405 // is why they carried a third of the inter blocks at their two
7406 // search-free modes alone.
7407 // The search is skipped when this reference's own NEARESTMV already
7408 // prices out `margin` times better than LAST's best vector does --
7409 // one candidate evaluation (`motion::cost_at`) standing in for a
7410 // whole search of ~50.
7411 let margin = extra_new_skip_margin();
7412 let skip_search = extra_ref_new_mv()
7413 && margin > 0.0
7414 && motion::cost_at(
7415 &g.y,
7416 g.width,
7417 luma.true_width,
7418 luma.true_height,
7419 &source_block,
7420 x,
7421 y,
7422 BLOCK,
7423 BLOCK,
7424 gstack.nearest_mv,
7425 gstack.pred_mv,
7426 search.lambda,
7427 fctx,
7428 ) * margin
7429 <= found.cost;
7430 if extra_ref_new_mv() && !skip_search {
7431 let (gseeds, gn) = mv_seeds(gstack);
7432 #[cfg(test)]
7433 let t = stage_start();
7434 let gfound = motion::search(
7435 &g.y,
7436 g.width,
7437 luma.true_width,
7438 luma.true_height,
7439 &source_block,
7440 x,
7441 y,
7442 BLOCK,
7443 BLOCK,
7444 gstack.pred_mv,
7445 &gseeds[..gn],
7446 search.lambda, fctx,
7447 ref_distance(ref_frame),
7448 );
7449 #[cfg(test)]
7450 stage_since(0, t);
7451 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
7452 extra_new_mvs.push((ref_frame, gmv));
7453 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
7454 cands.push((
7455 gmv,
7456 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
7457 InterInfo {
7458 ref1: None,
7459 mv1: (0, 0),
7460 ref_frame,
7461 mode: InterMode::NewMv,
7462 mv: gmv,
7463 ref_mv_idx,
7464 },
7465 ));
7466 }
7467 }
7468 }
7469
7470 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
7471 // trial set each: both references predict the block and the two
7472 // predictions are averaged, which is what pays on content where neither
7473 // reference alone is right. Priced with the same static-CDF approximation
7474 // the single-reference candidates use, plus the compound-only symbols
7475 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
7476 // The two compound-mode arms, each measured alone on the BD gate before
7477 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
7478 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
7479 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
7480 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
7481 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
7482 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
7483 // the keep rule. Still behind the knob.
7484 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
7485 let half_new = true;
7486 for (ref1, g, cstack) in compound {
7487 let (ref1, g) = (*ref1, *g);
7488 let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME)
7489 .contains(&ref1);
7490 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
7491 + if uni {
7492 // LAST + a backward reference: `comp_ref_type` = bidirectional,
7493 // `comp_ref` LAST, `comp_bwdref` ALTREF.
7494 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
7495 + symbol_bits(&cdf::COMP_REF[0][0], 0)
7496 + symbol_bits(&cdf::COMP_REF[0][1], 0)
7497 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
7498 } else {
7499 // LAST + GOLDEN: unidirectional, `uni_comp_ref` p0/p1/p2.
7500 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
7501 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
7502 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
7503 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
7504 };
7505 let mode_ctx =
7506 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7507 let mode_bits_of =
7508 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7509 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7510 (
7511 cstack.nearest_mv,
7512 mode_bits_of(0),
7513 InterInfo {
7514 ref_frame: crate::mvstack::LAST_FRAME,
7515 mode: InterMode::NearestNearestMv,
7516 mv: cstack.nearest_mv.0,
7517 mv1: cstack.nearest_mv.1,
7518 ref1: Some(ref1),
7519 ref_mv_idx: 0,
7520 },
7521 ),
7522 (
7523 ((0, 0), (0, 0)),
7524 mode_bits_of(6),
7525 InterInfo {
7526 ref_frame: crate::mvstack::LAST_FRAME,
7527 mode: InterMode::GlobalGlobalMv,
7528 mv: (0, 0),
7529 mv1: (0, 0),
7530 ref1: Some(ref1),
7531 ref_mv_idx: 0,
7532 },
7533 ),
7534 ];
7535 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
7536 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
7537 // the stack is deep enough for that walk to read one.
7538 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
7539 let drl = if cstack.entries.len() > 2 {
7540 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
7541 } else {
7542 0.0
7543 };
7544 ccands.push((
7545 (e.mv0, e.mv1),
7546 mode_bits_of(1) + drl,
7547 InterInfo {
7548 ref_frame: crate::mvstack::LAST_FRAME,
7549 mode: InterMode::NearNearMv,
7550 mv: e.mv0,
7551 mv1: e.mv1,
7552 ref1: Some(ref1),
7553 ref_mv_idx: 0,
7554 },
7555 ));
7556 }
7557 // The half-new modes and `NEW_NEWMV`, all seeded from the two
7558 // single-reference searches this block already ran -- no joint search
7559 // of its own. Every residual is priced against stack entry 0, which
7560 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
7561 let cbase = cstack
7562 .entries
7563 .first()
7564 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
7565 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
7566 ccands.push((
7567 (mv, cstack.nearest_mv.1),
7568 mode_bits_of(3) + b0,
7569 InterInfo {
7570 ref_frame: crate::mvstack::LAST_FRAME,
7571 mode: InterMode::NewNearestMv,
7572 mv,
7573 mv1: cstack.nearest_mv.1,
7574 ref1: Some(ref1),
7575 ref_mv_idx: 0,
7576 },
7577 ));
7578 }
7579 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
7580 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
7581 ccands.push((
7582 (cstack.nearest_mv.0, mv1),
7583 mode_bits_of(2) + b1,
7584 InterInfo {
7585 ref_frame: crate::mvstack::LAST_FRAME,
7586 mode: InterMode::NearestNewMv,
7587 mv: cstack.nearest_mv.0,
7588 mv1,
7589 ref1: Some(ref1),
7590 ref_mv_idx: 0,
7591 },
7592 ));
7593 }
7594 let base = cbase;
7595 if let (Some(b0), Some(b1)) = (
7596 mv_residual_bits(mv, base.0),
7597 mv_residual_bits(mv1, base.1),
7598 ) {
7599 ccands.push((
7600 (mv, mv1),
7601 mode_bits_of(7) + b0 + b1,
7602 InterInfo {
7603 ref_frame: crate::mvstack::LAST_FRAME,
7604 mode: InterMode::NewNewMv,
7605 mv,
7606 mv1,
7607 ref1: Some(ref1),
7608 ref_mv_idx: 0,
7609 },
7610 ));
7611 }
7612 }
7613 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
7614 ccands.dedup_by_key(|c| c.0);
7615 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
7616 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
7617 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
7618 for (mvs, bits, info) in ccands {
7619 let luma_trial = mc_trial_compound(
7620 luma, x, y, BLOCK, mvs, true,
7621 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
7622 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
7623 );
7624 let u = mc_trial_compound(
7625 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
7626 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
7627 search.base_q_idx, search.deadzone, chroma_set, fctx,
7628 );
7629 let v = mc_trial_compound(
7630 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
7631 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
7632 search.base_q_idx, search.deadzone, chroma_set, fctx,
7633 );
7634 let skip = luma_trial.levels.iter().all(|&l| l == 0)
7635 && u.levels.iter().all(|&l| l == 0)
7636 && v.levels.iter().all(|&l| l == 0);
7637 let cost = luma_trial.sse
7638 + u.sse
7639 + v.sse
7640 + search.lambda
7641 * (skip_bits(skip)
7642 + intra_inter_bits(true)
7643 + bits
7644 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
7645 consider(Candidate {
7646 cost,
7647 luma: luma_trial,
7648 u,
7649 v,
7650 mode: DC_PRED,
7651 skip,
7652 mode_bits: bits,
7653 inter: Some(info),
7654 });
7655 }
7656 }
7657
7658 // One trial set per distinct (reference, vector) pair: sort, cheapest
7659 // syntax first, and drop the rest of each pair's run.
7660 cands.sort_by(|a, b| {
7661 (a.2.ref_frame, a.0)
7662 .cmp(&(b.2.ref_frame, b.0))
7663 .then(a.1.total_cmp(&b.1))
7664 });
7665 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
7666 census_add(7, cands.len());
7667 {
7668 for (mv, mode_bits_inter, info) in cands {
7669 let (ref_luma, ref_u, ref_v) = match extra
7670 .iter()
7671 .find(|(r, _, _)| *r == info.ref_frame)
7672 {
7673 Some(&(_, g, _)) => (
7674 (&g.y, g.width, luma.true_width, luma.true_height),
7675 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
7676 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
7677 ),
7678 None => (ref_luma, ref_u, ref_v),
7679 };
7680 let luma_trial = mc_trial(
7681 luma,
7682 x,
7683 y,
7684 BLOCK,
7685 mv,
7686 true,
7687 ref_luma.0,
7688 ref_luma.1,
7689 ref_luma.2,
7690 ref_luma.3,
7691 false,
7692 search.base_q_idx,
7693 search.deadzone,
7694 TxbSet::Luma32Inter, fctx,
7695 );
7696 let u = mc_trial(
7697 &chroma[0],
7698 x / 2,
7699 y / 2,
7700 BLOCK / 2,
7701 mv,
7702 false,
7703 ref_u.0,
7704 ref_u.1,
7705 ref_u.2,
7706 ref_u.3,
7707 false,
7708 search.base_q_idx,
7709 search.deadzone,
7710 chroma_set, fctx,
7711 );
7712 let v = mc_trial(
7713 &chroma[1],
7714 x / 2,
7715 y / 2,
7716 BLOCK / 2,
7717 mv,
7718 false,
7719 ref_v.0,
7720 ref_v.1,
7721 ref_v.2,
7722 ref_v.3,
7723 false,
7724 search.base_q_idx,
7725 search.deadzone,
7726 chroma_set, fctx,
7727 );
7728 let skip = luma_trial.levels.iter().all(|&l| l == 0)
7729 && u.levels.iter().all(|&l| l == 0)
7730 && v.levels.iter().all(|&l| l == 0);
7731 let cost = luma_trial.sse
7732 + u.sse
7733 + v.sse
7734 + search.lambda
7735 * (skip_bits(skip)
7736 + intra_inter_bits(true)
7737 + mode_bits_inter
7738 + if skip {
7739 0.0
7740 } else {
7741 luma_trial.bits + u.bits + v.bits
7742 });
7743 consider(Candidate {
7744 cost,
7745 luma: luma_trial,
7746 u,
7747 v,
7748 mode: DC_PRED,
7749 skip,
7750 mode_bits: mode_bits_inter,
7751 inter: Some(info),
7752 });
7753 }
7754 }
7755
7756 let best = best.expect("the search offers at least the intra modes");
7757 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
7758 // offered to the SINGLE-REFERENCE winner only -- libaom's
7759 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
7760 // compound block, so the writer codes no symbol for one. The prediction
7761 // is built by the DECODER's own plan and blend
7762 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
7763 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
7764 // this search's `grid` already carries, so what is priced here is what a
7765 // decoder reconstructs -- never a second implementation of the blend.
7766 //
7767 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
7768 // on). Native crop BD, the standing recipe, with it on against the same
7769 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
7770 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
7771 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
7772 // one UP -- the keep rule wants two down and one flat, so it stays off.
7773 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
7774 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
7775 // things bound it and are the upgrade path: only the 32x32 winner is
7776 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
7777 // that is where libaom cashes most of its OBMC gain), and the symbol/
7778 // residual price here is the static-CDF estimate.
7779 let mut best = best;
7780 let mut motion_won = 0u8;
7781 if let Some(info) = best.inter.filter(|i| {
7782 i.ref1.is_none()
7783 && (crate::envflags::env_flag!("EC_AV1_OBMC")
7784 || warp_on())
7785 }) {
7786 let mut refs: [Option<&Picture>; 8] = [None; 8];
7787 refs[LAST_FRAME as usize] = Some(reference);
7788 for &(r, p, _) in extra {
7789 refs[r as usize] = Some(p);
7790 }
7791 // This block's OWN reference planes: the single-reference winner may
7792 // be one of the extra references, not LAST.
7793 let planes: [(&[u16], usize, usize, usize); 3] =
7794 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
7795 Some(&(_, g, _)) => [
7796 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
7797 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
7798 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
7799 ],
7800 None => [
7801 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7802 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7803 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7804 ],
7805 };
7806 // The alphabet `tile::write_motion_mode` will code this block's
7807 // symbol against, mirrored term for term (libaom
7808 // `motion_mode_allowed`).
7809 let warp_alphabet = warp_on()
7810 && crate::decode::num_proj_ref(
7811 grid,
7812 mi_row,
7813 mi_col,
7814 8,
7815 8,
7816 mi_cols,
7817 mi_rows,
7818 info.ref_frame,
7819 fctx,
7820 ) >= 1;
7821 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
7822 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
7823 if crate::envflags::env_flag!("EC_AV1_OBMC") {
7824 if let Some(pred) = obmc_prediction(
7825 grid,
7826 (mi_row, mi_col),
7827 (mi_rows, mi_cols),
7828 (x, y),
7829 BLOCK,
7830 info.mv,
7831 &refs,
7832 planes,
7833 reference.width,
7834 fctx,
7835 ) {
7836 candidates.push((1, pred));
7837 }
7838 }
7839 if warp_alphabet {
7840 if let Some(pred) = warp_prediction(
7841 grid,
7842 (mi_row, mi_col),
7843 (mi_rows, mi_cols),
7844 (x, y),
7845 BLOCK,
7846 info.mv,
7847 info.ref_frame,
7848 planes,
7849 fctx,
7850 ) {
7851 candidates.push((2, pred));
7852 }
7853 }
7854 for (motion, pred) in candidates {
7855 let luma_trial = luma.code_from_prediction(
7856 x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
7857 TxbSet::Luma32Inter,
7858 );
7859 let u = chroma[0].code_from_prediction(
7860 x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
7861 chroma_set,
7862 );
7863 let v = chroma[1].code_from_prediction(
7864 x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
7865 chroma_set,
7866 );
7867 let skip = luma_trial.levels.iter().all(|&l| l == 0)
7868 && u.levels.iter().all(|&l| l == 0)
7869 && v.levels.iter().all(|&l| l == 0);
7870 let cost = luma_trial.sse
7871 + u.sse
7872 + v.sse
7873 + search.lambda
7874 * (skip_bits(skip)
7875 + intra_inter_bits(true)
7876 + best.mode_bits
7877 + mm(motion)
7878 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
7879 if cost < best.cost + search.lambda * mm(motion_won) {
7880 motion_won = motion;
7881 best = Candidate {
7882 cost,
7883 luma: luma_trial,
7884 u,
7885 v,
7886 mode: DC_PRED,
7887 skip,
7888 mode_bits: best.mode_bits,
7889 inter: best.inter,
7890 };
7891 }
7892 }
7893 }
7894 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
7895 // default OFF): the four 16x16 units of `commit_inter_luma` against the
7896 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
7897 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
7898 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
7899 // it, and it is worse again on the deciding native table: film 1080p
7900 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
7901 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
7902 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
7903 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
7904 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
7905 // +28.4/+47.4/-4.0 -- the native table decides.)
7906 //
7907 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
7908 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
7909 // either, and the census names the row: the split units' own set
7910 // `Luma16Inter` is priced within 1.4% of what it is written at in every
7911 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
7912 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
7913 // so a perfect pricer would split even more, and more splitting is what
7914 // measured worse. The four extra txb_skip/eob symbols simply cost more
7915 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
7916 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
7917 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
7918 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
7919 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
7920 // plain translation, which is not the prediction it was priced from.
7921 let (levels, tx_depth, dcost) = match best.inter.filter(|_| motion_won == 0) {
7922 Some(info) => {
7923 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
7924 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
7925 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7926 };
7927 let second = info.ref1.and_then(|r| {
7928 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
7929 (
7930 info.mv1,
7931 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
7932 )
7933 })
7934 });
7935 match info.ref1.is_some() && second.is_none() {
7936 true => {
7937 luma.commit(x, y, BLOCK, &best.luma);
7938 (best.luma.levels.clone(), 0, 0.0)
7939 }
7940 false => commit_inter_luma(
7941 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,
7942 fctx,
7943 ),
7944 }
7945 }
7946 None => {
7947 luma.commit(x, y, BLOCK, &best.luma);
7948 (best.luma.levels.clone(), 0, 0.0)
7949 }
7950 };
7951 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
7952 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
7953 (
7954 BlockCoeffs {
7955 angle_delta_y: 0,
7956 cfl_alphas: None,
7957 filter_intra: None,
7958 luma: coeffs(&levels, BLOCK),
7959 u: coeffs(&best.u.levels, BLOCK / 2),
7960 v: coeffs(&best.v.levels, BLOCK / 2),
7961 mode: best.mode,
7962 uv_mode: DC_PRED,
7963 skip: best.skip,
7964 inter: best.inter,
7965 motion_mode: motion_won,
7966 eight: None,
7967 dv: None,
7968 palette: None,
7969 palette_uv: None,
7970 tx_depth,
7971 },
7972 best.cost + dcost,
7973 )
7974}
7975
7976/// lane-av1tpl: the strength `k` of the temporal lambda weighting
7977/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
7978/// is what every measurement before this lane was taken on. Swept by
7979/// `EC_AV1_TPL=<k>`.
7980///
7981/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
7982/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
7983/// baseline exactly, which is the control the rest of the table is read
7984/// against:
7985///
7986/// | k | film 1080p | film 2160p | screen |
7987/// |---|---|---|---|
7988/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
7989/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
7990/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
7991/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
7992/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
7993///
7994/// 0.5 is the only arm that is at least flat on every row and down on five of
7995/// the six columns, so it ships as the default. The lookahead pass that feeds
7996/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
7997const TPL_STRENGTH: f64 = 0.5;
7998
7999fn tpl_strength() -> f64 {
8000 std::env::var("EC_AV1_TPL")
8001 .ok()
8002 .and_then(|v| v.parse::<f64>().ok())
8003 .filter(|k| k.is_finite() && *k >= 0.0)
8004 .unwrap_or(TPL_STRENGTH)
8005}
8006
8007/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
8008/// the frame being coded. 1 turns the weighting off; 2 is the shipped
8009/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
8010/// [`tpl_propagating`], which is the map that can actually use them and is
8011/// the default since lane-av1tpl3, so the default window is 8. Swept by
8012/// `EC_AV1_TPL_D=<d>`.
8013///
8014/// The streaming facade holds `depth - 1` pictures back so it feeds
8015/// `encode_inter_frame` the same window `encode_sequence` does; both read
8016/// THIS function, so the two paths cannot disagree about the window.
8017const TPL_DEPTH: usize = 8;
8018
8019/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
8020/// 0.5 is libaom's own square-root compression of its dependence ratio.
8021const TPL_POWER: f64 = 0.5;
8022
8023/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
8024/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
8025///
8026/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
8027/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
8028/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
8029///
8030/// | k | D | p | film 1080p | film 2160p | screen |
8031/// |---|---|---|---|---|---|
8032/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
8033/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
8034/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
8035/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
8036/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
8037/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
8038/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
8039/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
8040/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
8041/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
8042/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
8043/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
8044///
8045/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
8046/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
8047/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
8048/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
8049/// 0.1..0.4 UP on film 2160p, so it shipped off.
8050///
8051/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
8052/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
8053/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
8054/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
8055/// wherever the window leans on a flat bar, which is exactly where coding is
8056/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
8057/// (libaom's own granularity) puts a busy cell's denominator next to the flat
8058/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
8059/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
8060/// the same native gate (baseline = the shipped one-frame map):
8061///
8062/// | arm | film 1080p | film 2160p | screen |
8063/// |---|---|---|---|
8064/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
8065/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
8066/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
8067/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
8068/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
8069/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
8070/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
8071/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
8072/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
8073/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
8074///
8075/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
8076/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
8077/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
8078/// floor is a real effect on the ratio and never a win once the aggregation
8079/// is in -- the aggregation is the same fix, done where libaom does it.
8080fn tpl_propagating() -> bool {
8081 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
8082}
8083
8084pub(crate) fn tpl_depth() -> usize {
8085 std::env::var("EC_AV1_TPL_D")
8086 .ok()
8087 .and_then(|v| v.parse::<usize>().ok())
8088 .filter(|d| *d >= 1)
8089 .unwrap_or(TPL_DEPTH)
8090 .max(1)
8091}
8092
8093/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
8094/// process, so the gate can price it against the encode it rides on.
8095static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
8096
8097/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
8098/// the winning displacement and its SAD.
8099///
8100/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
8101/// the left/above winners, first-best tie-break. Built once on the frame's
8102/// own thread and read-only afterwards, so it cannot make a tile's bytes
8103/// depend on the thread count.
8104fn tpl_coarse_pass(
8105 cur: &[u8],
8106 next: &[u8],
8107 width: usize,
8108 height: usize,
8109) -> Vec<((i32, i32), u32)> {
8110 let (cells_x, cells_y) = (width / 16, height / 16);
8111 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
8112 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
8113 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
8114 return u32::MAX;
8115 }
8116 let (sx, sy) = (sx as usize, sy as usize);
8117 let mut sum = 0u32;
8118 for r in 0..16 {
8119 let a = &next[(by + r) * width + bx..][..16];
8120 let b = &cur[(sy + r) * width + sx..][..16];
8121 sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>();
8122 }
8123 sum
8124 };
8125 let mut out = Vec::with_capacity(cells_x * cells_y);
8126 let mut above = vec![(0i32, 0i32); cells_x];
8127 for cy in 0..cells_y {
8128 let mut left = (0i32, 0i32);
8129 for cx in 0..cells_x {
8130 let (bx, by) = (cx * 16, cy * 16);
8131 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
8132 for cand in [left, above[cx]] {
8133 if cand != (0, 0) {
8134 let s = sad(bx, by, cand);
8135 if s < best.0 {
8136 best = (s, cand);
8137 }
8138 }
8139 }
8140 for step in [8i32, 4, 2, 1] {
8141 let centre = best.1;
8142 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
8143 let mv = (centre.0 + dx, centre.1 + dy);
8144 if mv.0.abs() > 32 || mv.1.abs() > 32 {
8145 continue;
8146 }
8147 let s = sad(bx, by, mv);
8148 if s < best.0 {
8149 best = (s, mv);
8150 }
8151 }
8152 }
8153 left = best.1;
8154 above[cx] = best.1;
8155 out.push((best.1, best.0));
8156 }
8157 }
8158 out
8159}
8160
8161/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
8162/// transform: here, the mean absolute deviation of the cell from its own DC.
8163/// It is the denominator every propagated cost is read against, so only its
8164/// SHAPE across the frame matters, not its scale.
8165fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
8166 let (cells_x, cells_y) = (width / 16, height / 16);
8167 let mut out = Vec::with_capacity(cells_x * cells_y);
8168 for cy in 0..cells_y {
8169 for cx in 0..cells_x {
8170 let (bx, by) = (cx * 16, cy * 16);
8171 let mut sum = 0u32;
8172 for r in 0..16 {
8173 sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>();
8174 }
8175 let dc = ((sum + 128) / 256) as u8;
8176 let mut cost = 0u32;
8177 for r in 0..16 {
8178 cost += frame[(by + r) * width + bx..][..16]
8179 .iter()
8180 .map(|&p| u32::from(p.abs_diff(dc)))
8181 .sum::<u32>();
8182 }
8183 out.push(cost);
8184 }
8185 }
8186 out
8187}
8188
8189/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
8190/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
8191/// splats its own area, at its winning displacement, onto the (at most four)
8192/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
8193fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
8194 let start = std::time::Instant::now();
8195 let (cells_x, cells_y) = (width / 16, height / 16);
8196 let pass = tpl_coarse_pass(cur, next, width, height);
8197 let mut area = vec![0.0f64; cells_x * cells_y];
8198 for cy in 0..cells_y {
8199 for cx in 0..cells_x {
8200 let (mv, _) = pass[cy * cells_x + cx];
8201 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
8202 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
8203 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
8204 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
8205 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
8206 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
8207 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
8208 }
8209 }
8210 }
8211 }
8212 TPL_NANOS.fetch_add(
8213 start.elapsed().as_nanos() as u64,
8214 std::sync::atomic::Ordering::Relaxed,
8215 );
8216 area
8217}
8218
8219/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
8220/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
8221/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
8222/// Decreasing in referenced-ness (a block the next frame leans on is coded
8223/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
8224/// total lambda scale is only redistributed, never moved -- a global move is
8225/// the thing lane-av1lambda already measured inert.
8226fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
8227 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
8228 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
8229 let mut out = Vec::with_capacity(sb_cols * sb_rows);
8230 for sr in 0..sb_rows {
8231 for sc in 0..sb_cols {
8232 let mut sum = 0.0;
8233 for r in 0..4 {
8234 for c in 0..4 {
8235 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
8236 }
8237 }
8238 let w_rel = sum / 16.0 / mean;
8239 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
8240 }
8241 }
8242 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
8243 let mut hist = [0usize; 8];
8244 for w in map {
8245 hist[((w / mean * 2.0) as usize).min(7)] += 1;
8246 }
8247 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
8248 eprintln!(
8249 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
8250 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
8251 map.len(),
8252 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
8253 );
8254 }
8255 out
8256}
8257
8258/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
8259/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
8260/// much of the WHOLE lookahead window leans on that cell.
8261///
8262/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
8263/// coarse pass gives a displacement and an inter cost; a cell's own
8264/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
8265/// cell well saves the frames that predict from it -- and it is splatted,
8266/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
8267/// displacement lands on. Walking `f` from the far end of the window back to
8268/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
8269/// area map could not do at all.
8270///
8271/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
8272/// factor over the frame is exactly 1: a cell the window leans on is coded
8273/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
8274/// scale only moves around, never up or down -- a global move is what
8275/// lane-av1lambda already measured inert.
8276fn tpl_lambda_factors(frames: &[&[u8]], width: usize, height: usize, k: f64) -> Vec<f64> {
8277 let start = std::time::Instant::now();
8278 let (cells_x, cells_y) = (width / 16, height / 16);
8279 let cells = cells_x * cells_y;
8280 let levels = frames.len();
8281 let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect();
8282 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
8283 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
8284 .collect();
8285 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
8286 for f in (1..levels).rev() {
8287 for cy in 0..cells_y {
8288 for cx in 0..cells_x {
8289 let ci = cy * cells_x + cx;
8290 let (mv, inter) = passes[f - 1][ci];
8291 let saved = f64::from(intra[f][ci].saturating_sub(inter));
8292 let propagate = saved + mc_dep[f][ci];
8293 if propagate <= 0.0 {
8294 continue;
8295 }
8296 // The 16x16 window of the PREVIOUS frame this cell predicted
8297 // from, spread over the cells it overlaps.
8298 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
8299 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
8300 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
8301 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
8302 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
8303 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
8304 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
8305 }
8306 }
8307 }
8308 }
8309 }
8310 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
8311 // tail (a nearly flat cell the window leans on has a tiny denominator),
8312 // and at p = 1 that tail slams into the clamp. libaom reads its own
8313 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
8314 // sweeps the exponent, 1 being the raw ratio.
8315 let power = std::env::var("EC_AV1_TPL_P")
8316 .ok()
8317 .and_then(|v| v.parse::<f64>().ok())
8318 .filter(|p| p.is_finite() && *p > 0.0)
8319 .unwrap_or(TPL_POWER);
8320 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
8321 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
8322 // `0` to take either back out); `FLOOR` defaults to off.
8323 //
8324 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
8325 // frame's own mean intra cost. A cell of flat content has a near-zero
8326 // MAD, so its ratio explodes exactly where coding is cheap.
8327 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
8328 // and mc_dep are summed over the 64x64 superblock first -- libaom's
8329 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
8330 // per-16x16 numbers), which is also what makes the ratio survive one
8331 // flat cell next to a busy one.
8332 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
8333 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
8334 // harder than the `p` exponent alone can.
8335 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
8336 .ok()
8337 .and_then(|v| v.parse::<f64>().ok())
8338 .filter(|f| f.is_finite() && *f >= 0.0)
8339 .unwrap_or(0.0);
8340 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
8341 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
8342 let intra_mean =
8343 intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
8344 let floor = floor_frac * intra_mean;
8345 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
8346 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
8347 // every cell under it. The edge groups are partial and summed as they are.
8348 let ratio: Vec<f64> = if sb_agg {
8349 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
8350 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
8351 for cy in 0..cells_y {
8352 for cx in 0..cells_x {
8353 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
8354 e.0 += mc_dep[0][cy * cells_x + cx];
8355 e.1 += denom(cy * cells_x + cx);
8356 }
8357 }
8358 (0..cells)
8359 .map(|c| {
8360 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
8361 dep / den.max(1.0)
8362 })
8363 .collect()
8364 } else {
8365 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
8366 };
8367 let mut out: Vec<f64> = ratio
8368 .iter()
8369 .map(|&r| {
8370 let r = if log_beta { (1.0 + r).log2() } else { r };
8371 (1.0 + k * r).powf(-power)
8372 })
8373 .collect();
8374 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
8375 for f in &mut out {
8376 *f = (*f / mean).clamp(0.25, 4.0);
8377 }
8378 TPL_NANOS.fetch_add(
8379 start.elapsed().as_nanos() as u64,
8380 std::sync::atomic::Ordering::Relaxed,
8381 );
8382 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
8383 let mut hist = [0usize; 8];
8384 for &f in &out {
8385 hist[((f * 4.0) as usize).min(7)] += 1;
8386 }
8387 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
8388 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
8389 eprintln!(
8390 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
8391 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
8392 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
8393 );
8394 }
8395 out
8396}
8397
8398/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
8399/// references name, which slot it refreshes, whether it is shown when it is
8400/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
8401/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
8402/// 0/2 alternation, every frame shown, every reference in the past).
8403///
8404/// The sign bias is carried rather than derived here because only the caller
8405/// knows what order hint each slot holds; it is armed onto the tile writer
8406/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
8407/// the writer scans the same stacks the decoder will.
8408#[derive(Debug, Clone, Copy)]
8409pub(crate) struct PyramidFrame {
8410 /// The slot `LAST_FRAME` (and every reference this encoder does not name
8411 /// apart) reads.
8412 pub last_slot: u8,
8413 /// The single slot `refresh_frame_flags` sets.
8414 pub self_slot: u8,
8415 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
8416 /// pyramid, which is what makes `sign_bias`'s last entry true.
8417 pub altref_slot: u8,
8418 /// `show_frame`: false for a hidden frame, output later by a
8419 /// `show_existing_frame` header.
8420 pub show_frame: bool,
8421 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
8422 pub sign_bias: crate::mvstack::SignBiasTable,
8423}
8424
8425/// Encodes one picture as an inter frame predicting from `reference`'s
8426/// reconstruction, which the caller decoded (or, for the frame right after
8427/// the key frame, is the key frame's own reconstruction).
8428pub(crate) fn encode_inter_frame(
8429 picture: &Picture,
8430 reference: &Picture,
8431 base_q_idx: u8,
8432 deadzone: f64,
8433 order_hint: u32,
8434 // The order hint each of the seven `ref_frame_idx` entries names, which a
8435 // decoder reads out of its own reference state -- only spec 5.9.22's
8436 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
8437 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
8438 // callers that follow this crate's own flat slot plan.
8439 order_hints: [u32; 7],
8440 render: (usize, usize),
8441 // The tables this frame's writer starts from: what the previous frame
8442 // stored into the slot this one's `primary_ref_frame` names. `None`
8443 // starts from the defaults, which is right only for the frame straight
8444 // after a key frame.
8445 start_cdfs: Option<&crate::cdf_state::Cdfs>,
8446 // The key frame's own (padded) reconstruction, which every frame of the
8447 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
8448 // with `LAST_FRAME` alone, exactly as before.
8449 golden: Option<&Picture>,
8450 // The frame two back, held in the slot this frame is about to refresh
8451 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
8452 // inter frames of a GOP, where the frame two back IS the key frame.
8453 altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,
8454 // Where this frame sits in the coding-order pyramid; `None` is the flat
8455 // one-shown-frame-per-picture stream this encoder wrote before.
8456 pyramid: Option<PyramidFrame>,
8457 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
8458 // them), padded like this one -- the lookahead window the per-block
8459 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
8460 // EMPTY slice codes the frame at one lambda, as before.
8461 lookahead: &[Picture],
8462) -> Result<Encoded> {
8463 picture.check()?;
8464 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
8465 return Err(Error::unsupported(
8466 "AV1 encode",
8467 "an inter frame is coded only for a picture that is a whole number \
8468 of 64x64 superblocks -- the inter tile writer never splits a \
8469 superblock's partition below that",
8470 ));
8471 }
8472 if reference.width != picture.width || reference.height != picture.height {
8473 return Err(Error::unsupported(
8474 "AV1 encode",
8475 "the reference picture must be the same size as the one being coded",
8476 ));
8477 }
8478
8479 // The single slot this crate's inter frames ever predict from or
8480 // refresh (`inter_frame_headers`'s contract): every frame both reads and
8481 // overwrites slot 0, so the frame just coded is always what the next one
8482 // predicts against.
8483 const LAST_SLOT: u8 = 0;
8484 // Slot 0 and slot 2 alternate so the frame two back survives one more
8485 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
8486 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
8487 // in the very slot it will overwrite.
8488 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
8489 let last_slot = pyramid.map_or(
8490 if order_hint <= 1 {
8491 LAST_SLOT
8492 } else if (order_hint - 1) % 2 == 1 {
8493 0
8494 } else {
8495 2
8496 },
8497 |p| p.last_slot,
8498 );
8499 // `render`, not `picture.width`/`picture.height`: `picture` here is
8500 // already padded to a whole number of superblocks (`encode_sequence`'s
8501 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
8502 // every true-edge clamp downstream) must come from the frame's real,
8503 // unpadded size, same as `key_frame_headers_colour` takes `render` and
8504 // not the padded picture in `encode_key_frame_inner`.
8505 let (seq, mut header) = inter_frame_headers_slots(
8506 render.0,
8507 render.1,
8508 base_q_idx,
8509 order_hint,
8510 last_slot,
8511 self_slot,
8512 match pyramid {
8513 Some(p) => p.altref_slot,
8514 None if altref.is_some() => self_slot,
8515 None => GOLDEN_SLOT,
8516 },
8517 )?;
8518 header.render_width = render.0 as u32;
8519 header.render_height = render.1 as u32;
8520 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
8521 // The order hint behind each `ref_frame_idx` entry. The flat path's own
8522 // slot plan (`inter_frame_headers_slots`) is: every reference but
8523 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
8524 // `ALTREF_FRAME`, which reads the frame two back when there is one;
8525 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
8526 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
8527 header.order_hints = order_hints;
8528 header.reference_select = reference_select();
8529 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
8530 // per-reference order-hint distance is read by the block SEARCH, which
8531 // runs long before the writer arms these (the distance-scaled search step
8532 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
8533 // never reached the tool).
8534 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
8535 if let Some(p) = pyramid {
8536 header.show_frame = p.show_frame;
8537 header.showable_frame = !p.show_frame;
8538 header.ref_frame_sign_bias = p.sign_bias;
8539 }
8540 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
8541 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
8542 // block inside this frame codes and searches its own `tx_depth`, the same
8543 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
8544 let tx_select = tx_select() && tx_select_inter();
8545 if tx_select {
8546 header.tx_mode = TxMode::Select;
8547 }
8548
8549 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
8550 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
8551 // here (see `encode_key_frame_inner`).
8552 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
8553 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
8554 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
8555 // This frame's own `allow_screen_content_tools`. It can only be set when
8556 // the SEQUENCE offers the bit at all, which is the key frame's decision
8557 // ([`SEQ_SCREEN`]): a frame header that contradicts
8558 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
8559 // encode.
8560 let screen = seq_screen()
8561 && screen_content(&picture_y8, picture.width, true_width, true_height);
8562 header.allow_screen_content_tools = screen;
8563 // The search prices coefficients against the tables this frame's writer
8564 // starts from, not against the defaults (lane-av1txbits) -- but only on a
8565 // frame the screen detector said no to (lane-av1price2): armed HERE, after
8566 // `screen` exists, and again on every search/tile worker below.
8567 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
8568 let mut luma = Plane {
8569 source: &picture_y8,
8570 reconstruction: vec![128; picture_y8.len()],
8571 width: picture.width,
8572 height: picture.height,
8573 true_width,
8574 true_height,
8575 tile_x0: 0,
8576 tile_y0: 0,
8577 tile_x1: picture.width,
8578 tile_y1: picture.height,
8579 ctx: CoefCtxMap::default(),
8580 };
8581 let mut chroma = [
8582 Plane {
8583 source: &picture_u8,
8584 reconstruction: vec![128; picture_u8.len()],
8585 width: picture.width / 2,
8586 height: picture.height / 2,
8587 true_width: true_width / 2,
8588 true_height: true_height / 2,
8589 tile_x0: 0,
8590 tile_y0: 0,
8591 tile_x1: picture.width / 2,
8592 tile_y1: picture.height / 2,
8593 ctx: CoefCtxMap::default(),
8594 },
8595 Plane {
8596 source: &picture_v8,
8597 reconstruction: vec![128; picture_v8.len()],
8598 width: picture.width / 2,
8599 height: picture.height / 2,
8600 true_width: true_width / 2,
8601 true_height: true_height / 2,
8602 tile_x0: 0,
8603 tile_y0: 0,
8604 tile_x1: picture.width / 2,
8605 tile_y1: picture.height / 2,
8606 ctx: CoefCtxMap::default(),
8607 },
8608 ];
8609
8610 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
8611 let search = Search {
8612 base_q_idx,
8613 deadzone,
8614 lambda: lambda_scale() * step * step,
8615 modes: &KEY_FRAME_MODES,
8616 top_k: prune_top_k_inter(),
8617 screen,
8618 };
8619 let mode_bits_table = inter_mode_bits();
8620 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
8621 // this frame the NEXT one predicts from. Off (`None`) without a
8622 // lookahead picture or at strength 0.
8623 let tpl_k = tpl_strength();
8624 let window: Vec<&Picture> = lookahead
8625 .iter()
8626 .take_while(|n| n.width == picture.width && n.height == picture.height)
8627 .collect();
8628 let tpl_sources: Vec<Vec<u8>> =
8629 window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect();
8630 let tpl_cells_x = picture.width / 16;
8631 let tpl_factors: Option<Vec<f64>> = (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| {
8632 if tpl_propagating() {
8633 let mut frames: Vec<&[u8]> = vec![&picture_y8];
8634 frames.extend(tpl_sources.iter().map(Vec::as_slice));
8635 tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k)
8636 } else {
8637 // The shipped map is one factor per 64x64; it is spread over that
8638 // superblock's own 16 cells so the application site below (which
8639 // averages the four cells of a 32x32 block) reads exactly the
8640 // superblock factor, whichever map fed it.
8641 let map =
8642 tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
8643 let cells_y = picture.height / 16;
8644 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
8645 (0..tpl_cells_x * cells_y)
8646 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
8647 .collect()
8648 }
8649 });
8650
8651 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
8652 // coding surface's: `blocks` carries one entry per 32x32 block the tile
8653 // writer will actually visit, same count it checks `blocks.len()`
8654 // against, which is fewer than the padded surface's own block count
8655 // whenever the true size is not a 64x64 multiple.
8656 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
8657 let (cols, rows) = (cols as usize, rows as usize);
8658 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
8659 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
8660 // This frame's tile grid, as in `encode_key_frame_inner`.
8661 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
8662 let layout =
8663 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
8664 header.tile_info = tile_info_of(&layout, 1);
8665 let header_tile_info = header.tile_info.clone();
8666 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
8667 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
8668 // once per frame (lane-av1rd2), not once per block, which is a whole
8669 // plane's map per 32x32 block and now per leaf too.
8670 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
8671 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
8672 // availability -- intra edges and the MV stack's scans alike -- already
8673 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
8674 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
8675 // giving each job its own planes and its own `MiGrid` therefore leaves
8676 // every decision, and so every coded bit, exactly where the whole-frame
8677 // loop left it, at any tile count and any thread count.
8678 let (frame_width, frame_height) = (picture.width, picture.height);
8679 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
8680 let [cb, cr] = &mut chroma;
8681 let chroma_out = [
8682 crate::par::Shared::new(&mut cb.reconstruction),
8683 crate::par::Shared::new(&mut cr.reconstruction),
8684 ];
8685 let search_tile = |index: usize,
8686 fctx: &crate::decode::FrameCtx|
8687 -> Result<Vec<(usize, Quadrant)>> {
8688 // Thread-local, and this job may be running on a `search_tiles`
8689 // worker: `ref_distance`'s order-hint distance (the scaled motion
8690 // search step) is read by the SEARCH, so every worker arms it or the
8691 // tile's bits depend on the thread count.
8692 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
8693 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
8694 let rect = layout.rect(index);
8695 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
8696 let mut chroma = [
8697 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8698 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8699 ];
8700 clip_planes_to_tile(&mut luma, &mut chroma, rect);
8701 let mut grid = MiGrid::new(mi_cols, mi_rows);
8702 grid.set_sign_bias(sign_bias);
8703 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
8704 // built once per tile job (`obmc_prediction`).
8705 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
8706 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
8707 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
8708 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
8709 grid.set_tile_bounds(
8710 rect.mi_row0 as usize,
8711 rect.mi_col0 as usize,
8712 rect.mi_row1 as usize,
8713 rect.mi_col1 as usize,
8714 );
8715 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
8716 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
8717 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
8718 for quadrant in 0..4 {
8719 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
8720 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
8721 // decision under it (partition, mode, tx, motion) reads
8722 // `search.lambda`, so scaling the one field here scales all
8723 // of them. 32x32 and not the 16x16 the map is built at
8724 // because the whole-vs-split comparison right below weighs
8725 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
8726 // would make those two numbers incomparable.
8727 let search = match &tpl_factors {
8728 Some(f) => {
8729 let mean = (0..4)
8730 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
8731 .sum::<f64>()
8732 / 4.0;
8733 Search { lambda: search.lambda * mean, ..search }
8734 }
8735 None => search,
8736 };
8737 // Same filter as the tile writer's: a quadrant whose own mi
8738 // origin is not inside the true frame is never coded.
8739 if r32 >= rows || c32 >= cols {
8740 continue;
8741 }
8742 // spec `decode_partition`'s hasRows/hasCols recomputed at this
8743 // 32x32 block's own half (`crate::tile::has_half`), same as
8744 // the key frame search: the true frame edge can fall inside a
8745 // quadrant a superblock-level check already let through, and
8746 // such a quadrant cannot be left whole -- it must split into
8747 // the 16x16 leaves that are actually inside the true frame
8748 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
8749 // arm).
8750 let (has_cols32, has_rows32) = (
8751 crate::tile::has_half(
8752 c32 as u32 * crate::tile::BLOCK_MI,
8753 crate::tile::BLOCK_MI,
8754 header.mi_cols,
8755 ),
8756 crate::tile::has_half(
8757 r32 as u32 * crate::tile::BLOCK_MI,
8758 crate::tile::BLOCK_MI,
8759 header.mi_rows,
8760 ),
8761 );
8762 if has_cols32 && has_rows32 {
8763 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
8764 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
8765 let stack =
8766 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
8767 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
8768 (crate::mvstack::GOLDEN_FRAME, golden),
8769 (crate::mvstack::ALTREF_FRAME, altref),
8770 ]
8771 .into_iter()
8772 .filter_map(|(r, pic)| {
8773 pic.map(|p| {
8774 (
8775 r,
8776 p,
8777 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
8778 )
8779 })
8780 })
8781 .collect();
8782 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
8783 .iter()
8784 .map(|(r, p, st)| (*r, *p, st))
8785 .collect();
8786 // The COMPOUND stack of each `LAST` + extra pair, off the
8787 // same grid (and the same armed sign bias) the tile writer
8788 // rebuilds it from. Empty unless this frame codes
8789 // `reference_select`, which is what gates the syntax.
8790 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
8791 if header.reference_select {
8792 extra_stacks
8793 .iter()
8794 .map(|&(r, p, _)| {
8795 (
8796 r,
8797 p,
8798 crate::mvstack::find_mv_stack_compound(
8799 &grid,
8800 mi_row,
8801 mi_col,
8802 8,
8803 8,
8804 (crate::mvstack::LAST_FRAME, r),
8805 mi_cols,
8806 mi_rows,
8807 grid.sign_bias_table(),
8808 &[(0, 0); 7],
8809 None,
8810 ),
8811 )
8812 })
8813 .collect()
8814 } else {
8815 Vec::new()
8816 };
8817
8818 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
8819 let (block, mut cost_whole) = search_inter_block(
8820 &mut luma,
8821 &mut chroma,
8822 (x, y),
8823 &search,
8824 &mode_bits_table,
8825 reference,
8826 &stack,
8827 &extra,
8828 &compound,
8829 &grid,
8830 (mi_row, mi_col),
8831 (mi_rows, mi_cols),
8832 fctx,
8833 );
8834 cost_whole += search.lambda * partition_bits(BLOCK, false);
8835 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
8836
8837 // What four 16x16 leaves cost instead (spec
8838 // PARTITION_SPLIT at BLOCK_32X32, which
8839 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
8840 // already writes for a straddling quadrant). Each leaf is
8841 // searched against the reconstruction -- and the `mi`
8842 // grid -- the ones before it left, exactly as the writer
8843 // and the decoder will read them.
8844 //
8845 // A block the whole-32 search left skipped (no residual
8846 // at all) is not offered the split: libaom prunes the
8847 // same way at cpu-used 6, and it is where the wall would
8848 // otherwise go on static content.
8849 let leaf_positions: Vec<(usize, usize)> = (0..4)
8850 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
8851 .collect();
8852 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
8853 crate::tile::has_half(
8854 sc as u32 * crate::tile::SUB_MI,
8855 crate::tile::SUB_MI,
8856 header.mi_cols,
8857 ) && crate::tile::has_half(
8858 sr as u32 * crate::tile::SUB_MI,
8859 crate::tile::SUB_MI,
8860 header.mi_rows,
8861 )
8862 });
8863 // The breakout above: a 32x32 block that codes almost
8864 // nothing is not offered the split at all.
8865 let breakout = split_breakout_coeffs();
8866 let split = (!block.skip
8867 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
8868 && (breakout == 0 || block.luma.len() > 4 * breakout)
8869 && leaves_legal
8870 && split_inter_blocks())
8871 .then(|| {
8872 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
8873 let mut cost = search.lambda * partition_bits(BLOCK, true);
8874 let mut leaves = Vec::with_capacity(4);
8875 for &(sr, sc) in &leaf_positions {
8876 let (mi_row, mi_col) = (sr * 4, sc * 4);
8877 let (lx, ly) = (sc * SUB, sr * SUB);
8878 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
8879 let stack = find_mv_stack(
8880 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
8881 );
8882 let cstacks = leaf_compound_stacks(
8883 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
8884 header.reference_select, golden, altref,
8885 );
8886 let (leaf, leaf_cost) = code_square_inter(
8887 &mut luma,
8888 &mut chroma,
8889 (lx, ly),
8890 SUB,
8891 &search,
8892 &mode_bits_table,
8893 reference,
8894 &stack,
8895 &cstacks,
8896 &grid,
8897 (mi_row, mi_col),
8898 (mi_rows, mi_cols),
8899 &obmc_refs,
8900 fctx,
8901 );
8902 let leaf_cost = leaf_cost
8903 + search.lambda * partition_bits(SUB, false);
8904 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
8905
8906 // And what four 8x8 leaves cost instead --
8907 // the same tree one step further down, which
8908 // the writer codes as a real PARTITION_SPLIT
8909 // at BLOCK_16X16 (lane-av1rd2). Same
8910 // skipped-block prune as the level above.
8911 let eight = (!leaf.skip
8912 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
8913 && (breakout == 0 || leaf.luma.len() > breakout)
8914 && split_inter_8())
8915 .then(|| {
8916 restore(
8917 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
8918 );
8919 let mut cost8 = search.lambda
8920 * (partition_bits(SUB, true)
8921 + 4.0 * partition_bits(8, false));
8922 let mut eight = Vec::with_capacity(4);
8923 for i in 0..4 {
8924 let (mr, mc) =
8925 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
8926 let stack8 = find_mv_stack(
8927 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
8928 );
8929 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
8930 if header.reference_select && leaf_compound() {
8931 [
8932 (crate::mvstack::GOLDEN_FRAME, golden),
8933 (crate::mvstack::ALTREF_FRAME, altref),
8934 ]
8935 .into_iter()
8936 .filter_map(|(r, pic)| {
8937 pic.map(|p| {
8938 (
8939 r,
8940 p,
8941 crate::mvstack::find_mv_stack_compound(
8942 &grid, mr, mc, 2, 2,
8943 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
8944 grid.sign_bias_table(), &[(0, 0); 7], None,
8945 ),
8946 )
8947 })
8948 })
8949 .collect()
8950 } else {
8951 Vec::new()
8952 };
8953 let (leaf8, cost) = code_square_inter(
8954 &mut luma,
8955 &mut chroma,
8956 (lx + (i % 2) * 8, ly + (i / 2) * 8),
8957 8,
8958 &search,
8959 &mode_bits_table,
8960 reference,
8961 &stack8,
8962 &cstacks8,
8963 &grid,
8964 (mr, mc),
8965 (mi_rows, mi_cols),
8966 &obmc_refs,
8967 fctx,
8968 );
8969 cost8 += cost;
8970 record_mi(&mut grid, mr, mc, 2, leaf8.inter);
8971 eight.push(leaf8);
8972 }
8973 (eight, cost8)
8974 });
8975 match eight {
8976 Some((eight, cost8)) if cost8 < leaf_cost => {
8977 partition_hit(3);
8978 cost += cost8;
8979 leaves.push(BlockCoeffs {
8980 eight: Some(eight),
8981 ..BlockCoeffs::default()
8982 });
8983 continue;
8984 }
8985 Some(_) => restore(
8986 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
8987 ),
8988 None => {}
8989 }
8990 partition_hit(2);
8991 cost += leaf_cost;
8992 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter);
8993 leaves.push(leaf);
8994 }
8995 (leaves, cost)
8996 });
8997 if let Some((leaves, cost)) = split {
8998 if cost < cost_whole {
8999 // The leaves' own `mi` cells are already in the
9000 // grid, and their reconstruction is what the
9001 // planes hold.
9002 partition_hit(1);
9003 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
9004 continue;
9005 }
9006 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
9007 }
9008 partition_hit(0);
9009 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);
9010 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
9011 } else {
9012 // The sub-positions actually inside the true frame, same
9013 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
9014 let sub_positions: Vec<(usize, usize)> = (0..4)
9015 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
9016 .filter(|&(sr, sc)| {
9017 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
9018 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
9019 })
9020 .collect();
9021 // Each leaf searches intra against its own `NEARESTMV`
9022 // candidate (`code_square_inter`), same real-inter choice
9023 // `search_inter_block` makes for a whole 32x32 block, at
9024 // this leaf's own 4x4-mi mv-stack window -- unless the
9025 // leaf's own half itself straddles the true edge, which
9026 // it codes as two (or one, at a true corner) 8x8 leaves
9027 // (`crate::tile::write_leaf8`'s inter counterpart),
9028 // mirroring the key frame search's straddling-16x16
9029 // handling above (lane-av1inter8).
9030 let mut leaves = Vec::with_capacity(sub_positions.len());
9031 for (sr, sc) in sub_positions {
9032 let (has_cols16, has_rows16) = (
9033 crate::tile::has_half(
9034 sc as u32 * crate::tile::SUB_MI,
9035 crate::tile::SUB_MI,
9036 header.mi_cols,
9037 ),
9038 crate::tile::has_half(
9039 sr as u32 * crate::tile::SUB_MI,
9040 crate::tile::SUB_MI,
9041 header.mi_rows,
9042 ),
9043 );
9044 if has_cols16 && has_rows16 {
9045 let (x, y) = (sc * SUB, sr * SUB);
9046 let (mi_row, mi_col) = (sr * 4, sc * 4);
9047 let stack = find_mv_stack(
9048 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
9049 );
9050 let cstacks = leaf_compound_stacks(
9051 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
9052 header.reference_select, golden, altref,
9053 );
9054 let (block, _) = code_square_inter(
9055 &mut luma,
9056 &mut chroma,
9057 (x, y),
9058 SUB,
9059 &search,
9060 &mode_bits_table,
9061 reference,
9062 &stack,
9063 &cstacks,
9064 &grid,
9065 (mi_row, mi_col),
9066 (mi_rows, mi_cols),
9067 &obmc_refs,
9068 fctx,
9069 );
9070 // One publication point for every coded leaf
9071 // (`record_mi`): this site used to spell the vote
9072 // out with `ref_frame` pinned to LAST and `mv1`
9073 // to (0,0), which is the encoder-grid-drift class
9074 // -- correct only for as long as a leaf can never
9075 // be compound.
9076 record_mi(&mut grid, mi_row, mi_col, 4, block.inter);
9077 leaves.push(block);
9078 } else {
9079 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
9080 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
9081 let mut eight = Vec::with_capacity(2);
9082 for i in 0..4 {
9083 let leaf_x = x_sub + (i % 2) * 8;
9084 let leaf_y = y_sub + (i / 2) * 8;
9085 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
9086 continue;
9087 }
9088 let (mi_row, mi_col) =
9089 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
9090 let stack = find_mv_stack(
9091 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
9092 );
9093 let cstacks = leaf_compound_stacks(
9094 &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows,
9095 header.reference_select, golden, altref,
9096 );
9097 let (leaf, _) = code_square_inter(
9098 &mut luma,
9099 &mut chroma,
9100 (leaf_x, leaf_y),
9101 8,
9102 &search,
9103 &mode_bits_table,
9104 reference,
9105 &stack,
9106 &cstacks,
9107 &grid,
9108 (mi_row, mi_col),
9109 (mi_rows, mi_cols),
9110 &obmc_refs,
9111 fctx,
9112 );
9113 // Same publication point as the 16x16
9114 // straddling leaf above (`record_mi`).
9115 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter);
9116 eight.push(leaf);
9117 }
9118 leaves.push(BlockCoeffs {
9119 eight: Some(eight),
9120 ..BlockCoeffs::default()
9121 });
9122 }
9123 }
9124 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
9125 }
9126 }
9127 }
9128 }
9129 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
9130 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
9131 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
9132 for (&out, tile) in chroma_out.iter().zip(&chroma) {
9133 copy_rect(
9134 out,
9135 &tile.reconstruction,
9136 frame_width / 2,
9137 x0 / 2,
9138 y0 / 2,
9139 x1.div_ceil(2),
9140 y1.div_ceil(2),
9141 );
9142 }
9143 Ok(blocks)
9144 };
9145 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
9146 .into_iter()
9147 .flatten()
9148 {
9149 blocks[at] = quadrant;
9150 }
9151
9152 let modes = blocks
9153 .iter()
9154 .flat_map(Quadrant::blocks)
9155 .map(|b| b.mode)
9156 .collect::<Vec<_>>();
9157 let inter_block_share = blocks
9158 .iter()
9159 .flat_map(Quadrant::blocks)
9160 .filter(|b| b.inter.is_some())
9161 .count() as f64
9162 / modes.len() as f64;
9163 for block in blocks.iter().flat_map(Quadrant::blocks) {
9164 if let Some(info) = block.inter {
9165 let r = (info.ref_frame as usize).min(7);
9166 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9167 }
9168 }
9169 #[cfg(test)]
9170 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
9171 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
9172 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
9173 // next frame's writer starts from them -- exactly what
9174 // `crate::stream::stored_cdfs_for` hands the decoder.
9175 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
9176 let cdfs = start_cdfs
9177 .cloned()
9178 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
9179 let start_cdfs = CdfSnapshot(cdfs);
9180 let reference_select_bit = header.reference_select;
9181 let switchable_motion_mode = header.is_motion_mode_switchable;
9182 let warped_motion = header.allow_warped_motion;
9183 let order_hint_bits = seq.order_hint_bits;
9184 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
9185 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
9186 // What this frame stores is the LARGEST tile's end-of-tile tables --
9187 // its own header's `context_update_tile_id` (spec 7.20), which
9188 // `tile_info_of` set to exactly that tile.
9189 let store_tile = layout.largest_tile();
9190 let end_cdfs = std::cell::RefCell::new(None);
9191 // As in `encode_key_frame_inner`: every tile starts from this frame's
9192 // own tables, so no tile depends on any other.
9193 let code_tiles = |bits: u8,
9194 sb_cols: usize,
9195 cdef_grid: &[u8],
9196 units: &[Option<crate::restoration::WienerInfo>]|
9197 -> Result<Vec<Vec<u8>>> {
9198 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
9199 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
9200 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
9201 crate::tile::arm_sign_bias(sign_bias);
9202 // Thread-locals: every tile job arms its own worker.
9203 crate::tile::arm_reference_select(reference_select_bit);
9204 crate::tile::arm_motion_mode(switchable_motion_mode);
9205 crate::tile::arm_warped_motion(warped_motion);
9206 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
9207 crate::tile::arm_screen(screen);
9208 crate::tile::arm_filter_intra(filter_intra_on());
9209 let mut cdfs = start_cdfs.0.clone();
9210 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
9211 // Each tile's own MV grid: a candidate scan never reaches past
9212 // the tile's bounds, so a grid holding only this tile's own
9213 // blocks reads exactly as the decoder's frame-wide one does
9214 // under `MiGrid::set_tile_bounds`.
9215 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
9216 mv_grid.set_sign_bias(sign_bias);
9217 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
9218 mi_cols,
9219 mi_rows,
9220 base_q_idx,
9221 &blocks,
9222 tx_select,
9223 &mut cdfs,
9224 layout.rect(index),
9225 &mut mv_grid,
9226 )?;
9227 Ok((bytes, Some(cdfs)))
9228 })?;
9229 if let Some(cdfs) = stored {
9230 *end_cdfs.borrow_mut() = Some(cdfs);
9231 }
9232 Ok(out)
9233 };
9234 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
9235 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
9236 // this tile against the same single-slot reference this encoder predicted
9237 // from, under each candidate level.
9238 // The reference a DECODER holds is this frame's cropped size, not the
9239 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
9240 // reference whose height is not the header's own `frame_height` (spec
9241 // 7.9's compatible-size rule), and the chained-decode round trips prove
9242 // the two predict identically.
9243 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
9244 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
9245 reference.clone()
9246 } else {
9247 Picture {
9248 width: fw,
9249 height: fh,
9250 y: crop_plane(&reference.y, reference.width, fw, fh),
9251 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
9252 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
9253 }
9254 };
9255 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
9256 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
9257 // blocks may name GOLDEN needs that plane too, cropped the same way.
9258 let trial_golden = golden.map(|g| {
9259 if (g.width, g.height) == (fw, fh) {
9260 g.clone()
9261 } else {
9262 Picture {
9263 width: fw,
9264 height: fh,
9265 y: crop_plane(&g.y, g.width, fw, fh),
9266 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
9267 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
9268 }
9269 }
9270 });
9271 let trial_altref = altref.map(|a| {
9272 if (a.width, a.height) == (fw, fh) {
9273 a.clone()
9274 } else {
9275 Picture {
9276 width: fw,
9277 height: fh,
9278 y: crop_plane(&a.y, a.width, fw, fh),
9279 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
9280 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
9281 }
9282 }
9283 });
9284 let mut refs: [Option<&Picture>; 8] = [None; 8];
9285 refs[1] = Some(&trial_ref);
9286 refs[4] = trial_golden.as_ref();
9287 refs[7] = trial_altref.as_ref();
9288 let refpix = crate::decode::RefPix::ready(refs);
9289 pick_and_apply_filters(
9290 &mut header,
9291 &mut luma,
9292 &mut chroma,
9293 [&picture_y8, &picture_u8, &picture_v8],
9294 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
9295 // this frame's own `tx_select`, so the search runs under inter
9296 // `TxMode::Select` too (it used to skip and leave every inter frame
9297 // unfiltered once Select became the default).
9298 true,
9299 &mut tiles,
9300 search.lambda,
9301 fctx,
9302 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
9303 // are what the NEXT frame writes from, so the winning re-code
9304 // publishes its own into `end_cdfs` -- the first write's are stale
9305 // the moment a second tile is coded.
9306 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
9307 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
9308 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
9309 crate::decode::decode_inter_frame_tiles_lr(
9310 &payloads,
9311 &header_tile_info,
9312 h.mi_cols,
9313 h.mi_rows,
9314 base_q_idx,
9315 h.frame_width,
9316 h.frame_height,
9317 &refpix,
9318 cdef,
9319 lf,
9320 h.allow_high_precision_mv,
9321 h.force_integer_mv,
9322 Some(mc::InterpFilterKind::Regular),
9323 seq.enable_dual_filter,
9324 h.reference_select,
9325 tx_select,
9326 lr,
9327 // The trial decode re-reads the tile the writer just wrote,
9328 // so it starts from the same tables the writer did (this
9329 // frame's `start_cdfs`), not from the defaults.
9330 Some(start_cdfs.0.clone()),
9331 sign_bias,
9332 h.allow_screen_content_tools,
9333 switchable_motion_mode,
9334 h.allow_warped_motion,
9335 seq.enable_filter_intra,
9336 fctx,
9337 )
9338 },
9339 )?;
9340 let mut cdfs = end_cdfs
9341 .into_inner()
9342 .unwrap_or_else(|| start_cdfs.0.clone());
9343 cdfs.reset_counts();
9344 let next_cdfs = CdfSnapshot(cdfs);
9345 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
9346 header.tile_info.tile_size_bytes = tile_size_bytes;
9347 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
9348 let mut stream = temporal_delimiter();
9349 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
9350
9351 let [u, v] = chroma;
9352 Ok(Encoded {
9353 stream,
9354 modes,
9355 inter_block_share,
9356 reconstruction: Picture {
9357 width: luma.width,
9358 height: luma.height,
9359 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9360 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9361 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9362 },
9363 tile,
9364 mi_cols: header.mi_cols,
9365 mi_rows: header.mi_rows,
9366 base_q_idx,
9367 tx_select,
9368 switchable_motion_mode,
9369 screen,
9370 start_cdfs,
9371 next_cdfs,
9372 loop_filter: header.loop_filter,
9373 cdef: header.cdef,
9374 loop_restoration: header.loop_restoration,
9375 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
9376 // intra frames only).
9377 allow_intrabc: false,
9378 })
9379}
9380
9381/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
9382/// frame's temporal unit followed by one inter frame's temporal unit per
9383/// remaining picture, all sharing the key frame's sequence header -- and
9384/// each frame's own [`Encoded`], in coding order.
9385#[derive(Clone, Debug)]
9386pub struct EncodedSequence {
9387 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
9388 /// sequence header and the key frame) followed by each later frame's
9389 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
9390 /// the sequence header the key frame carried).
9391 pub stream: Vec<u8>,
9392 /// One entry per picture, in DISPLAY order — the order a decoder outputs
9393 /// them and the order `pictures` came in. Without a pyramid that is also
9394 /// the coding order; with one the two differ, and `coding_order` is the
9395 /// map between them.
9396 pub frames: Vec<Encoded>,
9397 /// The index into `frames` of each coded frame, in CODING order — what a
9398 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
9399 /// `0..frames.len()` on the flat path.
9400 pub coding_order: Vec<usize>,
9401}
9402
9403/// Encodes a sequence of pictures as a key frame followed by one inter frame
9404/// per remaining picture, each predicting from the previous frame's own
9405/// decoded reconstruction — never from the source, which is what a decoder
9406/// cannot see. Every picture must be the same even size (any even width and
9407/// height — each is padded to a whole number of 64x64 superblocks
9408/// internally, which is what lets an inter frame's reference always match
9409/// the frame being coded against it), and `pictures` must be non-empty.
9410///
9411/// # Errors
9412/// Returns an error when `pictures` is empty, when any picture besides the
9413/// first is not the same size as the first, or under the same conditions
9414/// [`encode_key_frame`] and the inter frame path do.
9415pub(crate) fn encode_sequence_with_ctx(
9416 pictures: &[Picture],
9417 base_q_idx: u8,
9418 deadzone: f64, fctx: &crate::decode::FrameCtx,
9419) -> Result<EncodedSequence> {
9420 let Some((first, rest)) = pictures.split_first() else {
9421 return Err(Error::unsupported(
9422 "AV1 encode",
9423 "a sequence needs at least one picture",
9424 ));
9425 };
9426 first.check_even()?;
9427 let render = (first.width, first.height);
9428 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
9429 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
9430 // the leaves that predict backward off it, and a `show_existing_frame`
9431 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
9432 // an A/B. Screen content stays flat (the content gate in
9433 // `Av1Encoder::encode_frames`, whose detector this asks first so the
9434 // whole sequence path is decided in one place), and so does a run that
9435 // asks for a quantizer rounding offset the facade does not carry: the
9436 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
9437 // the ablations' -- must keep the flat path rather than be silently
9438 // ignored.
9439 //
9440 // The reordering itself is NOT reimplemented here: it is the facade's
9441 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
9442 // called with this sequence's shape, so the two paths cannot drift.
9443 let pyramid = crate::encoder::Pyramid::from_env()
9444 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
9445 .filter(|_| !picture_is_screen(first));
9446 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
9447 if let Some(pyramid) = pyramid {
9448 for picture in rest {
9449 picture.check_even()?;
9450 if (picture.width, picture.height) != render {
9451 return Err(Error::unsupported(
9452 "AV1 encode",
9453 "every picture in a sequence must be the same size as the first",
9454 ));
9455 }
9456 }
9457 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
9458 pictures,
9459 base_q_idx,
9460 pyramid,
9461 armed_tiles(),
9462 );
9463 }
9464 // The key frame and every inter frame after it are coded at the same
9465 // padded size, so the reference each inter frame predicts from -- the
9466 // previous frame's own uncropped reconstruction, at the size a decoder's
9467 // reference buffer actually holds -- always matches the frame being
9468 // coded against it.
9469 let key = encode_key_frame_inner(
9470 &first.padded_to(SUPERBLOCK),
9471 base_q_idx,
9472 deadzone,
9473 &KEY_FRAME_MODES,
9474 split_blocks(),
9475 render,
9476 unspecified_color_config(), fctx,
9477 )?;
9478 let mut stream = key.stream.clone();
9479 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
9480 // key frame refreshes every slot, each inter frame only slot 0), which is
9481 // what `GOLDEN_FRAME` names.
9482 let golden = key.reconstruction.clone();
9483 // The frame two back, once there is one that is not the key frame
9484 // itself (which `GOLDEN_FRAME` already names).
9485 let mut prev2: Option<Picture> = None;
9486 let mut carried = key.next_cdfs.clone();
9487 let mut reference = key.reconstruction.clone();
9488 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
9489 for (i, picture) in rest.iter().enumerate() {
9490 picture.check_even()?;
9491 // lane-av1tpl2: the lookahead window the per-block lambda weighting
9492 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
9493 // sources at this frame's coded (padded) size. The tail of the
9494 // sequence gets a shorter window, and the last frame none at all.
9495 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
9496 .iter()
9497 .take(tpl_depth() - 1)
9498 .map(|n| n.padded_to(SUPERBLOCK))
9499 .collect();
9500 if (picture.width, picture.height) != render {
9501 return Err(Error::unsupported(
9502 "AV1 encode",
9503 "every picture in a sequence must be the same size as the first",
9504 ));
9505 }
9506 let order_hint = (i + 1) as u32;
9507 let inter = encode_inter_frame(
9508 &picture.padded_to(SUPERBLOCK),
9509 &reference,
9510 base_q_idx,
9511 deadzone,
9512 order_hint,
9513 flat_order_hints(order_hint, 0, prev2.is_some()),
9514 render,
9515 Some(&carried.0),
9516 Some(&golden),
9517 prev2.as_ref(), fctx,
9518 None,
9519 &lookahead,
9520 )?;
9521 stream.extend_from_slice(&inter.stream);
9522 carried = inter.next_cdfs.clone();
9523 prev2 = Some(std::mem::replace(
9524 &mut reference,
9525 inter.reconstruction.clone(),
9526 ));
9527 frames.push(crop_encoded(&inter, render.0, render.1));
9528 }
9529 Ok(EncodedSequence {
9530 stream,
9531 coding_order: (0..frames.len()).collect(),
9532 frames,
9533 })
9534}
9535
9536#[cfg(test)]
9537mod tests {
9538
9539 /// lane-av1tpl2's propagated map, on the two properties every decision
9540 /// under it rests on: a frame the whole lookahead window repeats exactly
9541 /// (uniform texture) leans on every cell alike, so every factor is 1 and
9542 /// the weighting is a no-op; and where the window really does save bits
9543 /// by predicting -- the textured half of a frame whose other half is
9544 /// flat -- the factor FALLS below 1, i.e. that half is coded more
9545 /// distortion-averse than the half nothing gains from.
9546 #[test]
9547 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
9548 // Four 64x64 superblocks across: the shipped map forms its ratio per
9549 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
9550 // only ever produce one ratio -- and one ratio, mean-normalised, is
9551 // the flat map, whatever the content underneath it.
9552 let (w, h) = (256usize, 64usize);
9553 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
9554 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
9555 let f = super::tpl_lambda_factors(&frames, w, h, 1.0);
9556 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
9557 for (i, &v) in f.iter().enumerate() {
9558 assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda");
9559 }
9560
9561 // Left half textured, right half constant: the window saves bits
9562 // predicting the left half and nothing at all on the right.
9563 let split: Vec<u8> = (0..w * h)
9564 .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 })
9565 .collect();
9566 let frames: Vec<&[u8]> = vec![&split, &split, &split];
9567 let cells_x = w / 16;
9568 for k in [0.25f64, 0.5, 1.0, 2.0] {
9569 let f = super::tpl_lambda_factors(&frames, w, h, k);
9570 for r in 0..h / 16 {
9571 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
9572 assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1");
9573 assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1");
9574 }
9575 }
9576 }
9577
9578 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
9579 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
9580 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
9581 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
9582 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
9583 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
9584 /// only a quarter of the 16x8 table and read the wrong byte for every
9585 /// block row but the first (silently wrong above-right/below-left
9586 /// availability -- wrong pixels, no error).
9587 #[test]
9588 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
9589 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
9590 let (bw_log2, bh_log2) =
9591 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
9592 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
9593 for (name, table) in
9594 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
9595 {
9596 assert_eq!(
9597 table.len() * 8,
9598 rows * cols,
9599 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
9600 );
9601 let mut seen = vec![0u32; table.len() * 8];
9602 for blk_row in 0..rows {
9603 for blk_col in 0..cols {
9604 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
9605 assert!(
9606 idx < seen.len(),
9607 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
9608 );
9609 seen[idx] += 1;
9610 }
9611 }
9612 assert!(
9613 seen.iter().all(|&n| n == 1),
9614 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
9615 (row stride is not {cols})"
9616 );
9617 }
9618 }
9619 }
9620 use super::*;
9621 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
9622 use std::io::Write;
9623 use std::process::{Command, Stdio};
9624
9625 /// Every rectangular shape this decoder codes, at every position a block
9626 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
9627 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
9628 /// (`reconintra.c`) answer, whose bodies are ported below.
9629 ///
9630 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
9631 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
9632 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
9633 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
9634 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
9635 /// oracle's own arrays, so a re-routed or truncated table fails here even
9636 /// where the two rows happen to agree.
9637 ///
9638 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
9639 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
9640 /// callers handle by predicting each transform unit as its own block.
9641 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
9642 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
9643 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
9644 /// (the horizontal shapes, which those partitions never produce).
9645 #[test]
9646 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
9647 let fctx = &crate::decode::FrameCtx::new();
9648 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
9649 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
9650 (4, 8, 64, 9280, 64, 550),
9651 (8, 4, 64, 3712, 64, 9630),
9652 (8, 16, 16, 2352, 16, 134),
9653 (16, 8, 16, 960, 16, 2400),
9654 (16, 32, 4, 620, 4, 32),
9655 (32, 16, 4, 32, 4, 184),
9656 (32, 64, 1, 127, 1, 0),
9657 (64, 32, 1, 19, 1, 34),
9658 (4, 16, 32, 5472, 32, 14),
9659 (16, 4, 32, 960, 32, 6464),
9660 (8, 32, 8, 1400, 8, 2),
9661 (32, 8, 8, 32, 8, 1136),
9662 (16, 64, 2, 382, 2, 0),
9663 (64, 16, 2, 4, 2, 84),
9664 ];
9665 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
9666 /// a block whose transform covers it whole (`row_off == col_off == 0`,
9667 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
9668 /// superblock (`sb_mi_size == 16`).
9669 fn libaom_reach(
9670 bw: usize,
9671 bh: usize,
9672 x: usize,
9673 y: usize,
9674 width: usize,
9675 height: usize, _fctx: &crate::decode::FrameCtx,
9676 ) -> (bool, bool) {
9677 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
9678 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
9679 let sb_mi_size = 16usize;
9680 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
9681 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
9682 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
9683 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
9684 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
9685 // has_top_right: top_available && right_available, then row_off == 0.
9686 let top_right = if y == 0 || x + bw >= width {
9687 false
9688 } else if blk_row_in_sb == 0 {
9689 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
9690 // `bw_unit < bw_unit`, false for a whole-block transform.)
9691 true
9692 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
9693 false
9694 } else {
9695 bit(tr_table)
9696 };
9697 // has_bottom_left: bottom_available && left_available, col_off == 0.
9698 let bottom_left = if x == 0 || y + bh >= height {
9699 false
9700 } else if blk_col_in_sb == 0 {
9701 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
9702 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
9703 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
9704 false
9705 } else {
9706 bit(bl_table)
9707 };
9708 (top_right, bottom_left)
9709 }
9710 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
9711 let (tr, bl) = rect_reach_tables(bw, bh);
9712 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
9713 assert_eq!(
9714 (tr.len(), sum(tr), bl.len(), sum(bl)),
9715 (tr_len, tr_sum, bl_len, bl_sum),
9716 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
9717 );
9718 // Two superblocks across and down, so the superblock-relative
9719 // position (and not the frame position) is what decides.
9720 for sb_y in [0usize, 64] {
9721 for sb_x in [0usize, 64] {
9722 for y in (sb_y..sb_y + 64).step_by(bh) {
9723 for x in (sb_x..sb_x + 64).step_by(bw) {
9724 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
9725 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
9726 assert_eq!(
9727 (got.above_right, got.below_left),
9728 want,
9729 "{bw}x{bh} at ({x}, {y})"
9730 );
9731 }
9732 }
9733 }
9734 }
9735 }
9736 }
9737
9738 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
9739 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
9740 /// aomenc gate decodes its stream through ffmpeg and is meaningless
9741 /// without it -- turns it into a hard failure. Without this the require
9742 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
9743 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
9744 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
9745 fn have_ffmpeg() -> bool {
9746 let present = Command::new("ffmpeg")
9747 .arg("-version")
9748 .stdout(Stdio::null())
9749 .stderr(Stdio::null())
9750 .status()
9751 .is_ok_and(|s| s.success());
9752 assert!(
9753 present
9754 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
9755 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
9756 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
9757 );
9758 present
9759 }
9760
9761 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
9762 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
9763 let mut child = Command::new("ffmpeg")
9764 .args([
9765 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
9766 ])
9767 .stdin(Stdio::piped())
9768 .stdout(Stdio::piped())
9769 .stderr(Stdio::piped())
9770 .spawn()
9771 .expect("ffmpeg failed to start");
9772 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
9773 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
9774 // fills before the last input byte is written -- which is exactly what
9775 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
9776 // (measured: 45 min, both processes at 0% CPU). A write error here is
9777 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
9778 // below, are the real diagnosis.
9779 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
9780 let payload = stream.to_vec();
9781 let writer = std::thread::spawn(move || {
9782 let _ = stdin.write_all(&payload);
9783 });
9784 let out = child.wait_with_output().expect("ffmpeg failed to run");
9785 writer.join().expect("ffmpeg stdin writer thread");
9786 assert!(
9787 out.status.success(),
9788 "ffmpeg refused the stream: {}",
9789 String::from_utf8_lossy(&out.stderr)
9790 );
9791 let (luma, chroma) = (width * height, width * height / 4);
9792 assert_eq!(
9793 out.stdout.len(),
9794 luma + 2 * chroma,
9795 "expected one 4:2:0 frame"
9796 );
9797 Picture {
9798 width,
9799 height,
9800 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
9801 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
9802 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
9803 }
9804 }
9805
9806 /// A picture with something of everything in it: a gradient, an edge, a
9807 /// ripple and a block of flat colour, none of them aligned to the block
9808 /// grid.
9809 /// The in-loop filters actually FIRE and the stream still decodes to
9810 /// exactly what the encoder kept as its reconstruction
9811 /// (gate-blind-to-feature: a filter search that always answered "off"
9812 /// would leave every other test just as green, and the BD gate that
9813 /// would notice is `#[ignore]`d).
9814 ///
9815 /// Run:
9816 /// cargo test -p ec-av1 --release --lib -- \
9817 /// encode::tests::the_filter_search_picks_real_filters
9818 #[test]
9819 fn the_filter_search_picks_real_filters() {
9820 let fctx = &crate::decode::FrameCtx::new();
9821 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
9822 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
9823 let fired = encoded
9824 .frames
9825 .iter()
9826 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
9827 .count();
9828 assert!(
9829 fired > 0,
9830 "no frame of this sequence chose any in-loop filtering: {:?}",
9831 encoded
9832 .frames
9833 .iter()
9834 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
9835 .collect::<Vec<_>>()
9836 );
9837 // The reconstruction the encoder predicts from is the FILTERED one,
9838 // and it is what a decoder of the stream produces -- byte for byte,
9839 // frame for frame.
9840 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
9841 assert_eq!(decoded.len(), encoded.frames.len());
9842 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
9843 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
9844 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
9845 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
9846 }
9847 }
9848
9849 fn test_card(width: usize, height: usize) -> Picture {
9850 let mut picture = Picture::grey(width, height);
9851 for y in 0..height {
9852 for x in 0..width {
9853 let gradient = x as f64 * 200.0 / width as f64;
9854 let ripple = 30.0
9855 * (x as f64 * std::f64::consts::PI / 23.0).sin()
9856 * (y as f64 * std::f64::consts::PI / 37.0).cos();
9857 let edge = if x > width * 3 / 7 && y > height / 3 {
9858 40.0
9859 } else {
9860 0.0
9861 };
9862 picture.y[y * width + x] =
9863 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
9864 }
9865 }
9866 for y in 0..height / 2 {
9867 for x in 0..width / 2 {
9868 let i = y * width / 2 + x;
9869 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
9870 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
9871 }
9872 }
9873 picture
9874 }
9875
9876 fn psnr(a: &[u16], b: &[u16]) -> f64 {
9877 let squared: f64 = a
9878 .iter()
9879 .zip(b)
9880 .map(|(&x, &y)| {
9881 let d = f64::from(x) - f64::from(y);
9882 d * d
9883 })
9884 .sum();
9885 if squared == 0.0 {
9886 return f64::INFINITY;
9887 }
9888 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
9889 }
9890
9891 /// The claim the whole encoder rests on: what a decoder produces is what
9892 /// the encoder said it would, sample for sample, on every plane.
9893 ///
9894 /// Prediction reads the reconstruction, so a single sample of drift
9895 /// anywhere would spread into every block below and to the right of it —
9896 /// which is why this is an equality and not a tolerance.
9897 #[test]
9898 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
9899 let fctx = &crate::decode::FrameCtx::new();
9900 if !have_ffmpeg() {
9901 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
9902 return;
9903 }
9904 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] {
9905 let picture = test_card(width, height);
9906 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9907 let decoded = ffmpeg_decode(&encoded.stream, width, height);
9908 assert_eq!(
9909 decoded.y, encoded.reconstruction.y,
9910 "{width}x{height}: luma"
9911 );
9912 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
9913 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
9914 }
9915 // One q index from each of the four coefficient-CDF contexts
9916 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
9917 let (width, height) = (64usize, 64usize);
9918 let picture = test_card(width, height);
9919 let _ = take_tx_depth_hits();
9920 for &q in &[15u8, 45, 100, 200] {
9921 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
9922 let decoded = ffmpeg_decode(&encoded.stream, width, height);
9923 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
9924 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
9925 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
9926 }
9927 // lane-av1tx: the exactness above is only a claim about SPLIT
9928 // transforms if some block actually split one (`gate-blind-to-feature`
9929 // -- with `tx_depth` stuck at 0 every assert here passes on the
9930 // pre-lane stream). The test card's edges split at these four
9931 // quantizers; the counter is per-process (another test encoding in
9932 // parallel can only ADD to it, so this can be masked, never falsely
9933 // failed), so it is read once for the whole q ladder.
9934 let depths = take_tx_depth_hits();
9935 assert!(
9936 depths[1] + depths[2] > 0,
9937 "no block split its transform: depths {depths:?}"
9938 );
9939 }
9940
9941 /// A synthetic screen-content picture -- a few flat colours in a grid of
9942 /// boxes with hard edges and text-like bars, the shape a desktop capture
9943 /// has -- so the palette path is exercised on content it is for.
9944 #[cfg(test)]
9945 fn screen_card(width: usize, height: usize) -> Picture {
9946 const INK: [u16; 4] = [16, 90, 180, 235];
9947 let mut picture = Picture::grey(width, height);
9948 for y in 0..height {
9949 for x in 0..width {
9950 let cell = (x / 24 + y / 24) % 2;
9951 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
9952 picture.y[y * width + x] = INK[cell * 2 + bar];
9953 }
9954 }
9955 // Four chroma colours, not two: a two-colour chroma block only ever
9956 // codes a `PaletteSizeUV` of 2, which leaves
9957 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
9958 // deltas and the neighbour cache flags, exercised only when
9959 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
9960 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
9961 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
9962 for y in 0..height / 2 {
9963 for x in 0..width / 2 {
9964 let cell = (x / 12 + 2 * (y / 12)) % 4;
9965 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
9966 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
9967 }
9968 }
9969 picture
9970 }
9971
9972 /// The lane's own end-to-end check: on screen content the detector fires,
9973 /// blocks really take a palette (fire count, class
9974 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
9975 /// symbol this lane writes -- reconstructs exactly what the encoder did.
9976 /// The film-shaped `test_card` must NOT trip the detector, which is what
9977 /// keeps every non-screen stream byte-identical.
9978 #[test]
9979 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
9980 let fctx = &crate::decode::FrameCtx::new();
9981 let (width, height) = (192usize, 96usize);
9982 let _ = crate::tile::take_palette_hits();
9983 let picture = screen_card(width, height);
9984 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9985 assert!(
9986 encoded.screen,
9987 "the detector did not fire on screen content -- no palette syntax was coded at all"
9988 );
9989 let hits = crate::tile::take_palette_hits();
9990 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
9991 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
9992 // The chroma half is a claim about the plane-1 syntax only if some
9993 // block really took a chroma palette (`gate-blind-to-feature`): every
9994 // exactness assert below passes on a stream that codes
9995 // `palette_uv_mode == 0` everywhere.
9996 let uv_hits = crate::tile::take_palette_uv_hits();
9997 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
9998 let uv_cached = crate::tile::take_palette_uv_cache_hits();
9999 eprintln!(
10000 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
10001 uv_hits[0],
10002 &uv_hits[2..]
10003 );
10004 assert!(
10005 uv_cached > 0,
10006 "no chroma base colour came out of the neighbour cache -- \
10007 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
10008 );
10009 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
10010 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
10011 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
10012 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
10013 if !have_ffmpeg() {
10014 eprintln!("SKIP the ffmpeg half: no ffmpeg");
10015 return;
10016 }
10017 let decoded = ffmpeg_decode(&encoded.stream, width, height);
10018 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
10019 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
10020 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
10021 // A whole GOP: the inter frames' own intra blocks carry the palette
10022 // syntax too (the three intra arms of the inter writers), which only
10023 // ffmpeg reading the frames back can prove.
10024 let moved: Vec<Picture> = (0..4)
10025 .map(|f| {
10026 let base = screen_card(width, height);
10027 let mut out = Picture::grey(width, height);
10028 for y in 0..height {
10029 for x in 0..width {
10030 let sx = (x + f * 7) % width;
10031 out.y[y * width + x] = base.y[y * width + sx];
10032 }
10033 }
10034 for y in 0..height / 2 {
10035 for x in 0..width / 2 {
10036 let sx = (x + f * 3) % (width / 2);
10037 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
10038 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
10039 }
10040 }
10041 out
10042 })
10043 .collect();
10044 let _ = crate::tile::take_palette_hits();
10045 let _ = crate::tile::take_palette_uv_hits();
10046 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
10047 let gop_hits = crate::tile::take_palette_hits();
10048 let gop_uv_hits = crate::tile::take_palette_uv_hits();
10049 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
10050 eprintln!(
10051 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
10052 {} chroma palette blocks",
10053 inter_screen, gop_hits[0], gop_uv_hits[0]
10054 );
10055 assert!(
10056 gop_uv_hits[0] > 0,
10057 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
10058 );
10059 assert!(
10060 inter_screen > 0,
10061 "no inter frame set allow_screen_content_tools"
10062 );
10063 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
10064 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
10065 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
10066 }
10067 if have_ffmpeg() {
10068 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
10069 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
10070 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
10071 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
10072 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
10073 }
10074 }
10075
10076 // The other half of the keep rule: film-shaped content leaves the
10077 // detector (and so the whole sequence header) alone.
10078 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
10079 assert!(!film.screen, "the detector fired on the film-shaped test card");
10080 }
10081
10082 /// The lane's keep-rule measurement: the gate's own screen capture, one
10083 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
10084 /// Setting the bit forces deblocking, CDEF and loop restoration off for
10085 /// that frame, so the table is exactly the filter loss against the bytes
10086 /// the copied blocks save.
10087 #[test]
10088 #[ignore = "needs the real-library manifest and ffmpeg"]
10089 fn probe_intrabc_key_frame() {
10090 let fctx = &crate::decode::FrameCtx::new();
10091 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
10092 .join("../../fixtures");
10093 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
10094 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
10095 return;
10096 };
10097 let Some(clip) = manifest
10098 .lines()
10099 .skip(1)
10100 .filter_map(|l| l.split('\t').next())
10101 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
10102 else {
10103 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
10104 return;
10105 };
10106 let (width, height) = (640usize, 384usize);
10107 let picture = clip_frame(clip, "0", width, height);
10108 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
10109 for q in [5u8, 20, 35, 45] {
10110 for on in [false, true] {
10111 force_intrabc(Some(on));
10112 let _ = crate::tile::take_intrabc_hits();
10113 let _ = take_intrabc_search();
10114 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
10115 let hits = crate::tile::take_intrabc_hits();
10116 let search = take_intrabc_search();
10117 eprintln!(
10118 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
10119 if encoded.allow_intrabc { "on" } else { "off" },
10120 encoded.stream.len(),
10121 psnr_all(&encoded.reconstruction, &picture),
10122 hits[0],
10123 &hits[1..],
10124 search[0], search[1], search[2],
10125 );
10126 }
10127 }
10128 force_intrabc(None);
10129 }
10130
10131 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
10132 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
10133 /// take a block vector (fire count + DV histogram, class
10134 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
10135 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
10136 /// exactly what the encoder did.
10137 #[test]
10138 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
10139 let fctx = &crate::decode::FrameCtx::new();
10140 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
10141 // superblocks of 64) and tall enough for a source superblock row
10142 // above the blocks that copy from it.
10143 let (width, height) = (512usize, 256usize);
10144 let picture = screen_card(width, height);
10145 let _ = crate::tile::take_intrabc_hits();
10146 // The default is OFF (it measured worse on the real screen capture --
10147 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
10148 // the arm on for its own encode and puts it back straight after.
10149 force_intrabc(Some(true));
10150 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10151 force_intrabc(None);
10152 assert!(
10153 encoded.allow_intrabc,
10154 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
10155 intrabc_source_share() * 100.0
10156 );
10157 let hits = crate::tile::take_intrabc_hits();
10158 eprintln!(
10159 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
10160 hits[0],
10161 &hits[1..],
10162 intrabc_source_share() * 100.0
10163 );
10164 let search = take_intrabc_search();
10165 eprintln!(
10166 "intrabc searches {} found-valid {} won-RD {}",
10167 search[0], search[1], search[2]
10168 );
10169 assert!(
10170 hits[0] > 0,
10171 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
10172 );
10173 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
10174 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
10175 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
10176 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
10177 if !have_ffmpeg() {
10178 eprintln!("SKIP the ffmpeg half: no ffmpeg");
10179 return;
10180 }
10181 let decoded = ffmpeg_decode(&encoded.stream, width, height);
10182 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
10183 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
10184 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
10185 }
10186
10187 /// The minimal repro that isolated the inter-residual desync: a key frame
10188 /// followed by one inter frame whose single superblock carries one
10189 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
10190 /// coefficient, its three sibling blocks all `skip: true`. Before the
10191 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
10192 /// found when processing input") even though every symbol either block
10193 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
10194 /// same coefficient syntax decodes clean on every intra key-frame gate).
10195 #[test]
10196 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
10197 let fctx = &crate::decode::FrameCtx::new();
10198 if !have_ffmpeg() {
10199 eprintln!(
10200 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
10201 );
10202 return;
10203 }
10204 let (width, height) = (64usize, 64usize);
10205 let picture = Picture::grey(width, height);
10206 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10207
10208 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
10209 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
10210
10211 let residual_block = BlockCoeffs {
10212 angle_delta_y: 0,
10213 cfl_alphas: None,
10214 filter_intra: None,
10215 luma: vec![Coeff {
10216 row: 0,
10217 col: 0,
10218 level: 4,
10219 }],
10220 u: Vec::new(),
10221 v: Vec::new(),
10222 mode: 0,
10223 uv_mode: 0,
10224 skip: false,
10225 eight: None,
10226 dv: None,
10227 palette: None,
10228 palette_uv: None,
10229 tx_depth: 0,
10230 inter: Some(InterInfo {
10231 ref1: None,
10232 mv1: (0, 0),
10233 ref_frame: crate::mvstack::LAST_FRAME,
10234 mode: InterMode::NearestMv,
10235 mv: (0, 0),
10236 ref_mv_idx: 0,
10237 }),
10238 motion_mode: 0,
10239 };
10240 let skipped_block = BlockCoeffs {
10241 skip: true,
10242 inter: Some(InterInfo {
10243 ref1: None,
10244 mv1: (0, 0),
10245 ref_frame: crate::mvstack::LAST_FRAME,
10246 mode: InterMode::NearestMv,
10247 mv: (0, 0),
10248 ref_mv_idx: 0,
10249 }),
10250 ..BlockCoeffs::default()
10251 };
10252 let blocks = vec![
10253 Quadrant::Whole(residual_block),
10254 Quadrant::Whole(skipped_block.clone()),
10255 Quadrant::Whole(skipped_block.clone()),
10256 Quadrant::Whole(skipped_block),
10257 ];
10258 // lane-av1obmc: the header this tile is decoded under carries
10259 // `is_motion_mode_switchable`, so the writer must be armed with it
10260 // too or the decoder reads a `motion_mode` symbol nobody wrote.
10261 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
10262 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
10263 let tile =
10264 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
10265 .unwrap();
10266
10267 // `key.stream` is already a temporal delimiter, the sequence header
10268 // and the key frame's own OBU (`encode_key_frame` built it from the
10269 // same `key_frame_headers(width, height, 100)` this test calls), so
10270 // the inter frame's OBU is appended straight onto it rather than
10271 // re-deriving the key frame's tile bytes.
10272 let mut stream = key.stream.clone();
10273 stream.extend_from_slice(&temporal_delimiter());
10274 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
10275
10276 ffmpeg_decode_sequence(&stream, width, height, 2);
10277 }
10278
10279 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
10280 /// frame size an AV1 decoder allocates, not necessarily the render size
10281 /// (see [`a_frame_round_trips_at_its_own_size`]).
10282 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
10283 // Distinct per call, not per process: the test binary runs callers on
10284 // parallel threads, and a shared name lets one test's cleanup delete
10285 // the stream another test's ffprobe is still reading.
10286 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
10287 let path = std::env::temp_dir().join(format!(
10288 "ec-av1-probe-{}-{}.obu",
10289 std::process::id(),
10290 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
10291 ));
10292 let _ = std::fs::remove_file(&path);
10293 std::fs::write(&path, stream).expect("writing the probe stream");
10294 let out = Command::new("ffprobe")
10295 .args([
10296 "-v",
10297 "error",
10298 "-f",
10299 "obu",
10300 "-select_streams",
10301 "v:0",
10302 "-show_entries",
10303 "stream=width,height",
10304 "-of",
10305 "csv=p=0",
10306 ])
10307 .arg(&path)
10308 .output()
10309 .expect("ffprobe failed to run");
10310 let _ = std::fs::remove_file(&path);
10311 assert!(
10312 out.status.success(),
10313 "ffprobe refused the stream: {}",
10314 String::from_utf8_lossy(&out.stderr)
10315 );
10316 let text = String::from_utf8_lossy(&out.stdout);
10317 let mut fields = text.trim().split(',');
10318 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
10319 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
10320 (width, height)
10321 }
10322
10323 /// lane-av1cap: the final filter replay against the capture decode it
10324 /// replaced, at the block-padded and straddling sizes the whole-frame
10325 /// tests cover -- `set_verify_final_replay` makes
10326 /// [`pick_and_apply_filters`] run both on every frame and assert, per
10327 /// frame, that the spliced picture and the two filter stages the
10328 /// restoration search reads are bit-identical over the frame's own crop.
10329 #[test]
10330 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
10331 let fctx = &crate::decode::FrameCtx::new();
10332 crate::decode::set_verify_final_replay(true);
10333 for &(width, height) in
10334 &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)]
10335 {
10336 eprintln!("--- {width}x{height}");
10337 let picture = test_card(width, height);
10338 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10339 }
10340 crate::decode::set_verify_final_replay(false);
10341 }
10342
10343 /// A key frame at an arbitrary even size round-trips through ffmpeg over
10344 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
10345 /// picture's own size, and what ffmpeg decodes over that same top-left
10346 /// region equals it sample for sample.
10347 ///
10348 /// This does not check that `ffprobe` reports the picture's own size,
10349 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
10350 /// (block-padded) frame size, the same one libaom itself would code for
10351 /// a non-block-aligned picture. `render_width`/`render_height` (which
10352 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
10353 /// decoder is required to crop pixels by, and ffmpeg's does not --
10354 /// checked empirically against ffprobe here and against a real libaom
10355 /// encode separately. So the coded size, not the render size, is what
10356 /// `ffprobe` is asserted to report below.
10357 #[test]
10358 fn a_frame_round_trips_at_its_own_size() {
10359 let fctx = &crate::decode::FrameCtx::new();
10360 if !have_ffmpeg() {
10361 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
10362 return;
10363 }
10364 // 854x480 is covered separately by
10365 // `an_854x480_picture_round_trips_through_its_padding`, which its own
10366 // doc comment explains was worth keeping as its own test.
10367 for &(width, height) in &[
10368 (1920usize, 1080usize),
10369 (640, 352),
10370 (1280, 720),
10371 (64, 56),
10372 (854, 480),
10373 (216, 96),
10374 (192, 120),
10375 ] {
10376 let picture = test_card(width, height);
10377 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10378 assert_eq!(
10379 (encoded.reconstruction.width, encoded.reconstruction.height),
10380 (width, height),
10381 "{width}x{height}: reconstruction is cropped to the picture's own size"
10382 );
10383 assert_eq!(
10384 ffprobe_size(&encoded.stream),
10385 (width as u32, height as u32),
10386 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
10387 );
10388 let decoded = ffmpeg_decode(&encoded.stream, width, height);
10389 assert_eq!(
10390 decoded.y, encoded.reconstruction.y,
10391 "{width}x{height}: luma"
10392 );
10393 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
10394 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
10395 }
10396 }
10397
10398 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
10399 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
10400 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
10401 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
10402 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
10403 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
10404 /// col`) -- different bits of an 8-byte table, one true, one false. The
10405 /// stride libaom indexes by is fixed at its compile-time maximum
10406 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
10407 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
10408 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
10409 /// row/col position within the (correctly 64-relative) superblock stayed
10410 /// right, only the table's own row stride was wrong. Fixed in
10411 /// `Reach::table_stride`; not an arithmetic-coder desync (an
10412 /// EC_RNG-per-symbol trace against the same debug decoder found the
10413 /// bitstream byte-for-byte identical to libaom's across all 51188
10414 /// symbols of this frame before this bug was found).
10415 ///
10416 /// Since the frame header started writing the true (unpadded) display
10417 /// size into `frame_width`/`frame_height` rather than the padded coded
10418 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
10419 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
10420 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
10421 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
10422 /// the header's own size before output).
10423 #[test]
10424 fn an_854x480_picture_round_trips_through_its_padding() {
10425 let fctx = &crate::decode::FrameCtx::new();
10426 if !have_ffmpeg() {
10427 return;
10428 }
10429 let (width, height) = (854usize, 480usize);
10430 let picture = test_card(width, height);
10431 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10432 let decoded = ffmpeg_decode(&encoded.stream, width, height);
10433 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
10434 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
10435 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
10436 }
10437
10438 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
10439 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
10440 /// superblock, both partition tables:
10441 ///
10442 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
10443 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
10444 /// wiring the TU sites onto it changes no existing stream;
10445 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
10446 /// NULL in libaom because that lookup never happens, and reading a
10447 /// 4x4 row out of the three-row vert tables is what crashed a real
10448 /// `--enable-tx-size-search=1` stream (r2);
10449 /// 3. and it must be the BLOCK's vert answer where the two tables
10450 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
10451 /// row 1, column 0 reads its above-right samples from the 8x8 to its
10452 /// upper right, which a vertical AB partition codes AFTER it
10453 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
10454 #[test]
10455 fn of_tu_follows_the_block_row_including_under_vert_ab() {
10456 let fctx = &crate::decode::FrameCtx::new();
10457 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
10458 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
10459 // above-right answer is the BLOCK's, which is the whole reason a unit
10460 // asks the block instead of looking itself up (the
10461 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
10462 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
10463 assert_eq!(
10464 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
10465 plain.above_right,
10466 "ordinary table: the top-right TX4 unit takes the block's row"
10467 );
10468 let guard = Reach::vert_ab_partition();
10469 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
10470 assert_eq!(
10471 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
10472 vert.above_right,
10473 "vert AB: the unit follows the vert row the block just picked"
10474 );
10475 assert_ne!(
10476 plain.above_right, vert.above_right,
10477 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
10478 );
10479 drop(guard);
10480 }
10481
10482 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
10483 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
10484 /// reconintra.c`), for every 16x16 and 32x32 block position across three
10485 /// superblocks square -- interior and every superblock edge (top row,
10486 /// left column, right column, bottom row) both sizes reach. Written to
10487 /// catch the class the `table_stride` bug was: an index stride silently
10488 /// wrong for one block size while looking plausible for the other.
10489 #[test]
10490 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
10491 let fctx = &crate::decode::FrameCtx::new();
10492 // Transcribed from has_top_right/has_bottom_left's row_off==0,
10493 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
10494 // 128px reference grid) pinned as libaom pins it, independent of the
10495 // 64px superblock this crate actually codes.
10496 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
10497 if y == 0 || x + side >= width {
10498 return false;
10499 }
10500 let (row, col, per_side) = (
10501 (y % SUPERBLOCK) / side,
10502 (x % SUPERBLOCK) / side,
10503 SUPERBLOCK / side,
10504 );
10505 if row == 0 {
10506 return true;
10507 }
10508 if col + 1 == per_side {
10509 return false;
10510 }
10511 let stride = 128 / side;
10512 let index = row * stride + col;
10513 let table = if side == BLOCK {
10514 [95u8, 87].to_vec()
10515 } else {
10516 vec![255, 85, 119, 85, 127, 85, 119, 85]
10517 };
10518 (table[index / 8] >> (index % 8)) & 1 != 0
10519 }
10520
10521 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
10522 if x == 0 || y + side >= height {
10523 return false;
10524 }
10525 let (row, col, per_side) = (
10526 (y % SUPERBLOCK) / side,
10527 (x % SUPERBLOCK) / side,
10528 SUPERBLOCK / side,
10529 );
10530 if col == 0 {
10531 return row * side + side < SUPERBLOCK;
10532 }
10533 if row + 1 == per_side {
10534 return false;
10535 }
10536 let stride = 128 / side;
10537 let index = row * stride + col;
10538 let table = if side == BLOCK {
10539 [4u8, 4].to_vec()
10540 } else {
10541 vec![84, 16, 84, 0, 84, 16, 84, 0]
10542 };
10543 (table[index / 8] >> (index % 8)) & 1 != 0
10544 }
10545
10546 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
10547 for side in [16usize, BLOCK] {
10548 for y in (0..height).step_by(side) {
10549 for x in (0..width).step_by(side) {
10550 let reach = Reach::of(side, x, y, width, height, fctx);
10551 assert_eq!(
10552 reach.above_right,
10553 libaom_top_right(side, x, y, width, height),
10554 "side={side} x={x} y={y}: above_right"
10555 );
10556 assert_eq!(
10557 reach.below_left,
10558 libaom_bottom_left(side, x, y, height, fctx),
10559 "side={side} x={x} y={y}: below_left"
10560 );
10561 }
10562 }
10563 }
10564 }
10565
10566 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
10567 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
10568 /// column inside the superblock) may read the below-left samples the
10569 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
10570 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
10571 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
10572 /// stream that partitions that small first hits the still-refused
10573 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
10574 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
10575 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
10576 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
10577 /// pixels -- lane-palette2 r12: the square multi-TU path used the
10578 /// standalone-block tables instead of this rule and granted a 16x16
10579 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
10580 #[test]
10581 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
10582 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
10583 // *_count_unit = tx size / 4.
10584 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
10585 let (plane_bw_unit, count) = (bw / 4, tx / 4);
10586 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
10587 let _ = bh;
10588 if row_off_u > 0 {
10589 col_off_u + count < plane_bw_unit
10590 } else if col_off_u + count < plane_bw_unit {
10591 true
10592 } else {
10593 blk
10594 }
10595 }
10596 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
10597 let (plane_bh_unit, count) = (bh / 4, tx / 4);
10598 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
10599 let _ = bw;
10600 if col_off_u > 0 {
10601 false
10602 } else if row_off_u + count < plane_bh_unit {
10603 true
10604 } else {
10605 blk
10606 }
10607 }
10608 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
10609 for &tx in &[4usize, 8, 16, 32] {
10610 if tx > bw.min(bh) {
10611 continue;
10612 }
10613 for row_off in (0..bh).step_by(tx) {
10614 for col_off in (0..bw).step_by(tx) {
10615 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
10616 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
10617 assert_eq!(
10618 got.above_right,
10619 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
10620 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
10621 );
10622 assert_eq!(
10623 got.below_left,
10624 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
10625 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
10626 );
10627 }
10628 }
10629 }
10630 }
10631 }
10632 }
10633
10634 #[test]
10635 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
10636 let fctx = &crate::decode::FrameCtx::new();
10637 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
10638 // Interior superblock, so neither the frame edge nor the col == 0 /
10639 // last-row early returns answer instead of the table.
10640 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
10641 let mut flipped = 0;
10642 for row in 0..8 {
10643 for col in 1..8 {
10644 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
10645 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
10646 let vert = {
10647 let _guard = Reach::vert_ab_partition();
10648 Reach::of(8, x, y, width, height, fctx).below_left
10649 };
10650 // The TR square of a VERT_A/_B sits at an even row, odd
10651 // column; every other slot must be untouched by the guard.
10652 if row % 2 == 0 && col % 2 == 1 {
10653 assert!(!raster, "raster below_left at row={row} col={col}");
10654 assert!(vert, "vert below_left at row={row} col={col}");
10655 flipped += 1;
10656 } else {
10657 assert_eq!(raster, vert, "guard moved row={row} col={col}");
10658 }
10659 }
10660 }
10661 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
10662 // The guard is scoped: it must not leak past its own block.
10663 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
10664 }
10665
10666 /// An odd width or height is refused by name, not by however the padder
10667 /// or the block coder would happen to fail on it.
10668 #[test]
10669 fn odd_dimensions_are_refused() {
10670 let fctx = &crate::decode::FrameCtx::new();
10671 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
10672 let picture = Picture::grey(width, height);
10673 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
10674 .expect_err(&format!("{width}x{height} is odd and must be refused"));
10675 assert!(
10676 err.to_string().contains("even"),
10677 "{width}x{height}: error was {err}"
10678 );
10679 }
10680 }
10681
10682 /// A sequence at a size that is not a multiple of the block grid decodes
10683 /// to the right frame count and the right size for every frame,
10684 /// including the inter frames whose reference is the previous frame's
10685 /// own (padded) reconstruction.
10686 #[test]
10687 fn sequence_round_trips_at_a_non_multiple_size() {
10688 let fctx = &crate::decode::FrameCtx::new();
10689 if !have_ffmpeg() {
10690 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
10691 return;
10692 }
10693 let (width, height) = (160usize, 96usize);
10694 let pictures: Vec<Picture> = (0..3)
10695 .map(|i| panned_test_card(width, height, i * 3))
10696 .collect();
10697 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
10698 assert_eq!(encoded.frames.len(), 3);
10699 for (i, frame) in encoded.frames.iter().enumerate() {
10700 assert_eq!(
10701 (frame.reconstruction.width, frame.reconstruction.height),
10702 (width, height),
10703 "frame {i}: reconstruction size"
10704 );
10705 }
10706 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
10707 // true (display) size a sequence's frames share, not the padded one.
10708 assert_eq!(
10709 ffprobe_size(&encoded.stream),
10710 (width as u32, height as u32),
10711 "sequence: ffprobe reports the true (display) size"
10712 );
10713 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
10714 assert_eq!(decoded.len(), 3, "decoded frame count");
10715 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
10716 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
10717 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
10718 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
10719 }
10720 }
10721
10722 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
10723 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
10724 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
10725 /// `pos + side_mi / 2 < bound` boundary), which is the case
10726 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
10727 /// refusing. A key frame alone already covered this size; this proves the
10728 /// inter tile writer's parity with it across a real multi-frame export.
10729 #[test]
10730 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
10731 let fctx = &crate::decode::FrameCtx::new();
10732 if !have_ffmpeg() {
10733 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
10734 return;
10735 }
10736 let (width, height) = (1280usize, 720usize);
10737 let pictures: Vec<Picture> = (0..3)
10738 .map(|i| panned_test_card(width, height, i * 3))
10739 .collect();
10740 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
10741 assert_eq!(encoded.frames.len(), 3);
10742 for (i, frame) in encoded.frames.iter().enumerate() {
10743 assert_eq!(
10744 (frame.reconstruction.width, frame.reconstruction.height),
10745 (width, height),
10746 "frame {i}: reconstruction size"
10747 );
10748 }
10749 assert_eq!(
10750 ffprobe_size(&encoded.stream),
10751 (width as u32, height as u32),
10752 "ffprobe reports the true (display) 1280x720 size"
10753 );
10754 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
10755 assert_eq!(decoded.len(), 3, "decoded frame count");
10756 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
10757 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
10758 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
10759 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
10760 }
10761 }
10762
10763 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
10764 /// leaf's own half (`has_half` at the SUB level) itself straddles the
10765 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
10766 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
10767 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
10768 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
10769 /// straddling-16x16 branch), so an inter frame no longer refuses this
10770 /// size either. This only proves the encoder does not error out -- see
10771 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
10772 /// decoder-clean proof (a 3-frame sequence, so the inter path is
10773 /// actually exercised).
10774 #[test]
10775 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
10776 let fctx = &crate::decode::FrameCtx::new();
10777 let (width, height) = (640usize, 360usize);
10778 let picture = Picture::grey(width, height);
10779 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
10780
10781 // `encode_sequence`'s second frame is the inter path: same size, now
10782 // wired the same way.
10783 let pictures = vec![picture.clone(), picture];
10784 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
10785 .expect("inter frame now codes the mod-32==8 straddle too");
10786 }
10787
10788 /// The r15 fix at production size: three 640x360 key frames (inter is
10789 /// still refused at this size, per the test above, so this stands in for
10790 /// the charter's "3-frame sequence" using three independent key frames of
10791 /// shifted content), each proven decoder-clean through ffmpeg rather than
10792 /// only encoder-clean.
10793 #[test]
10794 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
10795 let fctx = &crate::decode::FrameCtx::new();
10796 if !have_ffmpeg() {
10797 eprintln!(
10798 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
10799 no ffmpeg"
10800 );
10801 return;
10802 }
10803 let (width, height) = (640usize, 360usize);
10804 for shift in [0i64, 7, 19] {
10805 let picture = panned_test_card(width, height, shift);
10806 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10807 let decoded = ffmpeg_decode(&encoded.stream, width, height);
10808 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
10809 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
10810 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
10811 }
10812 }
10813
10814 /// The 640x360 straddle class, but through the inter path an actual
10815 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
10816 /// proves the leaf-8 inter stream this round wires up is not just
10817 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
10818 #[test]
10819 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
10820 let fctx = &crate::decode::FrameCtx::new();
10821 if !have_ffmpeg() {
10822 eprintln!(
10823 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
10824 );
10825 return;
10826 }
10827 let (width, height) = (640usize, 360usize);
10828 let pictures: Vec<Picture> = (0..4)
10829 .map(|i| panned_test_card(width, height, i * 3))
10830 .collect();
10831 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
10832 assert_eq!(encoded.frames.len(), 4);
10833 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
10834 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
10835 }
10836 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
10837 assert_eq!(decoded.len(), 4, "decoded frame count");
10838 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
10839 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
10840 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
10841 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
10842 }
10843 }
10844
10845 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
10846 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
10847 let out = Command::new("ffmpeg")
10848 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
10849 .args(["-vf", &format!("scale={width}:{height}")])
10850 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
10851 .output()
10852 .expect("ffmpeg failed to run");
10853 assert!(
10854 out.status.success(),
10855 "ffmpeg: {}",
10856 String::from_utf8_lossy(&out.stderr)
10857 );
10858 let (luma, chroma) = (width * height, width * height / 4);
10859 assert_eq!(
10860 out.stdout.len(),
10861 luma + 2 * chroma,
10862 "expected one 4:2:0 frame"
10863 );
10864 Picture {
10865 width,
10866 height,
10867 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
10868 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
10869 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
10870 }
10871 }
10872
10873 /// Prints what the mode search saves over DC prediction alone, for the
10874 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
10875 /// weight the search puts on rate can be swept.
10876 #[test]
10877 #[ignore = "a sweep, not a gate"]
10878 fn probe_lambda() {
10879 let fctx = &crate::decode::FrameCtx::new();
10880 let mut pictures = vec![
10881 ("test card".to_string(), test_card(160, 96)),
10882 ("stripes".to_string(), stripes(160, 96, true)),
10883 ];
10884 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
10885 for entry in clips.split(':').filter(|e| !e.is_empty()) {
10886 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
10887 let name = path.rsplit('/').next().unwrap_or(path).to_string();
10888 pictures.push((name, clip_frame(path, skip, 640, 352)));
10889 }
10890 }
10891 for (name, picture) in pictures {
10892 let dc = ladder(&picture, &[DC_PRED], fctx);
10893 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
10894 println!(
10895 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
10896 bd_rate(&dc, &searched) * 100.0,
10897 10f64.powf(searched[1].1),
10898 searched[1].0,
10899 10f64.powf(dc[1].1),
10900 dc[1].0,
10901 );
10902 }
10903 }
10904
10905 /// Prints the whole mode-search ladder, so two builds of the search can be
10906 /// compared against each other rather than each against its own baseline.
10907 #[test]
10908 #[ignore = "a sweep, not a gate"]
10909 fn probe_ladder() {
10910 let fctx = &crate::decode::FrameCtx::new();
10911 for (name, picture) in sweep_pictures() {
10912 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
10913 let points = all
10914 .iter()
10915 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
10916 .collect::<Vec<_>>()
10917 .join(" ");
10918 println!("ladder {name}: {points}");
10919 }
10920 }
10921
10922 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
10923 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
10924 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
10925 #[test]
10926 #[ignore = "a sweep, not a gate"]
10927 fn probe_split() {
10928 let fctx = &crate::decode::FrameCtx::new();
10929 for (name, picture) in sweep_pictures() {
10930 let ladder = |split: bool| {
10931 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
10932 .iter()
10933 .map(|&q| {
10934 let encoded = encode_key_frame_inner(
10935 &picture,
10936 q,
10937 0.5,
10938 &KEY_FRAME_MODES,
10939 split,
10940 (picture.width, picture.height),
10941 unspecified_color_config(), fctx,
10942 )
10943 .unwrap();
10944 (
10945 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
10946 (encoded.stream.len() as f64).log10(),
10947 )
10948 })
10949 .collect();
10950 points.sort_by(|a, b| a.0.total_cmp(&b.0));
10951 points
10952 };
10953 let (whole, split) = (ladder(false), ladder(true));
10954 let blocks = encode_key_frame_inner(
10955 &picture,
10956 90,
10957 0.5,
10958 &KEY_FRAME_MODES,
10959 true,
10960 (picture.width, picture.height),
10961 unspecified_color_config(), fctx,
10962 )
10963 .unwrap()
10964 .modes
10965 .len();
10966 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
10967 println!(
10968 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
10969 bd_rate(&whole, &split) * 100.0
10970 );
10971 }
10972 }
10973
10974 /// A striped picture, running one way or the other. The stripes are what
10975 /// separates a vertical predictor from a horizontal one: a mode search
10976 /// reading a transposed edge would pick the wrong one of the pair, which no
10977 /// symmetric picture would show.
10978 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
10979 let mut picture = Picture::grey(width, height);
10980 for y in 0..height {
10981 for x in 0..width {
10982 let along = if vertical { x } else { y };
10983 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
10984 }
10985 }
10986 picture
10987 }
10988
10989 /// Where two planes first disagree, and by how much: a mismatch reported as
10990 /// a position says which block and which sample of it went wrong, which a
10991 /// pair of thousand-sample arrays does not.
10992 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
10993 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
10994 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
10995 Some(format!(
10996 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
10997 i % width,
10998 i / width,
10999 ours[i],
11000 theirs[i]
11001 ))
11002 }
11003
11004 /// Every mode the encoder offers has to predict what the decoder predicts,
11005 /// not just the ones a particular picture happens to choose: each is forced
11006 /// over a whole picture and the reconstruction gated against ffmpeg.
11007 #[test]
11008 fn every_mode_decodes_to_what_the_encoder_predicted() {
11009 let fctx = &crate::decode::FrameCtx::new();
11010 if !have_ffmpeg() {
11011 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
11012 return;
11013 }
11014 // 128 wide is a whole number of superblocks and 160 is not: the last
11015 // superblock of a 160-wide row is half a one, whose blocks have no
11016 // above-right samples inside the frame at all.
11017 for (width, height) in [(128, 96), (160, 96)] {
11018 let picture = test_card(width, height);
11019 for mode in KEY_FRAME_MODES {
11020 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
11021 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11022 for (plane, ours, theirs, stride) in [
11023 ("luma", &encoded.reconstruction.y, &decoded.y, width),
11024 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
11025 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
11026 ] {
11027 assert!(
11028 first_difference(ours, theirs, stride).is_none(),
11029 "{width}x{height} mode {mode}, {plane}: {}",
11030 first_difference(ours, theirs, stride).unwrap()
11031 );
11032 }
11033 assert!(
11034 encoded.modes.iter().all(|&m| m == mode),
11035 "mode {mode}: the encoder coded something else"
11036 );
11037 }
11038 }
11039 }
11040
11041 /// The search has to follow the picture: vertical stripes are cheapest
11042 /// predicted from the row above, horizontal ones from the column to the
11043 /// left. Reading the edges the other way round would swap the two answers
11044 /// while leaving every fidelity gate intact.
11045 #[test]
11046 fn the_search_picks_the_direction_the_picture_runs() {
11047 let fctx = &crate::decode::FrameCtx::new();
11048 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
11049 let picture = stripes(128, 96, vertical);
11050 // Only the pair, because on stripes a third mode predicts exactly
11051 // what the right one of the pair does -- PAETH reads the corner and
11052 // the left column, which a striped picture makes equal -- and the
11053 // tie then goes to whichever is cheaper to name, which is not what
11054 // this gate is about.
11055 let encoded =
11056 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
11057 // The first block of the picture has neither neighbour, so it
11058 // cannot tell the modes apart; every other one can.
11059 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
11060 assert!(
11061 picked * 2 > encoded.modes.len() - 1,
11062 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
11063 encoded.modes.len() - 1,
11064 encoded.modes
11065 );
11066 }
11067 }
11068
11069 /// What the search is for: the same picture, at the same quantizer, coded
11070 /// smaller and more faithfully than DC alone can manage.
11071 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
11072 /// between the two rate-distortion curves in log-rate against PSNR, as a
11073 /// fraction of the reference's rate. Negative means the second curve costs
11074 /// less for the same picture.
11075 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
11076 let low = reference[0].0.max(other[0].0);
11077 let high = reference[reference.len() - 1]
11078 .0
11079 .min(other[other.len() - 1].0);
11080 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
11081 // the non-directional one on the synthetic diagonals -- every point
11082 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
11083 // to integrate over any more. A curve that dominates that way has
11084 // saved everything the measure can express (the
11085 // `instrument-at-bound` class: the answer is at the instrument's own
11086 // edge, not undefined), so name it rather than panicking; anything
11087 // less clean than strict dominance still is.
11088 if high <= low {
11089 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
11090 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
11091 let dominates = other[0].0 > reference[reference.len() - 1].0
11092 && other_hi_rate <= ref_lo_rate;
11093 assert!(
11094 dominates,
11095 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
11096 );
11097 return -1.0;
11098 }
11099 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
11100 let i = curve
11101 .windows(2)
11102 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
11103 .unwrap_or(0);
11104 let (x0, y0) = curve[i];
11105 let (x1, y1) = curve[i + 1];
11106 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
11107 };
11108 let steps = 64;
11109 let mut area = 0.0;
11110 for step in 0..steps {
11111 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
11112 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
11113 }
11114 10f64.powf(area / f64::from(steps)) - 1.0
11115 }
11116
11117 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
11118 /// fidelity.
11119 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
11120 // A mode ablation measures the MODE search: the palette would code
11121 // these synthetic two-colour pictures losslessly under every arm and
11122 // leave nothing to compare (see [`force_screen`]).
11123 force_screen(Some(false));
11124 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
11125 .iter()
11126 .map(|&q| {
11127 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
11128 (
11129 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
11130 (encoded.stream.len() as f64).log10(),
11131 )
11132 })
11133 .collect();
11134 points.sort_by(|a, b| a.0.total_cmp(&b.0));
11135 points
11136 }
11137
11138 /// What the search is for: the same pictures cost less to code at the same
11139 /// fidelity than DC prediction alone can manage. A picture that runs one
11140 /// way saves far more than a busy one, which is the shape a working
11141 /// directional pair has.
11142 #[test]
11143 fn the_search_beats_dc_alone() {
11144 let fctx = &crate::decode::FrameCtx::new();
11145 for (name, picture, want) in [
11146 ("test card", test_card(160, 96), -0.05),
11147 ("stripes", stripes(160, 96, true), -0.40),
11148 ] {
11149 let saved = bd_rate(
11150 &ladder(&picture, &[DC_PRED], fctx),
11151 &ladder(&picture, &NON_DIRECTIONAL, fctx),
11152 );
11153 assert!(
11154 saved < want,
11155 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
11156 saved * 100.0,
11157 -want * 100.0
11158 );
11159 }
11160 }
11161
11162 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
11163 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
11164 fn sweep_pictures() -> Vec<(String, Picture)> {
11165 let mut pictures = vec![
11166 ("test card".to_string(), test_card(160, 96)),
11167 ("stripes".to_string(), stripes(160, 96, true)),
11168 ("diagonal".to_string(), diagonal(160, 96, true)),
11169 ];
11170 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
11171 for entry in clips.split(':').filter(|e| !e.is_empty()) {
11172 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
11173 let name = path.rsplit('/').next().unwrap_or(path).to_string();
11174 pictures.push((name, clip_frame(path, skip, 640, 352)));
11175 }
11176 }
11177 pictures
11178 }
11179
11180 /// What the six directional modes are worth, per picture, at whatever
11181 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
11182 /// no further, and how often the search picks one.
11183 #[test]
11184 #[ignore = "a sweep, not a gate"]
11185 fn probe_directional() {
11186 let fctx = &crate::decode::FrameCtx::new();
11187 for (name, picture) in sweep_pictures() {
11188 let dc = ladder(&picture, &[DC_PRED], fctx);
11189 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
11190 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
11191 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
11192 let directional = encoded
11193 .modes
11194 .iter()
11195 .filter(|&&m| (3..=8).contains(&m))
11196 .count();
11197 // A picture whose ladders sit at different fidelities altogether
11198 // has no BD-rate to report -- see the flat-sample-window class.
11199 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
11200 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
11201 };
11202 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
11203 if overlap(a, b) {
11204 format!("{:+.2}%", bd_rate(a, b) * 100.0)
11205 } else {
11206 "no overlap".to_string()
11207 }
11208 };
11209 println!(
11210 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
11211 against(&flat, &all),
11212 against(&dc, &all),
11213 encoded.modes.len(),
11214 );
11215 }
11216 }
11217
11218 /// A picture whose stripes run along a diagonal, one way or the other.
11219 /// This is to the directional modes what [`stripes`] is to the vertical and
11220 /// horizontal pair: a predictor that walked the edge in the wrong direction
11221 /// would answer the two pictures the same way round.
11222 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
11223 let mut picture = Picture::grey(width, height);
11224 for y in 0..height {
11225 for x in 0..width {
11226 let along = if down_right { x + height - y } else { x + y };
11227 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
11228 }
11229 }
11230 picture
11231 }
11232
11233 /// The mode picked by the most blocks of a picture, ignoring the first
11234 /// block, which has no neighbours to tell the modes apart with.
11235 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
11236 // A mode ablation measures the MODE search: the palette would code
11237 // these synthetic two-colour pictures losslessly under every arm and
11238 // leave nothing to compare (see [`force_screen`]).
11239 force_screen(Some(false));
11240 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
11241 let blocks = &encoded.modes[1..];
11242 let mut counts = [0usize; 13];
11243 for &mode in blocks {
11244 counts[usize::from(mode)] += 1;
11245 }
11246 let (mode, count) = counts
11247 .iter()
11248 .enumerate()
11249 .max_by_key(|&(_, count)| *count)
11250 .expect("thirteen modes");
11251 (mode as u8, *count, blocks.len())
11252 }
11253
11254 /// The search has to follow a diagonal the way it runs: stripes down and to
11255 /// the right are cheapest predicted at 135 degrees, stripes down and to the
11256 /// left at 45. A walk that stepped the wrong way along the edge, or read
11257 /// the above row where it should read the left column, would swap these.
11258 #[test]
11259 fn the_search_picks_the_diagonal_the_picture_runs() {
11260 let fctx = &crate::decode::FrameCtx::new();
11261 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
11262 let picture = diagonal(160, 96, down_right);
11263 let (mode, count, blocks) = favourite_mode(&picture, fctx);
11264 assert_eq!(
11265 mode, want,
11266 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
11267 );
11268 }
11269 }
11270
11271 /// What the directional modes are for: a picture that runs along a diagonal
11272 /// costs far less to code with them than the seven that read only their own
11273 /// edges can manage, and a picture that runs no particular way costs no
11274 /// more. The second half is the one that bites: a mode set the search
11275 /// cannot price is a mode set that loses rate on content that does not want
11276 /// it, which is what costing the mode symbol is for.
11277 #[test]
11278 fn the_diagonals_beat_the_modes_that_read_no_further() {
11279 let fctx = &crate::decode::FrameCtx::new();
11280 for (name, picture, want) in [
11281 ("down-right", diagonal(160, 96, true), -0.20),
11282 ("down-left", diagonal(160, 96, false), -0.20),
11283 ("test card", test_card(160, 96), 0.01),
11284 ] {
11285 let saved = bd_rate(
11286 &ladder(&picture, &NON_DIRECTIONAL, fctx),
11287 &ladder(&picture, &KEY_FRAME_MODES, fctx),
11288 );
11289 assert!(
11290 saved < want,
11291 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
11292 saved * 100.0,
11293 -want * 100.0
11294 );
11295 }
11296 }
11297
11298 /// A mode the encoder cannot predict must be refused rather than coded as
11299 /// something else, and a search with nothing to choose from likewise.
11300 #[test]
11301 fn a_mode_the_encoder_cannot_predict_is_refused() {
11302 let fctx = &crate::decode::FrameCtx::new();
11303 let picture = test_card(64, 64);
11304 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
11305 .unwrap_err()
11306 .to_string();
11307 assert!(
11308 message.contains("intra mode 13"),
11309 "the refusal must name the mode, got {message}"
11310 );
11311 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
11312 }
11313
11314 /// The picture that comes back is the picture that went in, to within the
11315 /// quantizer. A prediction that read the wrong neighbours, or a block
11316 /// written into the wrong place, would still decode to what the encoder
11317 /// reconstructed — it is this gate that says the reconstruction is of the
11318 /// right picture.
11319 #[test]
11320 fn the_encoded_picture_is_the_one_that_went_in() {
11321 let fctx = &crate::decode::FrameCtx::new();
11322 let picture = test_card(160, 96);
11323 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11324 let luma = psnr(&encoded.reconstruction.y, &picture.y);
11325 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
11326 for (plane, (got, want)) in [
11327 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
11328 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
11329 ]
11330 .iter()
11331 .enumerate()
11332 {
11333 let chroma = psnr(got, want);
11334 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
11335 }
11336 }
11337
11338 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
11339 /// does the opposite. Both are monotone, which is what a rate-distortion
11340 /// loop above this will assume.
11341 #[test]
11342 fn fidelity_and_rate_move_with_the_quantizer() {
11343 let fctx = &crate::decode::FrameCtx::new();
11344 let picture = test_card(128, 128);
11345 let mut previous: Option<(usize, f64)> = None;
11346 for &q in &[70u8, 90, 110] {
11347 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
11348 let quality = psnr(&encoded.reconstruction.y, &picture.y);
11349 if let Some((bytes, better)) = previous {
11350 assert!(
11351 encoded.stream.len() < bytes,
11352 "q {q}: {} bytes",
11353 encoded.stream.len()
11354 );
11355 assert!(quality < better, "q {q}: PSNR {quality}");
11356 }
11357 previous = Some((encoded.stream.len(), quality));
11358 }
11359
11360 let mut previous = None;
11361 for &deadzone in &[0.5f64, 0.3, 0.15] {
11362 let encoded = encode_key_frame_with_ctx(&picture, 100, deadzone, fctx).unwrap();
11363 let quality = psnr(&encoded.reconstruction.y, &picture.y);
11364 if let Some((bytes, better)) = previous {
11365 assert!(
11366 encoded.stream.len() < bytes,
11367 "deadzone {deadzone}: {} bytes",
11368 encoded.stream.len()
11369 );
11370 assert!(quality < better, "deadzone {deadzone}: PSNR {quality}");
11371 }
11372 previous = Some((encoded.stream.len(), quality));
11373 }
11374
11375 // Bytes must not jump up across a q-context boundary: a wrong CDF
11376 // table for the far side would show up as a rate discontinuity here,
11377 // even though a coarser quantizer always codes no more than a finer
11378 // one on the same picture.
11379 //
11380 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
11381 // chroma searches its own mode, a coarser quantizer can pick a
11382 // *different* uv_mode on a block whose modes now cost nearly the
11383 // same, and the search prices that symbol against the static default
11384 // CDF while the writer codes it against an adapted one -- 311 -> 319
11385 // bytes at q 120->121 on this picture. The table this gate is really
11386 // watching would move the rate by far more than the mode churn does.
11387 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
11388 // same block can also change transform DEPTH between two neighbouring
11389 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
11390 // symbol is priced off the static CDF row 0 for the same reason the
11391 // uv_mode one is.
11392 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
11393 // path is pricing through the adapting CDF state (what
11394 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
11395 // drift of), after which the exact bound comes back.
11396 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
11397 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
11398 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
11399 assert!(
11400 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
11401 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
11402 );
11403 }
11404 }
11405
11406 /// A flat picture is a flat stream: every block predicts its neighbours'
11407 /// average, which is the picture's own value, and codes nothing.
11408 #[test]
11409 fn a_flat_picture_costs_almost_nothing() {
11410 let fctx = &crate::decode::FrameCtx::new();
11411 let mut picture = Picture::grey(128, 128);
11412 picture.y.fill(97);
11413 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11414 // The first block has no neighbour and predicts 128, so it carries a
11415 // DC; every block after it predicts 97 and carries nothing.
11416 assert!(
11417 encoded.stream.len() < 100,
11418 "{} bytes for a flat picture",
11419 encoded.stream.len()
11420 );
11421 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
11422 assert_eq!(s, 97, "sample {i} of a flat picture");
11423 }
11424 }
11425
11426 /// The sizes the encoder refuses, refused for a reason rather than by
11427 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
11428 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
11429 /// lands past the halfway point of whichever block it falls in, so
11430 /// `PARTITION_NONE` or a single gathered split flag still says everything
11431 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
11432 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
11433 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
11434 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
11435 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
11436 /// refusal here claimed otherwise and was wrong; see
11437 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
11438 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
11439 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
11440 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
11441 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
11442 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
11443 /// still refused is a malformed picture.
11444 #[test]
11445 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
11446 let fctx = &crate::decode::FrameCtx::new();
11447 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
11448 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
11449 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
11450 .expect("36 luma columns still round up to an even MiCols");
11451
11452 let mut short = Picture::grey(64, 64);
11453 short.u.truncate(10);
11454 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
11455 }
11456
11457 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
11458 /// column half only (`has_half` false on cols, true on rows) -- exactly
11459 /// the single-axis straddle lane-av1-rect r7 wires through
11460 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
11461 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
11462 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
11463 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
11464 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
11465 /// `partition_context_lookup` entry this writer ever produces (no 4x4
11466 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
11467 /// leaf regardless of neighbour state -- our writer already agreed with
11468 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
11469 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
11470 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
11471 /// it does not regress the gate. r11 tell-for-tell traced two further,
11472 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
11473 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
11474 /// leaves, when the second leaf's true above (or left) neighbour is the
11475 /// first leaf itself -- fixed by threading the first leaf's mode into the
11476 /// second leaf's context, mi-precise, like `record_mi` already does for
11477 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
11478 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
11479 /// `reduced_tx_set` is false), but this crate's key frames set
11480 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
11481 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
11482 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
11483 /// symbol bits to desync everything after it. Fixed with a new
11484 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
11485 /// eset/size slot). Both fixes are provably correct against libaom
11486 /// source and each closed part of the gap (leaf0's `eob` went from a
11487 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
11488 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
11489 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
11490 /// (do not reuse r11's committed logs, which predate its own fixes) and
11491 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
11492 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
11493 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
11494 /// every other `write_block` caller at 16x16 and up already passes
11495 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
11496 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
11497 /// different amount of arithmetic range and derailed everything after
11498 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
11499 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
11500 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
11501 /// never updating those coarse arrays itself -- so a *second* straddling
11502 /// 16x16 quadrant stacked above or left of the first (never covered by
11503 /// r11's same-call `prev_leaf` override, which only threads state
11504 /// between the two leaves of one shared quadrant) read whatever stale
11505 /// mode sat in that slot before either leaf ran. Fixed by writing the
11506 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
11507 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
11508 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
11509 /// offset of a single unit; fixing (3)+(4) together still leaves a
11510 /// residual divergence one leaf further in -- the decoder now reads
11511 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
11512 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
11513 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
11514 /// desyncs the stream by exactly the width of one earlier symbol -- not
11515 /// yet isolated to a single named symbol. r15 found the last bug: the
11516 /// header fix from r14 explained the rng skew fully, and the remaining
11517 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
11518 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
11519 /// loop, once per leaf, so the first leaf's write clobbered the true
11520 /// external neighbour mode the second leaf of the *same* straddling
11521 /// quadrant still needed for its non-adjacency axis (a column-straddle
11522 /// case: two leaves share one `outer_at` column index, so leaf 1's
11523 /// write to `left_mode[r]` overwrote the real western neighbour before
11524 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
11525 /// doing it once, after the whole leaf loop, from the last (bottom/
11526 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
11527 #[test]
11528 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
11529 let fctx = &crate::decode::FrameCtx::new();
11530 if !have_ffmpeg() {
11531 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
11532 return;
11533 }
11534 let (width, height) = (40usize, 32usize);
11535 let picture = test_card(width, height);
11536 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11537 assert_eq!(
11538 (encoded.reconstruction.width, encoded.reconstruction.height),
11539 (width, height)
11540 );
11541 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
11542 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
11543 }
11544 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11545 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
11546 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
11547 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
11548 }
11549
11550 /// A frame of real video, rather than a picture built to be easy.
11551 ///
11552 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
11553 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
11554 /// encoder's reconstruction has to survive the same equality gate as the
11555 /// synthetic pictures — real video reaches contexts a test card does not.
11556 #[test]
11557 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
11558 let fctx = &crate::decode::FrameCtx::new();
11559 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
11560 eprintln!(
11561 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
11562 set EC_AV1_CLIP to a clip"
11563 );
11564 return;
11565 };
11566 if !have_ffmpeg() {
11567 eprintln!(
11568 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
11569 );
11570 return;
11571 }
11572 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
11573 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
11574 // test quick while still spanning many superblocks.
11575 let (width, height) = (640usize, 352usize);
11576 let picture = clip_frame(&clip, &skip, width, height);
11577
11578 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
11579 let decoded = ffmpeg_decode(&encoded.stream, width, height);
11580 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
11581 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
11582 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
11583 eprintln!(
11584 "{} bytes, luma PSNR {:.2} dB",
11585 encoded.stream.len(),
11586 psnr(&decoded.y, &picture.y)
11587 );
11588 }
11589
11590 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
11591 /// sequence of these is a translation a motion search can actually find
11592 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
11593 /// inter frame's rate against the key frame's is measuring the same
11594 /// picture moving, not two different pictures.
11595 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
11596 let mut picture = Picture::grey(width, height);
11597 for y in 0..height {
11598 for x in 0..width {
11599 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
11600 let gradient = sx * 200.0 / width as f64;
11601 let ripple = 30.0
11602 * (sx * std::f64::consts::PI / 23.0).sin()
11603 * (y as f64 * std::f64::consts::PI / 37.0).cos();
11604 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
11605 40.0
11606 } else {
11607 0.0
11608 };
11609 picture.y[y * width + x] =
11610 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
11611 }
11612 }
11613 for y in 0..height / 2 {
11614 for x in 0..width / 2 {
11615 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
11616 let i = y * width / 2 + x;
11617 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
11618 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
11619 }
11620 }
11621 picture
11622 }
11623
11624 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
11625 fn ffmpeg_decode_sequence(
11626 stream: &[u8],
11627 width: usize,
11628 height: usize,
11629 frames: usize,
11630 ) -> Vec<Picture> {
11631 let mut child = Command::new("ffmpeg")
11632 .args([
11633 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
11634 ])
11635 .stdin(Stdio::piped())
11636 .stdout(Stdio::piped())
11637 .stderr(Stdio::piped())
11638 .spawn()
11639 .expect("ffmpeg failed to start");
11640 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
11641 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
11642 // fills before the last input byte is written -- which is exactly what
11643 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
11644 // (measured: 45 min, both processes at 0% CPU). A write error here is
11645 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
11646 // below, are the real diagnosis.
11647 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
11648 let payload = stream.to_vec();
11649 let writer = std::thread::spawn(move || {
11650 let _ = stdin.write_all(&payload);
11651 });
11652 let out = child.wait_with_output().expect("ffmpeg failed to run");
11653 writer.join().expect("ffmpeg stdin writer thread");
11654 assert!(
11655 out.status.success(),
11656 "ffmpeg refused the stream: {}",
11657 String::from_utf8_lossy(&out.stderr)
11658 );
11659 let (luma, chroma) = (width * height, width * height / 4);
11660 let frame_bytes = luma + 2 * chroma;
11661 assert_eq!(
11662 out.stdout.len(),
11663 frame_bytes * frames,
11664 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
11665 String::from_utf8_lossy(&out.stderr)
11666 );
11667 (0..frames)
11668 .map(|i| {
11669 let base = i * frame_bytes;
11670 Picture {
11671 width,
11672 height,
11673 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
11674 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
11675 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
11676 }
11677 })
11678 .collect()
11679 }
11680
11681 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
11682 /// makes for a key frame, extended down the reference chain: each inter
11683 /// frame's reconstruction predicts from the previous frame's own decoded
11684 /// reconstruction, so a single sample of drift anywhere would propagate
11685 /// into every frame after it -- which is why every frame is checked, not
11686 /// just the last one, and why this is an equality and not a tolerance.
11687 #[test]
11688 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
11689 let fctx = &crate::decode::FrameCtx::new();
11690 if !have_ffmpeg() {
11691 eprintln!(
11692 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
11693 );
11694 return;
11695 }
11696 let (width, height) = (128usize, 64usize);
11697 let pictures: Vec<Picture> = (0..5)
11698 .map(|i| panned_test_card(width, height, i * 3))
11699 .collect();
11700 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
11701 assert_eq!(encoded.frames.len(), 5);
11702
11703 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
11704 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
11705 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
11706 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
11707 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
11708 }
11709
11710 eprintln!("frame bytes luma PSNR (dB) inter share");
11711 for (i, frame) in encoded.frames.iter().enumerate() {
11712 eprintln!(
11713 "{i:5} {:5} {:14.2} {:11.2}",
11714 frame.stream.len(),
11715 psnr(&frame.reconstruction.y, &pictures[i].y),
11716 frame.inter_block_share
11717 );
11718 }
11719 }
11720
11721 /// The same sequence through OUR OWN decoder, sample-exact against the
11722 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
11723 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
11724 /// divergence point at all, while our decoder can be traced symbol by
11725 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
11726 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
11727 /// names the first differing frame, plane and position.
11728 #[test]
11729 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
11730 let fctx = &crate::decode::FrameCtx::new();
11731 // 256x128, not the 128x64 this started at: once a leaf could search
11732 // its second reference (lane-av1comp4) the small card's every
11733 // eligible block went to a compound winner, which commits its flat
11734 // transform, and the split below stopped firing on content that
11735 // still splits at every larger size ([[gate-blind-to-feature]] --
11736 // the guard is right, the fixture had shrunk under it).
11737 let (width, height) = (256usize, 128usize);
11738 let pictures: Vec<Picture> =
11739 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
11740 let _ = take_inter_tx_split_hits();
11741 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
11742 let raw = take_inter_tx_split_hits();
11743 // Summed over the four block classes the census keys on (leaf/32x32 x
11744 // single/compound): this assert is about the split firing at all.
11745 let split = [
11746 raw.iter().step_by(2).sum::<usize>(),
11747 raw.iter().skip(1).step_by(2).sum::<usize>(),
11748 ];
11749 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
11750 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
11751 // content splits -- a green round trip in which the split never fires
11752 // would prove only the flat path.
11753 if tx_select() && tx_select_inter() {
11754 assert!(split[1] > 0, "the inter var-tx split never fired");
11755 }
11756 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
11757 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
11758 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
11759 let recon = &frame.reconstruction;
11760 for (plane, got, want, stride) in [
11761 ("luma", &dec.y, &recon.y, width),
11762 ("U", &dec.u, &recon.u, width / 2),
11763 ("V", &dec.v, &recon.v, width / 2),
11764 ] {
11765 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
11766 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
11767 panic!(
11768 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
11769 reconstruction {} ({} of {} samples differ)",
11770 at % stride,
11771 at / stride,
11772 got[at],
11773 want[at],
11774 got.iter().zip(want).filter(|(a, b)| a != b).count(),
11775 got.len(),
11776 );
11777 }
11778 }
11779 }
11780 }
11781
11782 /// The rate term the mode search ranks every decision by has to be the
11783 /// rate the writer then spends. The search prices a block's coefficients
11784 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
11785 /// against the default CDFs a tile starts from and the contexts of a
11786 /// block whose neighbours coded nothing -- while the tile writer codes
11787 /// them against a state that has been adapting all frame (the
11788 /// price-the-narrowing class). This measures that drift: the sum of what
11789 /// the search paid for the coefficients it kept, against the bytes the
11790 /// writer actually emitted for the whole tile (which also carries the
11791 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
11792 /// expected to be the larger of the two).
11793 #[test]
11794 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
11795 let fctx = &crate::decode::FrameCtx::new();
11796 let (width, height) = (256usize, 128usize);
11797 let pictures: Vec<Picture> = (0..5)
11798 .map(|i| panned_test_card(width, height, i * 2))
11799 .collect();
11800 let _ = take_predicted_bits();
11801 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
11802 let predicted = take_predicted_bits();
11803 assert_eq!(predicted.len(), encoded.frames.len());
11804
11805 eprintln!("frame predicted bits written bits drift");
11806 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
11807 // defect this gate exists to catch), a positive one is the written
11808 // side carrying syntax the coefficient sum leaves out -- and since
11809 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
11810 // on that side, so the two directions no longer share a bound.
11811 let mut worst_over: f64 = 0.0;
11812 let mut worst_under: f64 = 0.0;
11813 // The census is per CODED frame, so it is zipped in coding order --
11814 // which is not display order under a pyramid.
11815 let coded: Vec<&Encoded> =
11816 encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect();
11817 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
11818 let written = frame.tile.len() as f64 * 8.0;
11819 let drift = (written - bits) / written;
11820 worst_over = worst_over.max(-drift);
11821 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
11822 // all (150-250 bits of tile, nearly all of it partition/mode/mv
11823 // syntax the coefficient sum never counts), so its ratio measures
11824 // that floor rather than any drift. Frames under 512 written bits
11825 // are left out of the under-price bound for that reason; the
11826 // over-price bound -- the defect direction, where the search pays
11827 // MORE than the writer -- still covers every frame.
11828 if written >= 512.0 {
11829 worst_under = worst_under.max(drift);
11830 }
11831 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
11832 }
11833 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
11834 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
11835 // over-prices every frame but the last (its sum EXCLUDES the
11836 // partition/mode/skip/mv syntax the written side carries, so the true
11837 // coefficient over-price is larger still): the writer's CDFs adapt to
11838 // the content while the search's stay at the defaults. The bound is
11839 // set just above the worst measured point -- a widening drift is the
11840 // thing this gate exists to catch.
11841 assert!(
11842 worst_over <= 0.16,
11843 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
11844 worst_over * 100.0
11845 );
11846 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
11847 // the worst inter frame, where nearly every block now codes an MV
11848 // residual and a reference the coefficient sum never counts. Re-measured
11849 // at +29.6% once the encoder's grid published compound blocks properly
11850 // (compound share 8.8% -> 11.5%): a compound block carries a second
11851 // reference tree, a compound mode symbol and -- for the half-new modes
11852 // -- an MV residual, none of which the coefficient sum counts.
11853 // lane-av1txbits: pricing against the tables the frame's writer really
11854 // starts from collapses the over-price above to nothing, so the whole
11855 // remaining gap is the syntax the coefficient sum leaves out. That is
11856 // the default on a non-screen frame since lane-av1price2 (this
11857 // fixture is one), and it reads +32.6% here.
11858 // lane-av1obmc: every eligible single-reference inter block now also
11859 // carries a `motion_mode` symbol the coefficient sum never counts,
11860 // and an OBMC block carries the more expensive of the two values --
11861 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
11862 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
11863 // decisions, so this bound and the byte pins above FAIL BY DESIGN
11864 // under it; the default path (no motion_mode syntax at all) is the
11865 // one they are measured on.
11866 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
11867 // coding pyramid now, so the five frames are a key frame, a hidden
11868 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
11869 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
11870 // near-empty leaves below it. Both bounds stand where they were.
11871 // lane-av1rejudge: local warp is ON by default now, so every eligible
11872 // single-reference block carries that same `motion_mode` symbol (a
11873 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
11874 // +34.9% here, one point past the OBMC reading above. The bound moves
11875 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
11876 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
11877 // symbol and one or two magnitude symbols, none of which the
11878 // coefficient sum counts either -- +36.9% here against the same
11879 // fixture's +34.9% with `EC_AV1_CFL=0`.
11880 // ... and a directional block whose `angle_delta_y` is no longer
11881 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
11882 assert!(
11883 worst_under <= 0.40,
11884 "the writer spent {:.2}% more than the search priced -- more than \
11885 the mode/mv syntax outside the coefficient sum explains",
11886 worst_under * 100.0
11887 );
11888 }
11889
11890 /// The census behind step (1) of the pricer lane: for every transform
11891 /// block the writer really codes, what the search priced those levels at
11892 /// against what the writer spent on them, split by table set and non-zero
11893 /// count. One average hides the interesting part -- the classes the
11894 /// estimate is systematically wrong about (all-zero blocks, the
11895 /// one-coefficient blocks the inter search lives on) -- so the split is
11896 /// printed and only the total is asserted on.
11897 #[test]
11898 fn pricer_error_census_by_block_class() {
11899 let fctx = &crate::decode::FrameCtx::new();
11900 let (width, height) = (256usize, 128usize);
11901 let pictures: Vec<Picture> = (0..5)
11902 .map(|i| panned_test_card(width, height, i * 2))
11903 .collect();
11904 crate::tile::pricer_census_on();
11905 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
11906 let rows = crate::tile::take_pricer_census();
11907 assert!(!rows.is_empty(), "the census saw no transform block");
11908
11909 println!("| set | nz | blocks | priced bits | written bits | error |");
11910 println!("|---|---|---|---|---|---|");
11911 let (mut priced_all, mut written_all) = (0.0, 0.0);
11912 for ((set, bucket), (blocks, priced, written)) in &rows {
11913 priced_all += priced;
11914 written_all += written;
11915 println!(
11916 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
11917 crate::tile::census_bucket_label(*bucket),
11918 if *written > 0.0 {
11919 (priced - written) / written * 100.0
11920 } else {
11921 0.0
11922 }
11923 );
11924 }
11925 println!(
11926 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
11927 rows.values().map(|r| r.0).sum::<u64>(),
11928 (priced_all - written_all) / written_all * 100.0
11929 );
11930 assert!(written_all > 0.0);
11931 }
11932
11933 /// Step (2) of the pricer lane: the same census, but on the REAL clips
11934 /// the BD gate scores -- one film clip and the screen capture -- so the
11935 /// question the film/screen split raises can be answered from data. Real
11936 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
11937 /// the screen capture larger, and the census says why: on a screen
11938 /// capture the frame's own starting tables are the tables of a frame that
11939 /// coded PALETTE and long runs of zero blocks, so they are far from the
11940 /// tables the writer ends the frame with; the pricer error does not fall
11941 /// the way it does on film.
11942 ///
11943 /// Not a gate -- it prints. Run it once per mode:
11944 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
11945 /// --ignored pricer_error_census_on_clips --nocapture
11946 #[test]
11947 #[ignore = "reads the real library, needs ffmpeg"]
11948 fn pricer_error_census_on_clips() {
11949 if !have_ffmpeg() {
11950 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
11951 return;
11952 }
11953 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
11954 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
11955 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
11956 if film.exists() {
11957 clips.push(("film 1080p".to_string(), film));
11958 }
11959 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
11960 && let Some(p) = manifest
11961 .lines()
11962 .skip(1)
11963 .filter_map(|l| l.split('\t').next())
11964 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
11965 {
11966 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
11967 }
11968 assert!(!clips.is_empty(), "no source clip available");
11969 let (width, height, frames) = (640usize, 384usize, 6usize);
11970 for (name, path) in &clips {
11971 let fctx = &crate::decode::FrameCtx::new();
11972 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
11973 SCREEN_FRAMES.iter().for_each(|c| {
11974 c.store(0, std::sync::atomic::Ordering::Relaxed);
11975 });
11976 let _ = crate::tile::take_pricing_hits();
11977 crate::tile::pricer_census_on();
11978 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
11979 let rows = crate::tile::take_pricer_census();
11980 let (price_default, price_real) = crate::tile::take_pricing_hits();
11981 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
11982 println!(
11983 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
11984 {screen_on}, pricer armings default={price_default} real={price_real}"
11985 );
11986 println!("| set | nz | blocks | priced bits | written bits | error |");
11987 println!("|---|---|---|---|---|---|");
11988 let (mut priced_all, mut written_all) = (0.0, 0.0);
11989 for ((set, bucket), (blocks, priced, written)) in &rows {
11990 priced_all += priced;
11991 written_all += written;
11992 println!(
11993 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
11994 crate::tile::census_bucket_label(*bucket),
11995 if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
11996 );
11997 }
11998 println!(
11999 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
12000 rows.values().map(|r| r.0).sum::<u64>(),
12001 (priced_all - written_all) / written_all * 100.0
12002 );
12003 assert!(written_all > 0.0, "{name}: the census saw no transform block");
12004 }
12005 }
12006
12007 /// Low motion has to actually buy something: at least one inter frame of
12008 /// a panning sequence has to cost fewer bytes than the key frame that
12009 /// starts it, and the inter-block share it prints has to be non-zero --
12010 /// a search that never picks an inter mode would still pass a rate gate
12011 /// on a picture with no motion in it (the class this repo calls
12012 /// gate-blind-to-feature), so the share is printed even though it is not
12013 /// asserted on beyond being reachable at all.
12014 #[test]
12015 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
12016 let fctx = &crate::decode::FrameCtx::new();
12017 let (width, height) = (256usize, 128usize);
12018 let pictures: Vec<Picture> = (0..5)
12019 .map(|i| panned_test_card(width, height, i * 2))
12020 .collect();
12021 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
12022
12023 let key_bytes = encoded.frames[0].stream.len();
12024 eprintln!("frame bytes inter share");
12025 for (i, frame) in encoded.frames.iter().enumerate() {
12026 eprintln!(
12027 "{i:5} {:5} {:11.2}",
12028 frame.stream.len(),
12029 frame.inter_block_share
12030 );
12031 }
12032 assert!(
12033 encoded.frames[1..]
12034 .iter()
12035 .any(|f| f.stream.len() < key_bytes),
12036 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
12037 );
12038 assert!(
12039 encoded.frames[1..]
12040 .iter()
12041 .any(|f| f.inter_block_share > 0.0),
12042 "no inter frame coded a single inter block -- the search never fired"
12043 );
12044 }
12045
12046 /// A manual perf probe, not a gate: prints where a key frame's and an
12047 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
12048 /// measures before it optimizes rather than guessing. Run with
12049 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
12050 #[test]
12051 #[ignore = "a perf probe, not a gate"]
12052 fn stage_timing_breakdown() {
12053 let fctx = &crate::decode::FrameCtx::new();
12054 use std::time::Instant;
12055
12056 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
12057 let picture = test_card(width, height);
12058
12059 let t = Instant::now();
12060 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
12061 let dc_only_t = t.elapsed();
12062
12063 let t = Instant::now();
12064 let non_directional =
12065 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
12066 let non_directional_t = t.elapsed();
12067
12068 let t = Instant::now();
12069 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
12070 let all_modes_t = t.elapsed();
12071
12072 eprintln!(
12073 "\n=== key frame {width}x{height} ===\n\
12074 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
12075 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
12076 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
12077 dc_only.stream.len(),
12078 non_directional.stream.len(),
12079 all_modes.stream.len(),
12080 );
12081
12082 // One inter frame predicting off the key frame's own
12083 // reconstruction, the (256, 256)-padded surface encode_sequence
12084 // itself would hand encode_inter_frame.
12085 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
12086 let padded_pic = picture.padded_to(SUPERBLOCK);
12087 let t = Instant::now();
12088 let inter =
12089 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();
12090 let inter_t = t.elapsed();
12091 eprintln!(
12092 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
12093 {:.2})",
12094 inter.stream.len(),
12095 inter.inter_block_share
12096 );
12097 }
12098
12099 // Isolated per-call cost of the trial pipeline's own stages, at both
12100 // transform sizes the search runs, averaged over enough calls to
12101 // rise above `Instant::now`'s own noise.
12102 for side in [16usize, 32] {
12103 const N: u32 = 20_000;
12104 let residual: Vec<i32> = (0..side * side)
12105 .map(|i| ((i * 37 % 61) as i32) - 30)
12106 .collect();
12107
12108 let t = Instant::now();
12109 let mut levels = Vec::new();
12110 for _ in 0..N {
12111 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
12112 }
12113 let forward_t = t.elapsed() / N;
12114
12115 let t = Instant::now();
12116 for _ in 0..N {
12117 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
12118 }
12119 let inverse_t = t.elapsed() / N;
12120
12121 let set = if side == 32 {
12122 crate::cdf_state::TxbSet::Luma32
12123 } else {
12124 crate::cdf_state::TxbSet::Luma16
12125 };
12126 let t = Instant::now();
12127 for _ in 0..N {
12128 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
12129 }
12130 let entropy_t = t.elapsed() / N;
12131
12132 let above = vec![128u8; side * 2];
12133 let left = vec![128u8; side * 2];
12134 let mut prediction = vec![0u8; side * side];
12135 let t = Instant::now();
12136 for _ in 0..N {
12137 intra_predict_u8(
12138 D45_PRED,
12139 0,
12140 Some(&above),
12141 Some(&left),
12142 Some(128),
12143 side,
12144 side,
12145 false,
12146 false,
12147 &mut prediction, fctx,
12148 );
12149 }
12150 let predict_t = t.elapsed() / N;
12151
12152 eprintln!(
12153 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
12154 predict (1 directional mode): {predict_t:>9.2?}\n\
12155 forward_and_quantize: {forward_t:>9.2?}\n\
12156 dequant_and_inverse: {inverse_t:>9.2?}\n\
12157 coeff_bits: {entropy_t:>9.2?}"
12158 );
12159 }
12160 }
12161
12162 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
12163 /// (motion search, [`crate::mc::predict`], transform+quantize,
12164 /// `coeff_bits`), plus what is left over once those are subtracted --
12165 /// the thirteen-mode intra-candidate loop `search_inter_block` still
12166 /// runs on every inter block (its own transform/quant/entropy calls are
12167 /// already inside buckets 2/3, so "left over" here is everything NOT
12168 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
12169 /// symbol-cost lookups outside `coeff_bits`).
12170 ///
12171 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
12172 #[test]
12173 #[ignore = "a perf probe, not a gate"]
12174 fn stage_timing_breakdown_inter() {
12175 let fctx = &crate::decode::FrameCtx::new();
12176 use std::time::Instant;
12177
12178 let (width, height) = (1280usize, 720);
12179 let picture = test_card(width, height);
12180 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
12181 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
12182 let padded_pic = picture.padded_to(SUPERBLOCK);
12183
12184 stage_reset();
12185 let t = Instant::now();
12186 let inter =
12187 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();
12188 let total_t = t.elapsed();
12189 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
12190 let accounted = motion_search + transform_quant + entropy;
12191 // motion_search already contains interpolation's own time (every
12192 // candidate the search costs calls crate::mc::predict), so it is not
12193 // added again here -- interpolation is reported alongside as "of
12194 // which interpolation", not as a fifth additive bucket.
12195 let other = total_t.saturating_sub(accounted);
12196
12197 eprintln!(
12198 "\n=== inter frame {width}x{height}, one frame ===\n\
12199 total: {total_t:>9.2?} ({} bytes)\n\
12200 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
12201 {interpolation:>9.2?})\n\
12202 transform + quantize: {transform_quant:>9.2?}\n\
12203 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
12204 everything else (13-mode intra {other:>9.2?}\n\
12205 candidate loop's own predict/bookkeeping, NEARESTMV's own \
12206 predict, RD glue):",
12207 inter.stream.len(),
12208 );
12209 }
12210
12211 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
12212 /// frames (a dark/flat one, a detailed one, a normal film one) at two
12213 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
12214 /// None`, the baseline this same build produces without
12215 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
12216 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
12217 /// go in the lane report, which is where "ship as default" is decided --
12218 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
12219 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
12220 #[test]
12221 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
12222 fn prune_k_quality_sweep() {
12223 let fctx = &crate::decode::FrameCtx::new();
12224 if !have_ffmpeg() {
12225 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
12226 return;
12227 }
12228 let (width, height) = (640usize, 352usize);
12229 let frames: &[(&str, &str, &str)] = &[
12230 // (label, clip, seek) -- a near-black scene, a busy one, and an
12231 // ordinary film frame, each from a different real file.
12232 (
12233 "dark/flat",
12234 "/home/user/Videos/reela.mp4",
12235 "3",
12236 ),
12237 (
12238 "detailed",
12239 "/home/user/Downloads/reelb.mkv",
12240 "1200",
12241 ),
12242 (
12243 "film",
12244 "/home/user/Videos/Films/reelc.mkv",
12245 "600",
12246 ),
12247 ];
12248 for &(label, clip, skip) in frames {
12249 if !std::path::Path::new(clip).exists() {
12250 eprintln!("SKIP {label}: {clip} not present on this machine");
12251 continue;
12252 }
12253 let picture = clip_frame(clip, skip, width, height);
12254 for &q in &[60u8, 150] {
12255 // SAFETY (not literally unsafe, just process-global): this is
12256 // a single-threaded #[ignore] probe, run by hand, never
12257 // alongside other tests that read Search::top_k.
12258 set_test_top_k_override(None);
12259 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
12260 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
12261 eprint!(
12262 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
12263 baseline.stream.len(),
12264 baseline_psnr
12265 );
12266 for &k in &[3usize, 4, 6] {
12267 set_test_top_k_override(Some(k));
12268 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
12269 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
12270 eprint!(
12271 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
12272 pruned.stream.len(),
12273 pruned_psnr,
12274 pruned_psnr - baseline_psnr
12275 );
12276 }
12277 eprintln!();
12278 }
12279 }
12280 set_test_top_k_override(None);
12281 }
12282
12283 /// Two consecutive decoded frames from one clip, for an inter-frame
12284 /// sweep -- [`clip_frame`] alone only ever gives one.
12285 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
12286 let out = Command::new("ffmpeg")
12287 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
12288 .args(["-vf", &format!("scale={width}:{height}")])
12289 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
12290 .output()
12291 .expect("ffmpeg failed to run");
12292 assert!(
12293 out.status.success(),
12294 "ffmpeg: {}",
12295 String::from_utf8_lossy(&out.stderr)
12296 );
12297 let (luma, chroma) = (width * height, width * height / 4);
12298 let frame_len = luma + 2 * chroma;
12299 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
12300 std::array::from_fn(|i| {
12301 let bytes = &out.stdout[i * frame_len..][..frame_len];
12302 Picture {
12303 width,
12304 height,
12305 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
12306 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
12307 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
12308 }
12309 })
12310 }
12311
12312 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
12313 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
12314 /// then one inter frame off it (`search_inter_block`'s own intra
12315 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
12316 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
12317 /// padding step complicates the comparison. Prints bytes and luma PSNR
12318 /// for the inter frame alone, unpruned vs each `K`.
12319 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
12320 #[test]
12321 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
12322 fn prune_k_quality_sweep_inter() {
12323 let fctx = &crate::decode::FrameCtx::new();
12324 if !have_ffmpeg() {
12325 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
12326 return;
12327 }
12328 let (width, height) = (1280usize, 704usize);
12329 let frames: &[(&str, &str, &str)] = &[
12330 (
12331 "dark/flat",
12332 "/home/user/Videos/reela.mp4",
12333 "3",
12334 ),
12335 (
12336 "detailed",
12337 "/home/user/Downloads/reelb.mkv",
12338 "1200",
12339 ),
12340 (
12341 "film",
12342 "/home/user/Videos/Films/reelc.mkv",
12343 "600",
12344 ),
12345 ];
12346 for &(label, clip, skip) in frames {
12347 if !std::path::Path::new(clip).exists() {
12348 eprintln!("SKIP {label}: {clip} not present on this machine");
12349 continue;
12350 }
12351 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
12352 for &q in &[60u8, 150] {
12353 // SAFETY (not literally unsafe, just process-global): a
12354 // single-threaded #[ignore] probe, run by hand, never
12355 // alongside other tests that read Search::top_k.
12356 set_test_top_k_override_inter(None);
12357 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
12358 let baseline = encode_inter_frame(
12359 &inter_source,
12360 &key.reconstruction,
12361 q,
12362 0.5,
12363 1,
12364 flat_order_hints(1, 0, false),
12365 (width, height), None, None, None, fctx, None, &[],
12366 )
12367 .unwrap();
12368 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
12369 eprint!(
12370 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
12371 baseline.stream.len(),
12372 baseline_psnr
12373 );
12374 for &k in &[3usize, 4, 6] {
12375 set_test_top_k_override_inter(Some(k));
12376 let pruned = encode_inter_frame(
12377 &inter_source,
12378 &key.reconstruction,
12379 q,
12380 0.5,
12381 1,
12382 flat_order_hints(1, 0, false),
12383 (width, height), None, None, None, fctx, None, &[],
12384 )
12385 .unwrap();
12386 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
12387 eprint!(
12388 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
12389 pruned.stream.len(),
12390 pruned_psnr,
12391 pruned_psnr - baseline_psnr
12392 );
12393 }
12394 eprintln!();
12395 }
12396 }
12397 set_test_top_k_override_inter(None);
12398 }
12399
12400 /// `frames` consecutive pictures out of a real clip, scaled to a whole
12401 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
12402 /// to an arbitrary count for the fixture regression gate below.
12403 fn clip_frames(
12404 clip: &str,
12405 skip: &str,
12406 width: usize,
12407 height: usize,
12408 frames: usize,
12409 ) -> Vec<Picture> {
12410 clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames)
12411 }
12412
12413 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
12414 /// for a native-resolution CROP instead of a downscale (the downscale is
12415 /// what destroys a screen capture's exact repeats -- class
12416 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
12417 fn clip_frames_vf(
12418 clip: &str,
12419 skip: &str,
12420 vf: &str,
12421 width: usize,
12422 height: usize,
12423 frames: usize,
12424 ) -> Vec<Picture> {
12425 let out = Command::new("ffmpeg")
12426 .args(["-v", "error", "-ss", skip, "-i", clip])
12427 .args(["-frames:v", &frames.to_string()])
12428 .args(["-vf", vf])
12429 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
12430 .output()
12431 .expect("ffmpeg failed to run");
12432 assert!(
12433 out.status.success(),
12434 "ffmpeg: {}",
12435 String::from_utf8_lossy(&out.stderr)
12436 );
12437 let (luma, chroma) = (width * height, width * height / 4);
12438 let frame_len = luma + 2 * chroma;
12439 assert_eq!(
12440 out.stdout.len(),
12441 frame_len * frames,
12442 "expected {frames} 4:2:0 frames"
12443 );
12444 (0..frames)
12445 .map(|i| {
12446 let bytes = &out.stdout[i * frame_len..][..frame_len];
12447 Picture {
12448 width,
12449 height,
12450 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
12451 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
12452 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
12453 }
12454 })
12455 .collect()
12456 }
12457
12458 /// The standing regression gate on real content: 12 frames of a real
12459 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
12460 /// this crate's own input regardless of its own source codec), encoded
12461 /// as an AV1 GOP and checked against three numeric floors so a
12462 /// compatibility or quality regression fails the suite instead of
12463 /// waiting for a downstream repo's gate to catch it (as happened for a
12464 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
12465 /// refusal, both caught only that way).
12466 ///
12467 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
12468 /// that geometry is already covered elsewhere), chosen only so encode
12469 /// time and gate numbers are not muddied by an edge-block class this
12470 /// test is not about.
12471 ///
12472 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
12473 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
12474 /// below carry a margin off those measured numbers (PSNR floor =
12475 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
12476 #[test]
12477 fn real_clip_encodes_within_its_quality_and_size_budget() {
12478 let fctx = &crate::decode::FrameCtx::new();
12479 if !have_ffmpeg() {
12480 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
12481 return;
12482 }
12483 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12484 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
12485 if !clip.exists() {
12486 eprintln!(
12487 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
12488 clip.display()
12489 );
12490 return;
12491 }
12492 let (width, height, frame_count) = (640usize, 384usize, 12usize);
12493 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
12494 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
12495 assert_eq!(encoded.frames.len(), frame_count);
12496
12497 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
12498 // stream and hands back every frame -- a stream a downstream
12499 // decoder refuses is the exact class of regression this gate
12500 // exists for.
12501 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
12502 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
12503
12504 // Gate 2: quality vs the source did not silently collapse.
12505 let mean_psnr: f64 = decoded
12506 .iter()
12507 .zip(&source)
12508 .map(|(d, s)| psnr(&d.y, &s.y))
12509 .sum::<f64>()
12510 / frame_count as f64;
12511 assert!(
12512 mean_psnr >= 44.91,
12513 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
12514 );
12515
12516 // Gate 3: the stream did not silently bloat.
12517 assert!(
12518 encoded.stream.len() <= 80_340,
12519 "stream grew to {} bytes, over the 80340-byte ceiling",
12520 encoded.stream.len()
12521 );
12522 }
12523
12524 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
12525 /// straddle size: 640x384 is exact on both axes (32-aligned), so
12526 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
12527 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
12528 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
12529 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
12530 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
12531 /// card; this one is the real-clip gate, same three floors.
12532 ///
12533 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
12534 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
12535 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
12536 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
12537 #[test]
12538 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
12539 let fctx = &crate::decode::FrameCtx::new();
12540 if !have_ffmpeg() {
12541 eprintln!(
12542 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
12543 no ffmpeg"
12544 );
12545 return;
12546 }
12547 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12548 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
12549 if !clip.exists() {
12550 eprintln!(
12551 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
12552 {} missing",
12553 clip.display()
12554 );
12555 return;
12556 }
12557 let (width, height, frame_count) = (704usize, 400usize, 8usize);
12558 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
12559 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
12560 assert_eq!(encoded.frames.len(), frame_count);
12561
12562 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
12563 // stream and hands back every frame.
12564 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
12565 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
12566
12567 // Gate 2: quality vs the source did not silently collapse.
12568 let mean_psnr: f64 = decoded
12569 .iter()
12570 .zip(&source)
12571 .map(|(d, s)| psnr(&d.y, &s.y))
12572 .sum::<f64>()
12573 / frame_count as f64;
12574 assert!(
12575 mean_psnr >= 44.98,
12576 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
12577 );
12578
12579 // Gate 3: the stream did not silently bloat.
12580 assert!(
12581 encoded.stream.len() <= 62_703,
12582 "stream grew to {} bytes, over the 62703-byte ceiling",
12583 encoded.stream.len()
12584 );
12585 }
12586
12587 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
12588 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
12589 /// facade -- timed end to end, so the edith export-time projection is a
12590 /// real number rather than a guess from the isolated key/inter numbers
12591 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
12592 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
12593 #[test]
12594 #[ignore = "a perf probe, not a gate"]
12595 fn sequence_bench_sanity() {
12596 let fctx = &crate::decode::FrameCtx::new();
12597 use std::time::Instant;
12598 let (width, height) = (1280usize, 720usize);
12599 let pictures: Vec<Picture> = (0..24)
12600 .map(|i| panned_test_card(width, height, i * 3))
12601 .collect();
12602 let t = Instant::now();
12603 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
12604 let elapsed = t.elapsed();
12605 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
12606 eprintln!(
12607 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
12608 elapsed / 24
12609 );
12610 }
12611
12612 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
12613 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
12614 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
12615 /// -- --ignored --nocapture`.
12616 #[test]
12617 #[ignore = "a calibration probe, not a gate"]
12618 fn calibration_sweep_base_q_idx() {
12619 let fctx = &crate::decode::FrameCtx::new();
12620 if !have_ffmpeg() {
12621 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
12622 return;
12623 }
12624 let (width, height, frames) = (640usize, 384usize, 12usize);
12625 for clip in [
12626 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
12627 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
12628 ] {
12629 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12630 .join("../../fixtures/video")
12631 .join(clip);
12632 if !path.exists() {
12633 eprintln!("SKIP {clip}: fixture missing");
12634 continue;
12635 }
12636 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
12637 eprintln!("--- {clip} ---");
12638 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
12639 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
12640 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
12641 let mean_psnr: f64 = decoded
12642 .iter()
12643 .zip(&source)
12644 .map(|(d, s)| psnr(&d.y, &s.y))
12645 .sum::<f64>()
12646 / frames as f64;
12647 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
12648 eprintln!(
12649 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
12650 encoded.stream.len()
12651 );
12652 }
12653 }
12654 }
12655
12656 // -----------------------------------------------------------------------
12657 // The encoder's standing BD-rate baseline against libaom and rav1e.
12658 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
12659 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
12660 // agreeing with our encoder proves nothing about the bitstream.
12661 // -----------------------------------------------------------------------
12662
12663 /// All-plane PSNR of a decoded picture against its source, on the same
12664 /// 8-bit scale [`psnr`] uses.
12665 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
12666 let cat = |p: &Picture| {
12667 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
12668 v.extend_from_slice(&p.y);
12669 v.extend_from_slice(&p.u);
12670 v.extend_from_slice(&p.v);
12671 v
12672 };
12673 psnr(&cat(decoded), &cat(source))
12674 }
12675
12676 /// The pictures back as the planar 8-bit bytes an encoder reads.
12677 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
12678 let mut raw = Vec::new();
12679 for p in source {
12680 for plane in [&p.y, &p.u, &p.v] {
12681 raw.extend(plane.iter().map(|&s| s as u8));
12682 }
12683 }
12684 raw
12685 }
12686
12687 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
12688 /// through ffmpeg: one point per entry of `points`, each a quality flag
12689 /// set. Returns the ladder ordered by fidelity and the total encode wall
12690 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
12691 /// so both curves are measured by the same decoder.
12692 fn external_ladder(
12693 source: &[Picture],
12694 width: usize,
12695 height: usize,
12696 encoder: &str,
12697 points: &[Vec<String>],
12698 ) -> (Vec<(f64, f64)>, f64) {
12699 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
12700 let dir = std::env::temp_dir();
12701 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
12702 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
12703 let mut ladder = Vec::new();
12704 let mut wall = 0.0;
12705 for (i, params) in points.iter().enumerate() {
12706 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
12707 let start = std::time::Instant::now();
12708 let out = Command::new("ffmpeg")
12709 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
12710 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
12711 .arg(&raw_path)
12712 .args(["-an", "-threads", "1"])
12713 .args(["-g", &source.len().to_string(), "-c:v", encoder])
12714 .args(params)
12715 .args(["-f", "obu"])
12716 .arg(&obu)
12717 .output()
12718 .expect("ffmpeg failed to run");
12719 wall += start.elapsed().as_secs_f64();
12720 assert!(
12721 out.status.success(),
12722 "{encoder} {params:?}: {}",
12723 String::from_utf8_lossy(&out.stderr)
12724 );
12725 let stream = std::fs::read(&obu).expect("reference stream");
12726 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
12727 let mean: f64 = decoded
12728 .iter()
12729 .zip(source)
12730 .map(|(d, s)| psnr_all(d, s))
12731 .sum::<f64>()
12732 / source.len() as f64;
12733 ladder.push((mean, (stream.len() as f64).log10()));
12734 let _ = std::fs::remove_file(&obu);
12735 }
12736 let _ = std::fs::remove_file(&raw_path);
12737 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
12738 (ladder, wall)
12739 }
12740
12741 /// First differing sample between two pictures, as
12742 /// `(plane, index, left, right)` -- so a gate failure names the plane and
12743 /// the sample instead of just "differs". A length difference counts as a
12744 /// mismatch of that plane at the first index past the shorter one.
12745 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
12746 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
12747 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
12748 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
12749 }
12750 if l.len() != r.len() {
12751 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
12752 }
12753 }
12754 None
12755 }
12756
12757 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
12758 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
12759 /// stream is decoded twice -- by ffmpeg and by our own
12760 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
12761 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
12762 /// in Y, U and V over every shown frame in display order. That is itself
12763 /// a gate: it proves the bitstream says what the encoder thinks, in the
12764 /// only two decoders that read it.
12765 fn our_ladder(
12766 name: &str,
12767 source: &[Picture],
12768 width: usize,
12769 height: usize,
12770 fctx: &crate::decode::FrameCtx,
12771 ) -> (Vec<(f64, f64)>, f64) {
12772 let mut ladder = Vec::new();
12773 let mut wall = 0.0;
12774 for &q in &[150u8, 120, 90, 60] {
12775 let start = std::time::Instant::now();
12776 let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap();
12777 wall += start.elapsed().as_secs_f64();
12778 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
12779 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
12780 assert_eq!(
12781 ours.len(),
12782 source.len(),
12783 "{name} q={q}: our decoder's display-order frame count"
12784 );
12785 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
12786 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
12787 panic!(
12788 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
12789 {got}, the encoder reconstructed {want}"
12790 );
12791 }
12792 }
12793 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
12794 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
12795 panic!(
12796 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
12797 {got}, the encoder reconstructed {want}"
12798 );
12799 }
12800 }
12801 let mean: f64 = decoded
12802 .iter()
12803 .zip(source)
12804 .map(|(d, s)| psnr_all(d, s))
12805 .sum::<f64>()
12806 / source.len() as f64;
12807 ladder.push((mean, (encoded.stream.len() as f64).log10()));
12808 }
12809 // What this clip asked for and what the content gate left it coding
12810 // under: a screen clip requests a pyramid and codes flat, and that
12811 // difference is what keeps its row identical to the flat baseline
12812 // (class `gate-blind-to-feature`).
12813 eprintln!(
12814 "{name}: sequence, pyramid requested {:?} effective {:?}",
12815 crate::encoder::Pyramid::from_env(),
12816 last_sequence_pyramid(),
12817 );
12818 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
12819 (ladder, wall)
12820 }
12821
12822 /// [`our_ladder`] through the streaming facade — the surface the editor's
12823 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
12824 /// each stream is also reordered (hidden `ALTREF` first,
12825 /// `show_existing_frame` last per group) and each level is coded at its
12826 /// own quantizer offset; without one it is the flat ladder, which
12827 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
12828 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
12829 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
12830 /// the whole ladder how many frames and how many bytes it spent, and the
12831 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
12832 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
12833 /// flat path, so a requested pyramid can come back `None` here.
12834 fn our_ladder_facade(
12835 name: &str,
12836 source: &[Picture],
12837 width: usize,
12838 height: usize,
12839 pyramid: Option<crate::encoder::Pyramid>,
12840 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) {
12841 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
12842 let slot = |l: Level| match l {
12843 Level::Key => 0,
12844 Level::Arf => 1,
12845 Level::Leaf => 2,
12846 Level::ShowExisting => 3,
12847 };
12848 let mut ladder = Vec::new();
12849 let mut wall = 0.0;
12850 let mut effective = None;
12851 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
12852 for &q in &[150u8, 120, 90, 60] {
12853 let config = EncoderConfig {
12854 width,
12855 height,
12856 base_q_idx: q,
12857 gop: source.len(),
12858 colour: Colour::Unspecified,
12859 tile_cols_log2: 0,
12860 tile_rows_log2: 0,
12861 };
12862 let start = std::time::Instant::now();
12863 let mut enc = match pyramid {
12864 None => Av1Encoder::new(config).unwrap(),
12865 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
12866 };
12867 let mut packets = Vec::new();
12868 for picture in source {
12869 packets.extend(enc.encode_frames(picture).unwrap());
12870 }
12871 packets.extend(enc.flush().unwrap());
12872 wall += start.elapsed().as_secs_f64();
12873 effective = enc.pyramid();
12874 let mut stream = Vec::new();
12875 for p in &packets {
12876 counts[slot(p.level)] += 1;
12877 bytes[slot(p.level)] += p.data.len();
12878 stream.extend_from_slice(&p.data);
12879 }
12880 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
12881 // correct if the DISPLAY-order output still has one frame per
12882 // source picture, in the right order -- checked against our own
12883 // decoder as well as ffmpeg's, both below.
12884 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
12885 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
12886 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
12887 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
12888 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
12889 panic!(
12890 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
12891 decoded {got}, our decoder decoded {want}"
12892 );
12893 }
12894 }
12895 let mean: f64 = decoded
12896 .iter()
12897 .zip(source)
12898 .map(|(d, s)| psnr_all(d, s))
12899 .sum::<f64>()
12900 / source.len() as f64;
12901 ladder.push((mean, (stream.len() as f64).log10()));
12902 }
12903 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
12904 (ladder, wall, counts, bytes, effective)
12905 }
12906
12907 /// Byte-exactness gate for encoder work that is meant to change only
12908 /// how long the encoder takes.
12909 ///
12910 /// The BD gate above measures quality, which a speed lane can move by a
12911 /// hair without failing anything; this pins the streams themselves.
12912 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
12913 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
12914 /// in the tile) and again on lane-av1mv's merge of it: an extra
12915 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
12916 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
12917 /// prices coefficients against the tables the frame's writer really
12918 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
12919 /// decision change the BD gate judges. Re-pinned again on
12920 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
12921 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
12922 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
12923 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
12924 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
12925 /// by default ([`warp_on`], a sequence/frame header bit and a new
12926 /// motion_mode symbol on eligible blocks) and
12927 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
12928 /// every inter frame's superblocks now code at their own lambda
12929 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
12930 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
12931 /// and the two var-tx depth searches ([`tx32_depth_search`],
12932 /// [`compound_var_tx`]) are on by default, all three re-judged on the
12933 /// native gate's real film rows.
12934 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
12935 /// every block whose chroma takes it codes a different mode symbol, two
12936 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
12937 /// restores the previous streams. Re-pinned again in the same lane once
12938 /// directional luma winners searched their `angle_delta_y`
12939 /// (`EC_AV1_ANGLE=0` restores that half).
12940 #[test]
12941 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
12942 if !have_ffmpeg() {
12943 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
12944 return;
12945 }
12946 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12947 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
12948 if !clip.exists() {
12949 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
12950 return;
12951 }
12952 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
12953 // FNV-1a over the stream: a witness that every coded bit is where it
12954 // was, which a byte count alone is not.
12955 let fnv = |b: &[u8]| {
12956 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
12957 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
12958 })
12959 };
12960 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
12961 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
12962 // of 4, its leaves at q+8 and a `show_existing_frame` header per
12963 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
12964 // four frames; four pictures is one short mini-GOP, which is the
12965 // shape that pays least (the ARF's own quality has no later group to
12966 // carry it), so this is not the BD gate's number.
12967 // Re-taken again on lane-av1cfl: the chroma search offers
12968 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
12969 // so every block taking either codes different syntax and different
12970 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
12971 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
12972 let pins: [(u8, usize, u64); 2] =
12973 [(150, 7321, 0x34e2_e4e0_d7c5_09f3), (60, 27285, 0xbfd2_41af_dcac_a0c6)];
12974 for (q, bytes, hash) in pins {
12975 let encoded = encode_sequence(&source, q, 0.5).unwrap();
12976 assert_eq!(
12977 (encoded.stream.len(), fnv(&encoded.stream)),
12978 (bytes, hash),
12979 "q={q}: the encoder's stream moved"
12980 );
12981 }
12982 }
12983
12984 /// A ladder is only a ladder if both axes rise together.
12985 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
12986 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
12987 for w in ladder.windows(2) {
12988 assert!(
12989 w[1].0 > w[0].0 && w[1].1 > w[0].1,
12990 "{name}: not monotone, {ladder:?}"
12991 );
12992 }
12993 }
12994
12995 /// The sweep behind [`screen_content`]'s constants
12996 /// (`unswept-decision-constants`), on the SAME five clips
12997 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
12998 /// same native crop: for each colour bound N the share of 16x16 luma
12999 /// blocks with 2..=N distinct colours, and the share of those whose
13000 /// per-pixel variance also clears a floor V -- libaom's
13001 /// `av1_set_screen_content_options` counts the variance-cleared blocks
13002 /// too (its `counts_2`, which gates intrabc), and without that term a
13003 /// smooth dark film frame reads as screen content.
13004 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
13005 #[test]
13006 #[ignore = "reads the real library"]
13007 fn probe_screen_detect() {
13008 if !have_ffmpeg() {
13009 eprintln!("SKIP probe_screen_detect: no ffmpeg");
13010 return;
13011 }
13012 let limits = [4usize, 8, 16, 32, 64, 128];
13013 let floors = [0u64, 4, 16, 64, 256];
13014 // The census of one clip at one size: mean share, over the frames, of
13015 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
13016 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
13017 let mut acc = [[0f64; 5]; 6];
13018 for picture in frames {
13019 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
13020 let mut hit = [[0usize; 5]; 6];
13021 let mut blocks = 0usize;
13022 for by in (0..ch).step_by(16) {
13023 for bx in (0..cw).step_by(16) {
13024 let mut seen = [false; 256];
13025 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
13026 for row in 0..16 {
13027 for col in 0..16 {
13028 let v = y[(by + row) * cw + bx + col];
13029 sum += u64::from(v);
13030 sq += u64::from(v) * u64::from(v);
13031 if !seen[usize::from(v)] {
13032 seen[usize::from(v)] = true;
13033 colors += 1;
13034 }
13035 }
13036 }
13037 let var = (sq - sum * sum / 256) / 256;
13038 blocks += 1;
13039 for (li, &limit) in limits.iter().enumerate() {
13040 if colors > 1 && colors <= limit {
13041 for (fi, &floor) in floors.iter().enumerate() {
13042 hit[li][fi] += usize::from(var > floor);
13043 }
13044 }
13045 }
13046 }
13047 }
13048 for li in 0..6 {
13049 for fi in 0..5 {
13050 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
13051 }
13052 }
13053 }
13054 let n = frames.len().max(1) as f64;
13055 eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len());
13056 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>());
13057 for (li, &limit) in limits.iter().enumerate() {
13058 eprintln!(
13059 " {limit:>5} |{}",
13060 (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>()
13061 );
13062 }
13063 };
13064 for (name, path, seek) in native_gate_clips() {
13065 let Some((nw, nh)) = probe_dims(&path) else {
13066 eprintln!("SKIP {name}: ffprobe gave no size");
13067 continue;
13068 };
13069 let cw = nw.min(1920) / 128 * 128;
13070 let ch = nh.min(1024) / 128 * 128;
13071 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
13072 let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12);
13073 census(&name, &frames, cw, ch);
13074 // The 640x384 gate scales instead of cropping, and the scaling
13075 // changes the census (bars smooth out): the constants have to
13076 // separate at BOTH sizes.
13077 let small = clip_frames(&path, &seek, 640, 384, 12);
13078 census(&name, &small, 640, 384);
13079 }
13080 }
13081
13082 /// The detector against the WHOLE real library (class
13083 /// `unswept-decision-constants`, user rule "his data is the gate"):
13084 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
13085 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
13086 /// duration, four frames each, 8-bit 4:2:0, at native size or a
13087 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
13088 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
13089 /// Prints per file and offset the share of qualifying 16x16 blocks, the
13090 /// [`screen_content`] verdict and a content hint (mean luma, luma
13091 /// standard deviation, inter MAD), then sweeps the colour bound against
13092 /// the variance floor over the whole library: for each (N, V) the worst
13093 /// (highest) share among the camera/film rows against the best (lowest)
13094 /// among the screen-recording rows, so the rule with the widest gap can
13095 /// be read off. Rows carry the manifest index, codec and size only --
13096 /// no titles, no home paths.
13097 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
13098 #[test]
13099 #[ignore = "reads the real library"]
13100 fn probe_screen_library() {
13101 if !have_ffmpeg() {
13102 eprintln!("SKIP probe_screen_library: no ffmpeg");
13103 return;
13104 }
13105 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
13106 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
13107 eprintln!("SKIP probe_screen_library: no real-library manifest");
13108 return;
13109 };
13110 let limits = [4usize, 8, 16, 32, 64];
13111 let floors = [0u64, 4, 8, 16, 32, 64, 128];
13112 // Whatever ffmpeg gave us, without the exact-count assertion the
13113 // gate loaders make: a seek near the end of a clip returns fewer
13114 // frames, and that is a row to print, not a panic.
13115 let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
13116 let out = Command::new("ffmpeg")
13117 .args(["-v", "error", "-ss", seek, "-i", clip])
13118 .args(["-frames:v", &n.to_string()])
13119 .args(["-vf", vf])
13120 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
13121 .output();
13122 let Ok(out) = out else { return Vec::new() };
13123 if !out.status.success() {
13124 return Vec::new();
13125 }
13126 let (luma, chroma) = (w * h, w * h / 4);
13127 let frame_len = luma + 2 * chroma;
13128 (0..out.stdout.len() / frame_len)
13129 .map(|i| {
13130 let b = &out.stdout[i * frame_len..][..frame_len];
13131 Picture {
13132 width: w,
13133 height: h,
13134 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
13135 u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
13136 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
13137 }
13138 })
13139 .collect()
13140 };
13141 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
13142 // variance > V, for every (N, V) of the sweep grid, over one frame.
13143 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
13144 let mut hit = [[0usize; 7]; 5];
13145 let mut blocks = 0usize;
13146 for by in (0..h).step_by(16) {
13147 for bx in (0..w).step_by(16) {
13148 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
13149 let mut seen = [false; 256];
13150 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
13151 for row in 0..bh {
13152 for col in 0..bw {
13153 let v = y[(by + row) * w + bx + col];
13154 sum += u64::from(v);
13155 sq += u64::from(v) * u64::from(v);
13156 if !seen[usize::from(v)] {
13157 seen[usize::from(v)] = true;
13158 colors += 1;
13159 }
13160 }
13161 }
13162 let n = (bh * bw) as u64;
13163 let var = (sq - sum * sum / n) / n;
13164 blocks += 1;
13165 for (li, &limit) in limits.iter().enumerate() {
13166 if colors > 1 && colors <= limit {
13167 for (fi, &floor) in floors.iter().enumerate() {
13168 hit[li][fi] += usize::from(var > floor);
13169 }
13170 }
13171 }
13172 }
13173 }
13174 let mut out = [[0f64; 7]; 5];
13175 for li in 0..5 {
13176 for fi in 0..7 {
13177 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
13178 }
13179 }
13180 out
13181 };
13182 // (index, label, path, duration, screen-by-its-own-content). The
13183 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
13184 // are desktop recordings; everything else in this library is camera
13185 // or film material.
13186 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
13187 for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] {
13188 let path = fixtures.join("video").join(file);
13189 if path.exists() {
13190 rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false));
13191 }
13192 }
13193 for (i, line) in manifest.lines().skip(1).enumerate() {
13194 let f: Vec<&str> = line.split('\t').collect();
13195 if f.len() < 10 {
13196 continue;
13197 }
13198 let (path, codec) = (f[0], f[2]);
13199 if codec == "-" || codec.is_empty() {
13200 continue;
13201 }
13202 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
13203 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
13204 continue;
13205 };
13206 if !std::path::Path::new(path).exists() {
13207 eprintln!("SKIP {}: file is gone", i + 1);
13208 continue;
13209 }
13210 let name = path.rsplit('/').next().unwrap_or(path);
13211 let is_capture = path.contains("/OBS/")
13212 || (name.len() > 19
13213 && name.as_bytes()[4] == b'-'
13214 && name.as_bytes()[7] == b'-'
13215 && name.as_bytes()[10] == b' '
13216 && name.as_bytes()[13] == b'-');
13217 rows.push((
13218 format!("{}", i + 1),
13219 format!("{codec} {w}x{h}"),
13220 path.to_string(),
13221 f[8].parse::<f64>().unwrap_or(0.0),
13222 is_capture,
13223 ));
13224 }
13225 // Per (N, V): the worst camera/film row and the best screen row, so
13226 // the separation of the whole library is one subtraction.
13227 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
13228 eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |");
13229 for (idx, label, path, dur, is_capture) in &rows {
13230 let Some((nw, nh)) = probe_dims(path) else {
13231 eprintln!("SKIP {idx}: ffprobe gave no size");
13232 continue;
13233 };
13234 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
13235 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
13236 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
13237 let mut file_grid = [[0f64; 7]; 5];
13238 let mut file_frames = 0usize;
13239 for pct in [10u32, 50, 90] {
13240 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
13241 let frames = decode(path, &seek, &vf, cw, ch, 4);
13242 if frames.is_empty() {
13243 eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" });
13244 continue;
13245 }
13246 let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64);
13247 let mut prev: Option<Vec<u8>> = None;
13248 for picture in &frames {
13249 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
13250 let grid = census(&y, cw, ch);
13251 for li in 0..5 {
13252 for fi in 0..7 {
13253 file_grid[li][fi] += grid[li][fi];
13254 }
13255 }
13256 file_frames += 1;
13257 // The shipped rule is (16 colours, var > 16): grid row 2,
13258 // floor 16 is column 3.
13259 share += grid[2][3];
13260 yes += usize::from(screen_content(&y, cw, cw, ch));
13261 let n = y.len() as f64;
13262 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
13263 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
13264 mean += sum / n;
13265 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
13266 if let Some(p) = &prev {
13267 mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n;
13268 }
13269 prev = Some(y);
13270 }
13271 let f = frames.len() as f64;
13272 eprintln!(
13273 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
13274 if *is_capture { "screen" } else { "camera" },
13275 share / f,
13276 if yes * 2 > frames.len() { "SCREEN" } else { "camera" },
13277 frames.len(),
13278 mean / f,
13279 sd / f,
13280 mad / (f - 1.0).max(1.0),
13281 );
13282 }
13283 if file_frames == 0 {
13284 continue;
13285 }
13286 for li in 0..5 {
13287 for fi in 0..7 {
13288 let s = file_grid[li][fi] / file_frames as f64;
13289 match is_capture {
13290 true => scr_min[li][fi] = scr_min[li][fi].min(s),
13291 false => cam_max[li][fi] = cam_max[li][fi].max(s),
13292 }
13293 }
13294 }
13295 }
13296 eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):");
13297 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>());
13298 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
13299 for (li, &limit) in limits.iter().enumerate() {
13300 let mut row = String::new();
13301 for fi in 0..7 {
13302 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
13303 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
13304 if s - c > best {
13305 best = s - c;
13306 best_rule = (limit, floors[fi]);
13307 }
13308 }
13309 eprintln!(" {limit:>5} |{row}");
13310 }
13311 // The threshold sits at the midpoint of the widest gap; the shipped
13312 // constant is its reciprocal in whole parts of the frame.
13313 let (li, fi) = (
13314 limits.iter().position(|&l| l == best_rule.0).unwrap(),
13315 floors.iter().position(|&f| f == best_rule.1).unwrap(),
13316 );
13317 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
13318 eprintln!(
13319 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
13320 best_rule.0,
13321 best_rule.1,
13322 best,
13323 cam_max[li][fi],
13324 scr_min[li][fi],
13325 mid,
13326 (100.0 / mid.max(0.1)).round() as usize,
13327 );
13328 }
13329
13330 /// The missing instrument: what this encoder costs against libaom and
13331 /// rav1e at matched fidelity, and how long it takes to get there.
13332 ///
13333 /// Recipe, identical on all three sides: 12 consecutive frames of each
13334 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
13335 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
13336 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
13337 /// it by default), 4:2:0 8-bit in and out. Reference points:
13338 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
13339 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
13340 /// tile_cols=1:tile_rows=1:threads=1`
13341 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
13342 /// ffmpeg-decoded frames of each encoder's own stream.
13343 ///
13344 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
13345 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
13346 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
13347 /// four encodes of that ladder together):
13348 ///
13349 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
13350 /// |---|---|---|---|---|
13351 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
13352 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
13353 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
13354 ///
13355 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
13356 /// the encoder takes -- every stream it writes is byte-identical, so the
13357 /// BD columns are this box's own re-run of the same recipe rather than a
13358 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
13359 /// rav1e). What moved is the wall of the four encodes:
13360 ///
13361 /// | clip | wall ours before | after | instructions:u before -> after |
13362 /// |---|---|---|---|
13363 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
13364 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
13365 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
13366 ///
13367 /// Three exact steps, none of which touches a coded bit: the coefficient
13368 /// rate pricer stopped rebuilding every CDF table per candidate
13369 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
13370 /// tile once per candidate (`decode::FilterReplay`), and the forward
13371 /// transform stopped transforming the all-zero residual that 70% of its
13372 /// calls carry.
13373 ///
13374 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
13375 ///
13376 /// | step | 1080p | 2160p | screen |
13377 /// |---|---|---|---|
13378 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
13379 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
13380 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
13381 ///
13382 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
13383 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
13384 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
13385 /// -- all three decided on the REAL film rows of
13386 /// [`bd_rate_screen_native`], which this downscaled recipe does not
13387 /// carry:
13388 ///
13389 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
13390 /// |---|---|---|---|
13391 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
13392 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
13393 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
13394 ///
13395 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
13396 /// DEFAULT of the sequence path this gate codes through -- the bars are
13397 /// non-screen so they take it, the capture is gated flat:
13398 ///
13399 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
13400 /// |---|---|---|---|---|
13401 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
13402 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
13403 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
13404 ///
13405 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
13406 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
13407 /// facade arm -- which is what "one mini-GOP driver, two entry points"
13408 /// means here. This downscaled recipe HATES the pyramid (as it hates
13409 /// every knob the real film rows of `bd_rate_screen_native` keep, which
13410 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
13411 /// above. The capture's row is the flat row to the byte in both runs --
13412 /// that equality IS the content gate.
13413 ///
13414 /// Loop restoration is NOT in yet: it is the one filter whose parameters
13415 /// are per restoration UNIT inside the tile payload, so it needs both
13416 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
13417 /// buffer to solve against -- neither of which this frame-header-level
13418 /// search reaches.
13419 ///
13420 /// The baseline it replaced, before an inter frame's blocks chose their
13421 /// own partition, was +501.4/+504.4/+440.9 against libaom and
13422 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
13423 ///
13424 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
13425 /// fidelity, while spending far more time than either (the partition
13426 /// search's own cost, uncut: see the two intra-pruning variants measured
13427 /// and rejected in the lane report). No
13428 /// threshold is asserted yet -- this run sets the baseline; the gate
13429 /// asserts four monotone points per ladder, and at EVERY ladder point of
13430 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
13431 /// `crate::stream::decode_stream` -- and asserts the encoder's
13432 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
13433 /// and V over every shown frame in display order. A failure names the
13434 /// clip, the q, the frame, the plane and the first differing sample.
13435 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
13436 /// which exposes no per-packet reconstruction, so that path asserts the
13437 /// two decoders against each other on all three planes.)
13438 ///
13439 /// Run:
13440 /// cargo test -p ec-av1 --release --lib -- --ignored \
13441 /// bd_rate_vs_libaom_and_rav1e --nocapture
13442 #[test]
13443 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
13444 fn bd_rate_vs_libaom_and_rav1e() {
13445 if !have_ffmpeg() {
13446 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
13447 return;
13448 }
13449 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
13450 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
13451 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
13452 // rows for real content (the real rows live in the native gate).
13453 for (label, name) in [
13454 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
13455 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
13456 ] {
13457 let path = fixtures.join("video").join(name);
13458 if path.exists() {
13459 clips.push((label.to_string(), path));
13460 } else {
13461 eprintln!("SKIP clip {name}: missing");
13462 }
13463 }
13464 // Screen capture: the repo carries no screen-capture fixture, so take
13465 // the first OBS recording the real-library manifest names.
13466 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
13467 Ok(manifest) => {
13468 let screen = manifest
13469 .lines()
13470 .skip(1)
13471 .filter_map(|l| l.split('\t').next())
13472 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
13473 match screen {
13474 Some(p) => clips.push((
13475 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
13476 std::path::PathBuf::from(p),
13477 )),
13478 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
13479 }
13480 }
13481 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
13482 }
13483 assert!(!clips.is_empty(), "no source clip available");
13484
13485 let (width, height, frames) = (640usize, 384usize, 12usize);
13486 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
13487 .iter()
13488 .map(|q| {
13489 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
13490 .map(String::from)
13491 .to_vec()
13492 })
13493 .collect();
13494 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
13495 .iter()
13496 .map(|q| {
13497 vec![
13498 "-rav1e-params".to_string(),
13499 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
13500 ]
13501 })
13502 .collect();
13503 println!(
13504 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
13505 );
13506 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
13507 println!("|---|---|---|---|---|");
13508 for (name, path) in &clips {
13509 let fctx = &crate::decode::FrameCtx::new();
13510 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
13511 let _ = take_partition_hits();
13512 let _ = crate::tile::take_palette_hits();
13513 SCREEN_FRAMES.iter().for_each(|c| {
13514 c.store(0, std::sync::atomic::Ordering::Relaxed);
13515 });
13516 let _ = take_uv_mode_hits();
13517 let _ = crate::tile::take_inter_mode_hits();
13518 let _ = crate::tile::take_drl_hits();
13519 let _ = crate::tile::take_ref_hits();
13520 let _ = crate::tile::take_compound_mode_hits();
13521 let _ = crate::tile::take_compound_pair_hits();
13522 let _ = crate::tile::take_compound_size_hits();
13523 let _ = crate::tile::take_compound_leaf_mode_hits();
13524 let _ = crate::motion::take_census();
13525 // The entry-surface arm: run the SAME ladder through the
13526 // streaming facade the editor's export calls, which must print
13527 // the same BD numbers as the sequence path -- byte for byte the
13528 // same stream now that both drive one mini-GOP driver
13529 // (lane-av1pyrdef).
13530 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
13531 let (ours, ours_wall) = match facade {
13532 false => our_ladder(name, &source, width, height, fctx),
13533 true => {
13534 let pyramid = crate::encoder::Pyramid::from_env();
13535 let (ladder, wall, counts, bytes, effective) =
13536 our_ladder_facade(name, &source, width, height, pyramid);
13537 eprintln!(
13538 "{name}: facade, pyramid requested {pyramid:?} effective \
13539 {effective:?} -- frames key {} arf {} leaf {} \
13540 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
13541 counts[0], counts[1], counts[2], counts[3],
13542 bytes[0], bytes[1], bytes[2], bytes[3],
13543 );
13544 (ladder, wall)
13545 }
13546 };
13547 // How often the inter split actually fired over this clip's four
13548 // encodes, against the whole 32x32 that was the only outcome
13549 // before (gate-blind-to-feature).
13550 let [whole32, split32, whole16, split16] = take_partition_hits();
13551 // Which inter modes actually fired over this clip's four encodes,
13552 // and at which DRL index -- a mode nobody picks is a mode the BD
13553 // number cannot be crediting (gate-blind-to-feature).
13554 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
13555 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
13556 let refs = crate::tile::take_ref_hits();
13557 let modes_total = (nearest + near + global + new).max(1);
13558 eprintln!(
13559 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
13560 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
13561 {drl0}/{drl1}/{drl2}/{drl3}",
13562 100.0 * nearest as f64 / modes_total as f64,
13563 100.0 * near as f64 / modes_total as f64,
13564 100.0 * global as f64 / modes_total as f64,
13565 100.0 * new as f64 / modes_total as f64,
13566 );
13567 // The compound census: what share of the coded inter blocks took
13568 // a compound reference at all, which compound mode they took, and
13569 // which pair (gate-blind-to-feature -- a compound mode nobody
13570 // picks cannot be what a BD number credits).
13571 let comp_modes = crate::tile::take_compound_mode_hits();
13572 let comp_pairs = crate::tile::take_compound_pair_hits();
13573 let comp_sizes = crate::tile::take_compound_size_hits();
13574 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
13575 let comp_total: usize = comp_modes.iter().sum();
13576 eprintln!(
13577 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
13578 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
13579 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
13580 modes_total + comp_total,
13581 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
13582 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
13583 comp_modes[6], comp_modes[7],
13584 comp_pairs[3], comp_pairs[6],
13585 );
13586 eprintln!(
13587 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
13588 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
13589 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6],
13590 comp_leaf[7],
13591 );
13592 eprintln!(
13593 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
13594 comp_sizes[1], comp_sizes[2], comp_sizes[3],
13595 );
13596 // Where the wall-owning stage actually goes: how many candidate
13597 // evaluations (one `mc::predict` + SAD each) a search spends, how
13598 // many of them are subpel, and how often the winner is the seed
13599 // it started from -- the census the seeded search is judged by.
13600 let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census();
13601 let per = |n: u64| n as f64 / calls.max(1) as f64;
13602 eprintln!(
13603 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
13604 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
13605 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
13606 per(evals),
13607 100.0 * subpel as f64 / evals.max(1) as f64,
13608 per(rounds),
13609 100.0 * near_pred as f64 / calls.max(1) as f64,
13610 100.0 * unmoved as f64 / calls.max(1) as f64,
13611 );
13612 eprintln!(
13613 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
13614 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
13615 );
13616 eprintln!(
13617 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
13618 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
13619 whole32 + split32,
13620 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
13621 whole16 + split16,
13622 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
13623 );
13624 // The deblocking level each of this clip's frames chose
13625 // (lane-av1filt): 0 everywhere would mean the filter never fires.
13626 let levels = crate::filter_search::take_chosen_levels();
13627 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
13628 let mean = |f: fn(&Chosen) -> u8| {
13629 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
13630 };
13631 eprintln!(
13632 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
13633 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
13634 levels.len(),
13635 mean(|l| l.0.0),
13636 mean(|l| l.0.1),
13637 mean(|l| l.1.0),
13638 mean(|l| l.1.1),
13639 mean(|l| l.2.0),
13640 mean(|l| l.2.1),
13641 );
13642 // How many strength presets each frame's CDEF list carried and
13643 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
13644 // everywhere would mean the per-unit choice never fires.
13645 let presets = crate::filter_search::take_cdef_presets();
13646 let mut by_bits = [0usize; 4];
13647 for (b, _) in &presets {
13648 by_bits[usize::from(*b)] += 1;
13649 }
13650 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
13651 let on_extra: usize = presets
13652 .iter()
13653 .flat_map(|(_, c)| c.iter().skip(1))
13654 .sum();
13655 eprintln!(
13656 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
13657 on a non-default preset ({:.1}%)",
13658 by_bits[0],
13659 by_bits[1],
13660 by_bits[2],
13661 by_bits[3],
13662 on_extra,
13663 units,
13664 100.0 * on_extra as f64 / units.max(1) as f64
13665 );
13666 // How the 64x64 luma restoration units split between
13667 // RESTORE_NONE and Wiener (lane-av1lr).
13668 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
13669 eprintln!(
13670 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
13671 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
13672 );
13673 // Which chroma modes the search actually wins with, against the
13674 // unconditional DC_PRED that was the only outcome before
13675 // (gate-blind-to-feature).
13676 // Screen-content detection and the palette it turns on
13677 // (gate-blind-to-feature): how many frames set
13678 // `allow_screen_content_tools`, how many blocks took a palette,
13679 // and of what size. A film clip must print `screen frames on=0`.
13680 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
13681 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
13682 // Which tables the SEARCH priced against, per frame arming
13683 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
13684 // real starting ones. A film clip must show every inter arming on
13685 // the real side, a screen clip none of them.
13686 let (price_default, price_real) = crate::tile::take_pricing_hits();
13687 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
13688 let palette = crate::tile::take_palette_hits();
13689 eprintln!(
13690 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
13691 palette[0],
13692 (2..=8)
13693 .filter(|&n| palette[n] > 0)
13694 .map(|n| format!("{n}={}", palette[n]))
13695 .collect::<Vec<_>>()
13696 .join(" ")
13697 );
13698 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
13699 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
13700 // only ever fires at one magnitude is a search that never left
13701 // its first candidate (gate-blind-to-feature).
13702 // The luma angle-delta histogram (lane-av1cfl): how many
13703 // directional blocks won at each delta. All-zero would mean the
13704 // refinement never beat the base angle.
13705 let deltas = take_angle_delta_hits();
13706 if deltas.iter().sum::<usize>() > 0 {
13707 eprintln!(
13708 "{name}: angle_delta_y {}",
13709 deltas
13710 .iter()
13711 .enumerate()
13712 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
13713 .collect::<Vec<_>>()
13714 .join(" ")
13715 );
13716 }
13717 let alphas = take_cfl_alpha_hits();
13718 if alphas.iter().sum::<usize>() > 0 {
13719 eprintln!(
13720 "{name}: cfl |alpha| {}",
13721 alphas
13722 .iter()
13723 .enumerate()
13724 .filter(|&(_, &n)| n > 0)
13725 .map(|(a, &n)| format!("{a}={n}"))
13726 .collect::<Vec<_>>()
13727 .join(" ")
13728 );
13729 }
13730 let palette_uv = crate::tile::take_palette_uv_hits();
13731 eprintln!(
13732 "{name}: chroma palette blocks {} sizes {}",
13733 palette_uv[0],
13734 (2..=8)
13735 .filter(|&n| palette_uv[n] > 0)
13736 .map(|n| format!("{n}={}", palette_uv[n]))
13737 .collect::<Vec<_>>()
13738 .join(" ")
13739 );
13740 let uv = take_uv_mode_hits();
13741 let uv_total: usize = uv.iter().sum();
13742 eprintln!(
13743 "{name}: uv modes {}",
13744 uv.iter()
13745 .enumerate()
13746 .filter(|&(_, &n)| n > 0)
13747 .map(|(m, &n)| format!(
13748 "{}={n} ({:.1}%)",
13749 UV_MODE_NAMES[m],
13750 100.0 * n as f64 / uv_total.max(1) as f64
13751 ))
13752 .collect::<Vec<_>>()
13753 .join(" ")
13754 );
13755 // Which transform depth the intra blocks of this clip's key
13756 // frames resolved to (lane-av1tx): depth 0 is one transform over
13757 // the whole block, 1 and 2 its halvings.
13758 let depths = take_tx_depth_hits();
13759 let depth_total: usize = depths.iter().sum();
13760 eprintln!(
13761 "{name}: intra tx depths {}",
13762 depths
13763 .iter()
13764 .enumerate()
13765 .map(|(d, &n)| format!(
13766 "{d}={n} ({:.1}%)",
13767 100.0 * n as f64 / depth_total.max(1) as f64
13768 ))
13769 .collect::<Vec<_>>()
13770 .join(" ")
13771 );
13772 print_inter_tx_census(name);
13773 // lane-av1obmc: how many blocks actually CODED a motion_mode
13774 // symbol and which value they took, by footprint -- "OBMC is on"
13775 // as a measurement rather than a claim (class
13776 // `gate-blind-to-feature`).
13777 let mm = crate::tile::take_motion_mode_hits();
13778 eprintln!(
13779 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
13780 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
13781 eligible)",
13782 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
13783 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
13784 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
13785 mm.iter().sum::<usize>(),
13786 );
13787 let (aom, aom_wall) =
13788 external_ladder(&source, width, height, "libaom-av1", &aom_points);
13789 let (rav1e, rav1e_wall) =
13790 external_ladder(&source, width, height, "librav1e", &rav1e_points);
13791 assert_monotone(&format!("{name}: ours"), &ours);
13792 assert_monotone(&format!("{name}: libaom"), &aom);
13793 assert_monotone(&format!("{name}: rav1e"), &rav1e);
13794 let points = ours
13795 .iter()
13796 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
13797 .collect::<Vec<_>>()
13798 .join(", ");
13799 println!(
13800 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
13801 bd_rate(&aom, &ours) * 100.0,
13802 bd_rate(&rav1e, &ours) * 100.0,
13803 );
13804 println!(
13805 "| references | libaom {} | rav1e {} | | |",
13806 aom.iter()
13807 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
13808 .collect::<Vec<_>>()
13809 .join(", "),
13810 rav1e
13811 .iter()
13812 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
13813 .collect::<Vec<_>>()
13814 .join(", "),
13815 );
13816 }
13817 }
13818 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
13819 /// split by block class in lane-av1txdepth): depth 0 is one transform over
13820 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
13821 /// leaves and the 32x32 root, each single-reference or compound. A class
13822 /// with no counts at all never reached `commit_inter_luma` -- which is
13823 /// what its knob being off looks like (class `gate-blind-to-feature`).
13824 fn print_inter_tx_census(name: &str) {
13825 let splits = take_inter_tx_split_hits();
13826 let total: usize = splits.iter().sum();
13827 let row = |label: &str, base: usize| {
13828 let (n0, n1) = (splits[base], splits[base + 1]);
13829 format!(
13830 "{label} 0={n0} 1={n1} ({:.1}% split)",
13831 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
13832 )
13833 };
13834 eprintln!(
13835 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
13836 row("leaf single", 0),
13837 row("leaf compound", 2),
13838 row("32x32 single", 4),
13839 row("32x32 compound", 6),
13840 );
13841 }
13842
13843 /// The video stream's coded size, from ffprobe.
13844 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
13845 let out = Command::new("ffprobe")
13846 .args(["-v", "error", "-select_streams", "v:0"])
13847 .args(["-show_entries", "stream=width,height", "-of", "csv=p=0"])
13848 .arg(clip)
13849 .output()
13850 .ok()?;
13851 let text = String::from_utf8_lossy(&out.stdout);
13852 let mut f = text.trim().split(',');
13853 Some((f.next()?.trim().parse().ok()?, f.next()?.trim().parse().ok()?))
13854 }
13855
13856 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
13857 /// with `probe_screen_detect` so the detector sweep measures exactly the
13858 /// clips the keep table is read off. Selector env vars as documented on
13859 /// the gate; a missing clip prints a SKIP and drops its row.
13860 fn native_gate_clips() -> Vec<(String, String, String)> {
13861 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
13862 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
13863 let (film, film4k, screen) = (
13864 on("EC_AV1_NATIVE_FILM"),
13865 on("EC_AV1_NATIVE_FILM4K"),
13866 on("EC_AV1_NATIVE_SCREEN"),
13867 );
13868 // No selector at all means every clip; any selector means that subset.
13869 let all = !(film || film4k || screen);
13870 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
13871 // not film -- they print as "bars" so no reader takes them for real
13872 // content -- and the two rows below them are the real AV1 films.
13873 let mut clips: Vec<(String, String, String)> = Vec::new();
13874 for (want, label, file) in [
13875 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
13876 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
13877 ] {
13878 if !want {
13879 continue;
13880 }
13881 let path = fixtures.join("video").join(file);
13882 match path.exists() {
13883 true => {
13884 clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into()))
13885 }
13886 false => eprintln!("SKIP {label}: {file} missing"),
13887 }
13888 }
13889 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
13890 // The real films, taken out of the real-library manifest by codec and
13891 // coded width so no title and no home path lives in this file. Each
13892 // seek is PINNED (class `seeded fixture not reproducible`) at a
13893 // moving, non-black window -- a black leader would make every arm
13894 // read +0.000 (class `flat sample window`). Both sources are 10-bit
13895 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
13896 // what all three encoders see, so the comparison stays
13897 // encoder-vs-encoder.
13898 let pick = |width: &str| -> Option<String> {
13899 let m = manifest.as_ref().ok()?;
13900 m.lines()
13901 .skip(1)
13902 .map(|l| l.split('\t').collect::<Vec<_>>())
13903 .find(|f| {
13904 f.len() > 4
13905 && f[2] == "av1"
13906 && f[3] == width
13907 && std::path::Path::new(f[0]).exists()
13908 })
13909 .map(|f| f[0].to_string())
13910 };
13911 for (want, label, width, seek) in [
13912 (all || film, "film A (1080p source)", "1920", "00:35:00"),
13913 (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"),
13914 ] {
13915 if !want {
13916 continue;
13917 }
13918 match pick(width) {
13919 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
13920 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
13921 }
13922 }
13923 if all || screen {
13924 match &manifest {
13925 Ok(manifest) => match manifest
13926 .lines()
13927 .skip(1)
13928 .filter_map(|l| l.split('\t').next())
13929 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
13930 {
13931 Some(p) => clips.push((
13932 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
13933 p.to_string(),
13934 "0".into(),
13935 )),
13936 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
13937 },
13938 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
13939 }
13940 }
13941 clips
13942 }
13943
13944 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
13945 /// downscales the OBS capture to 640x384, which destroys exactly the
13946 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
13947 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
13948 /// on that recipe is taken on content the tool cannot serve. This arm
13949 /// crops -- never scales -- a superblock-aligned window out of the middle
13950 /// of the capture at its own resolution (at most 1920x1024, so the wall
13951 /// stays in the minutes) and runs the same 12-frame, four-quantizer
13952 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
13953 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
13954 /// sample-exactness assertion `our_ladder` makes.
13955 ///
13956 /// It is its own `--ignored` test so the default gate's wall does not
13957 /// grow. Every variant is an environment knob, and each of those is a
13958 /// `OnceLock` read once per process, so a variant is a separate run:
13959 ///
13960 /// cargo test -p ec-av1 --release --lib -- --ignored \
13961 /// bd_rate_screen_native --nocapture # baseline
13962 /// EC_AV1_INTRABC=1 ... same command # intra block copy
13963 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
13964 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
13965 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
13966 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
13967 ///
13968 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
13969 /// through (lane-av1pyrdef); the run prints the requested and the
13970 /// effective pyramid per clip, and a screen clip's effective one is
13971 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
13972 /// streaming facade instead, which prints the per-level frame and byte
13973 /// census and asserts ffmpeg's decode against our own decoder on all
13974 /// three planes in display order; both arms code the same bytes
13975 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
13976 ///
13977 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
13978 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
13979 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
13980 /// cost -- so every "film" column in the historical tables of this file
13981 /// is that generator, not film. The real content is `film A`, `film B`
13982 /// (native crops out of the two AV1 films the real-library manifest
13983 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
13984 /// decision only the bars rows support is not supported.
13985 ///
13986 /// Measured 2026-09-07, the five rows before and after the screen
13987 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
13988 /// BOTH real films were classified as screen content on 48/48 frames, so
13989 /// their coefficients were priced against the DEFAULT CDFs and the
13990 /// palette search ran over film; after, both are non-screen (0/48) and
13991 /// the capture is unchanged at 48/48:
13992 ///
13993 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
13994 /// |---|---|---|---|
13995 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
13996 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
13997 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
13998 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
13999 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
14000 ///
14001 /// Both bars rows and the capture are byte-identical across that change
14002 /// (their classification never moved); the palette search over film was
14003 /// costing roughly a tenth of the film rows' wall.
14004 ///
14005 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
14006 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
14007 /// the capture is gated flat and does not move a byte:
14008 ///
14009 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
14010 /// |---|---|---|---|---|
14011 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
14012 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
14013 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
14014 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
14015 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
14016 ///
14017 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
14018 /// which is the point of the shared driver: the two entry points code one
14019 /// stream. The bars rows are fixtures (recorded, never a decision); the
14020 /// two real films are what the pyramid ships for.
14021 ///
14022 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
14023 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
14024 /// setting any one of them keeps only the selected rows (the two 1080p
14025 /// rows, the two 2160p rows, the capture row respectively). A missing
14026 /// real film SKIPs its row; it never fails the gate.
14027 #[test]
14028 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
14029 fn bd_rate_screen_native() {
14030 if !have_ffmpeg() {
14031 eprintln!("SKIP bd_rate_screen_native: no ffmpeg");
14032 return;
14033 }
14034 let clips = native_gate_clips();
14035 if clips.is_empty() {
14036 eprintln!("SKIP bd_rate_screen_native: no clip");
14037 return;
14038 }
14039
14040 let frames = 12usize;
14041 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
14042 .iter()
14043 .map(|q| {
14044 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
14045 .map(String::from)
14046 .to_vec()
14047 })
14048 .collect();
14049 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
14050 .iter()
14051 .map(|q| {
14052 vec![
14053 "-rav1e-params".to_string(),
14054 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
14055 ]
14056 })
14057 .collect();
14058 println!(
14059 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
14060 intrabc {}, palette maxcolors {}",
14061 armed_tiles(),
14062 crate::par::tile_threads(),
14063 intrabc_enabled(),
14064 palette_max_colors(),
14065 );
14066 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |");
14067 println!("|---|---|---|---|---|");
14068 for (name, path, seek) in &clips {
14069 let fctx = &crate::decode::FrameCtx::new();
14070 let Some((nw, nh)) = probe_dims(path) else {
14071 eprintln!("SKIP {name}: ffprobe gave no size");
14072 continue;
14073 };
14074 // A whole number of 128-wide superblocks, at most 1920x1024, out
14075 // of the middle of the frame; the offsets stay even for 4:2:0.
14076 let cw = nw.min(1920) / 128 * 128;
14077 let ch = nh.min(1024) / 128 * 128;
14078 assert!(cw >= 128 && ch >= 128, "{name}: {nw}x{nh} is smaller than a superblock");
14079 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
14080 let source = clip_frames_vf(
14081 path,
14082 seek,
14083 &format!("crop={cw}:{ch}:{x}:{y}"),
14084 cw,
14085 ch,
14086 frames,
14087 );
14088 SCREEN_FRAMES.iter().for_each(|c| {
14089 c.store(0, std::sync::atomic::Ordering::Relaxed);
14090 });
14091 let _ = crate::tile::take_palette_hits();
14092 let _ = crate::tile::take_palette_uv_hits();
14093 let _ = crate::tile::take_intrabc_hits();
14094 let _ = take_intrabc_search();
14095 // The sequence path itself codes the pyramid now
14096 // (lane-av1pyrdef), and prints what it requested and what the
14097 // content gate left effective.
14098 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
14099 // gate-blind-to-feature: what the screen tools actually did at
14100 // native resolution, over this clip's four encodes.
14101 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
14102 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
14103 // Which tables the SEARCH priced against, per frame arming
14104 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
14105 // real starting ones. A film clip must show every inter arming on
14106 // the real side, a screen clip none of them.
14107 let (price_default, price_real) = crate::tile::take_pricing_hits();
14108 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
14109 // lane-av1obmc2: the same motion_mode census the 640x384 gate
14110 // prints (class `gate-blind-to-feature`) -- how many blocks coded
14111 // the symbol at each footprint and how many took OBMC. Without it
14112 // the native table, which is the standing keep table, could not
14113 // say whether the tool fired at all.
14114 let mm = crate::tile::take_motion_mode_hits();
14115 eprintln!(
14116 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
14117 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
14118 eligible)",
14119 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
14120 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
14121 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
14122 mm.iter().sum::<usize>(),
14123 );
14124 print_inter_tx_census(name);
14125 let palette = crate::tile::take_palette_hits();
14126 let palette_uv = crate::tile::take_palette_uv_hits();
14127 let ibc = crate::tile::take_intrabc_hits();
14128 let search = take_intrabc_search();
14129 eprintln!(
14130 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
14131 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
14132 won {})",
14133 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
14134 palette[0],
14135 palette_uv[0],
14136 ibc[0],
14137 search[0],
14138 search[1],
14139 search[2],
14140 );
14141 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
14142 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
14143 assert_monotone(&format!("{name}: ours"), &ours);
14144 assert_monotone(&format!("{name}: libaom"), &aom);
14145 assert_monotone(&format!("{name}: rav1e"), &rav1e);
14146 let points = ours
14147 .iter()
14148 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
14149 .collect::<Vec<_>>()
14150 .join(", ");
14151 println!(
14152 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
14153 bd_rate(&aom, &ours) * 100.0,
14154 bd_rate(&rav1e, &ours) * 100.0,
14155 );
14156 }
14157 }
14158
14159 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
14160 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
14161 /// on the two film clips at their native gate crop. The 2160p clip loses
14162 /// at every arm of the propagating map and the named suspect was that its
14163 /// heavily filtered flat cells give a tiny denominator, so the dependence
14164 /// ratio explodes exactly where coding is cheap; this prints the numbers
14165 /// that confirm or refute it.
14166 #[test]
14167 #[ignore = "needs ffmpeg and the film fixtures"]
14168 fn tpl_intra_denominator_histogram() {
14169 if !have_ffmpeg() {
14170 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
14171 return;
14172 }
14173 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
14174 for (label, file) in [
14175 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
14176 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
14177 ] {
14178 let path = fixtures.join("video").join(file);
14179 if !path.exists() {
14180 eprintln!("SKIP {label}: {file} missing");
14181 continue;
14182 }
14183 let path = path.to_str().unwrap();
14184 let Some((nw, nh)) = probe_dims(path) else {
14185 eprintln!("SKIP {label}: ffprobe gave no size");
14186 continue;
14187 };
14188 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
14189 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
14190 let source =
14191 clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
14192 let mut costs: Vec<f64> = Vec::new();
14193 for pic in &source {
14194 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
14195 costs.extend(
14196 super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)),
14197 );
14198 }
14199 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
14200 let mut sorted = costs.clone();
14201 sorted.sort_by(f64::total_cmp);
14202 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
14203 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
14204 eprintln!(
14205 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
14206 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
14207 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
14208 below 1.0x {} ({:.1}%)",
14209 costs.len(),
14210 q(0.0),
14211 q(0.01),
14212 q(0.05),
14213 q(0.25),
14214 q(0.50),
14215 q(0.75),
14216 q(0.99),
14217 q(1.0),
14218 below(0.25),
14219 100.0 * below(0.25) as f64 / costs.len() as f64,
14220 below(0.5),
14221 100.0 * below(0.5) as f64 / costs.len() as f64,
14222 below(1.0),
14223 100.0 * below(1.0) as f64 / costs.len() as f64,
14224 );
14225 }
14226 }
14227}