forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB4c07cbcTahinli2 months ago3583 commits

encode.rs23323 lines, 1021.1 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};
43#[cfg(test)]
44use crate::transform::forward_and_quantize;
45use crate::transform::{
46 TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
47 forward_and_quantize_typed_scaled,
48};
49
50/// The side of the larger of the two luma blocks this encoder codes, in
51/// samples.
52const BLOCK: usize = 32;
53
54/// The side of the smaller one, which a 32x32 block may be split into four of.
55const SUB: usize = 16;
56
57/// The side of a superblock, which is what the partition tree starts from.
58pub(crate) const SUPERBLOCK: usize = 64;
59
60// lane-sb128 r1: the superblock size in samples the intra-reach rules
61// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the
62// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and
63// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128
64// superblock changes every answer inside it (the tables themselves are
65// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
66// stays the encoder's own fixed 64.
67
68/// Sets the superblock size [`Reach`] answers against (64 or 128).
69pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
70 fctx.reach_sb_px.with(|c| c.set(px));
71}
72
73fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
74 fctx.reach_sb_px.with(|c| c.get())
75}
76
77/// How heavily the mode search weighs rate against squared error, in units of
78/// the quantizer's reconstruction step squared per bit.
79///
80/// Swept three times over his clips and three synthetic pictures
81/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
82/// the three lane reports). The first sweep, before the mode symbol was
83/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
84/// third sweep, after the levels were costed through the writer's own CDFs
85/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
86/// on film and -0.20% against -0.14% on screen capture.
87///
88/// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than
89/// those ladders, and 0.1 was far off the point: the rate term was carrying
90/// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom /
91/// vs rav1e for 1080p film, 2160p film, screen capture:
92///
93/// | lambda | 1080p | 2160p | screen |
94/// |--------|-------|-------|--------|
95/// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 |
96/// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 |
97/// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 |
98/// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
99/// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 |
100/// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 |
101/// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 |
102/// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 |
103/// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 |
104///
105/// and on the native 1920x1024 crops, which is the table that decides:
106///
107/// | lambda | film 1080p | film 2160p | screen |
108/// |--------|------------|------------|--------|
109/// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 |
110/// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 |
111/// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 |
112/// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 |
113///
114/// 0.0375 was the best point on two clips of three there and cost the "2160p
115/// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept
116/// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the
117/// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of
118/// whose cells have no intra cost -- no real film supported the point.
119///
120/// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL
121/// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs
122/// libaom / vs rav1e, everything else at the shipped defaults:
123///
124/// | lambda | bars 1080p | bars 2160p | film A | film B | screen |
125/// |--------|------------|------------|--------|--------|--------|
126/// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 |
127/// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 |
128/// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 |
129/// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 |
130/// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 |
131/// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 |
132///
133/// Real film wants roughly HALF the rate weight the bars asked for: the bowl
134/// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep
135/// against the shipped 0.05, while the bars rows walk the other way (they are
136/// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so
137/// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture
138/// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx
139/// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall.
140const LAMBDA_SCALE: f64 = 0.0275;
141
142/// The rate weight a HIDDEN frame (a pyramid ARF, coded but not shown) codes
143/// under, as a multiple of [`LAMBDA_SCALE`] (lane-arfcen).
144///
145/// The ARF-vs-ARF census says our top ARF codes residual over HALF its area
146/// (rav1e's, at the same display position, over 26-30%) and comes out 1.4-2.5x
147/// its bytes at the same PSNR, while every leaf that predicts from it is
148/// still 0.4 dB behind rav1e's -- i.e. the ARF's extra fidelity is bought at
149/// a rate weight fitted on shown frames and does not propagate. This is the
150/// one knob that prices a hidden frame's rate differently from its q, which
151/// the pyramid's q offsets cannot do (they move lambda and step together).
152const HIDDEN_LAMBDA_FACTOR: f64 = 1.0;
153
154/// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build.
155fn hidden_lambda_factor() -> f64 {
156 match std::env::var("EC_AV1_LAMBDA_HIDDEN")
157 .ok()
158 .and_then(|v| v.parse().ok())
159 {
160 Some(f) => f,
161 None => HIDDEN_LAMBDA_FACTOR,
162 }
163}
164
165/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
166/// picks it is the thing running. A release build has no such knob.
167fn lambda_scale() -> f64 {
168 let swept = std::env::var("EC_AV1_LAMBDA")
169 .ok()
170 .and_then(|v| v.parse::<f64>().ok());
171 match swept {
172 Some(scale) if cfg!(test) => scale,
173 _ => LAMBDA_SCALE,
174 }
175}
176
177/// How a key frame's lambda differs from an inter frame's: libaom weighs the
178/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
179/// of 128), because every later frame predicts from the key frame, so an error
180/// left in it is paid for over the whole group. This encoder has no temporal
181/// propagation model at all, and this factor is the cheapest stand-in for one.
182/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
183///
184/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
185/// libaom / vs rav1e:
186///
187/// | k_key | 1080p | 2160p | screen |
188/// |---|---|---|---|
189/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
190/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
191/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
192/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
193///
194/// The two films want the key frame coded finer and the screen capture wants
195/// the opposite, by about the same amount, and at native the whole lever is
196/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
197/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
198/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
199/// per-frame-type weight; the real lever here is temporal propagation
200/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
201/// predict from, not each frame.
202const KEY_LAMBDA_FACTOR: f64 = 1.0;
203
204/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
205fn key_lambda_factor() -> f64 {
206 match std::env::var("EC_AV1_LAMBDA_KEY")
207 .ok()
208 .and_then(|v| v.parse::<f64>().ok())
209 {
210 Some(k) if cfg!(test) => k,
211 _ => KEY_LAMBDA_FACTOR,
212 }
213}
214
215// Every frame's predicted coefficient bits since the last
216// `take_predicted_bits`, in coding order -- the encoder half of
217// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
218#[cfg(test)]
219thread_local! {
220 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
221}
222
223/// Records one frame's predicted coefficient bits.
224#[cfg(test)]
225fn record_predicted_bits(bits: f64) {
226 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
227}
228
229/// Takes (and clears) what the frames encoded on this thread were predicted to
230/// spend on coefficients.
231#[cfg(test)]
232pub(crate) fn take_predicted_bits() -> Vec<f64> {
233 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
234}
235
236/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
237pub(crate) const SPLIT_INTER_8: bool = true;
238
239/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
240/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
241/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
242/// turns it off for an A/B on one build.
243/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
244/// residual as one transform over the whole block or as the four transforms
245/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
246/// intra block inside the inter frame. ON since lane-av1tx2, which found why
247/// the streams desynced -- the writer counted the [`crate::decode::
248/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
249/// reader drops the term -- and measured the split search: BD-rate vs libaom
250/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
251/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
252/// A/B on one build.
253fn tx_select_inter() -> bool {
254 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
255 crate::envflags::var("EC_AV1_TX_SELECT_INTER")
256 .ok()
257 .map(|v| !matches!(v.as_str(), "0" | "off"))
258 });
259 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
260}
261
262/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`, control
263/// vs arm): the capture row goes +27.8/-26.0 -> +20.8/-30.1 -- seven points
264/// against libaom -- while BOTH film rows LOSE (film A +21.7/-4.4 ->
265/// +22.1/-4.0, film B +26.9/-0.6 -> +28.1/+0.7) and 2160p bars lose 0.8/1.1.
266/// The keep rule wants both films down, so this takes the same content gate
267/// palette, intrabc and the angle-delta refinement already stand behind: a
268/// non-screen frame is byte-identical to the encoder before the lane.
269///
270/// The transform types an intra luma transform unit of `set` may be coded
271/// with -- exactly the alphabet the writer's `tx_type` symbol names for that
272/// set, so a searched type is always one the tile can express (lane-txset).
273/// `DCT_DCT` first: it is the incumbent every other candidate has to beat.
274///
275/// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16
276/// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types
277/// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all,
278/// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT`
279/// here.
280pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
281 const DCT: [TxType; 1] = [TxType::DctDct];
282 const INTRA1: [TxType; 7] = [
283 TxType::DctDct,
284 TxType::AdstAdst,
285 TxType::AdstDct,
286 TxType::DctAdst,
287 TxType::Idtx,
288 TxType::VDct,
289 TxType::HDct,
290 ];
291 const INTRA2: [TxType; 5] = [
292 TxType::DctDct,
293 TxType::AdstAdst,
294 TxType::AdstDct,
295 TxType::DctAdst,
296 TxType::Idtx,
297 ];
298 match set {
299 TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 if intra_tx_search_on(screen) => &INTRA2,
300 // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the
301 // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`;
302 // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two
303 // extra members are the 1-D DCTs, and the order is the reader's own
304 // map (`decode::tx_type_from_symbol`, 8-wide CDF).
305 TxbSet::Luma8Set1 | TxbSet::Luma4Set1 if intra_tx_search_on(screen) => &INTRA1,
306 _ => &DCT,
307 }
308}
309
310/// The transform types an INTER luma transform unit of `set` may be coded
311/// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every
312/// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3`
313/// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two
314/// types, a symbol the writer already codes and never varied. 64x64 codes no
315/// `tx_type` symbol at all, so it is not offered one.
316/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`): the
317/// capture row goes +20.8/-30.1 -> +20.1/-30.4 while the two synthetic bars
318/// rows lose TWENTY points (-1.0/-16.8 -> +23.1/+3.3 and +9.4/-12.7 ->
319/// +31.2/+3.7) and film B 0.3 -- the `local-rd-on-references` class at its
320/// loudest, and restricting the offer to 16x16 and below does not soften it
321/// (`le16`: +22.9/+3.1, +31.6/+4.0). So this takes the same content gate the
322/// intra search, palette and intrabc stand behind: a non-screen frame is
323/// byte-identical to the encoder before the lane.
324///
325/// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), `le16`
326/// (16x16 and below, the sizes libaom's own census picks a non-`DCT_DCT`
327/// inter type on -- it never takes `IDTX` at 32x32 on film B), anything else
328/// on for every frame at every size.
329pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
330 const DCT: [TxType; 1] = [TxType::DctDct];
331 const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx];
332 const INTER_WIDE: [TxType; 7] = [
333 TxType::DctDct,
334 TxType::AdstAdst,
335 TxType::AdstDct,
336 TxType::DctAdst,
337 TxType::Idtx,
338 TxType::VDct,
339 TxType::HDct,
340 ];
341 let mode = inter_tx_type_search();
342 let on = match mode {
343 InterTxSearch::Off => false,
344 InterTxSearch::Screen => screen,
345 InterTxSearch::All | InterTxSearch::Le16 => true,
346 };
347 match set {
348 TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3,
349 TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3,
350 // lane-txi: a `reduced_tx_set == 0` frame's inter 16x16 reads the
351 // TWELVE-type `TX_SET_INTER_2` and its 8x8/4x4 `ALL16` (inter 32x32
352 // stays the two-type `DCT_IDTX`). The seven offered here are the
353 // members those two alphabets SHARE with the intra set -- the four
354 // DTT combinations, `IDTX` and the two 1-D DCTs -- which is the
355 // candidate list rav1e's speed 6 prunes to; the FLIPADST family and
356 // the 1-D ADSTs are codable and left unoffered (deferred).
357 TxbSet::Luma16InterSet1 | TxbSet::Luma8InterSet1 | TxbSet::Luma4InterSet1 if on => {
358 &INTER_WIDE
359 }
360 _ => &DCT,
361 }
362}
363
364/// lane-txi: does THIS frame code `reduced_tx_set = 0` (spec 5.9.2), i.e.
365/// the wider `tx_type` alphabets at intra 8x8/4x4 and inter 16x16 and below?
366/// `EC_AV1_TXSET_WIDE`: `0`/`off`, `screen` (screen frames only), anything
367/// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated
368/// like both halves of the type search itself.
369pub(crate) fn wide_tx_set(screen: bool) -> bool {
370 match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
371 0 => return false,
372 1 => return true,
373 _ => {}
374 }
375 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
376 crate::envflags::var("EC_AV1_TXSET_WIDE")
377 .ok()
378 .map(|v| match v.as_str() {
379 "0" | "off" => InterTxSearch::Off,
380 "screen" => InterTxSearch::Screen,
381 _ => InterTxSearch::All,
382 })
383 });
384 match ENV.unwrap_or(if crate::speed::at(&crate::speed::WIDE_TX_SET) {
385 InterTxSearch::Screen
386 } else {
387 InterTxSearch::Off
388 }) {
389 InterTxSearch::Off => false,
390 InterTxSearch::Screen => screen,
391 _ => true,
392 }
393}
394
395/// A PROCESS-GLOBAL [`wide_tx_set`] override that wins over both the
396/// environment and the preset (`u8::MAX` = unset), the shape
397/// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the
398/// witness that has to see the wider alphabets turns it on through this while
399/// holding [`crate::speed::knob_write`].
400static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
401
402/// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it.
403#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
404pub(crate) fn set_wide_tx_set(on: Option<bool>) {
405 WIDE_TX_OVERRIDE.store(
406 on.map_or(u8::MAX, u8::from),
407 std::sync::atomic::Ordering::Relaxed,
408 );
409}
410
411/// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes
412/// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own
413/// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read
414/// the same alphabet or the two disagree on what a `tx_type` symbol costs.
415pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet {
416 if wide_tx_set(screen) { set.wide() } else { set }
417}
418
419#[derive(Clone, Copy, PartialEq)]
420pub(crate) enum InterTxSearch {
421 Off,
422 Screen,
423 /// 16x16 and below only.
424 Le16,
425 All,
426}
427
428/// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the
429/// environment and the preset (`u8::MAX` = unset), the shape
430/// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness
431/// that has to see a non-`DCT_DCT` inter unit turns it on through this while
432/// holding [`crate::speed::knob_write`].
433static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
434
435/// Sets [`INTER_TX_OVERRIDE`]; `None` clears it.
436#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
437pub(crate) fn set_inter_tx_search(on: Option<bool>) {
438 INTER_TX_OVERRIDE.store(
439 on.map_or(u8::MAX, u8::from),
440 std::sync::atomic::Ordering::Relaxed,
441 );
442}
443
444fn inter_tx_type_search() -> InterTxSearch {
445 match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
446 0 => return InterTxSearch::Off,
447 1 => return InterTxSearch::All,
448 _ => {}
449 }
450 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
451 crate::envflags::var("EC_AV1_TXSET_INTER")
452 .ok()
453 .map(|v| match v.as_str() {
454 "0" | "off" => InterTxSearch::Off,
455 "screen" => InterTxSearch::Screen,
456 "le16" => InterTxSearch::Le16,
457 _ => InterTxSearch::All,
458 })
459 });
460 ENV.unwrap_or_else(|| {
461 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) {
462 InterTxSearch::Screen
463 } else {
464 InterTxSearch::Off
465 }
466 })
467}
468
469/// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the
470/// 64-point one (it codes no `tx_type` symbol).
471/// lane-txw history, resolved by lane-intertx: the INTER half of the
472/// widening was blocked by `refusal-from-own-desync` twice over. Half of it
473/// was this writer coding a `V_DCT`/`H_DCT` unit as `TX_CLASS_2D`
474/// (`tile::write_coeffs`, fixed by lane-txw, which unblocked the intra
475/// half). The other half was the CHROMA inheritance: an inter block's
476/// chroma transform type is the luma type reduced to the chroma size's set
477/// (`decode::reduce_inherited_chroma_tx_type`), and (a) the encoder never
478/// set `FrameCtx::reduced_tx_set_inter`, so [`recode_inter_chroma`] reduced
479/// against a STALE allowance, and (b) `tile::write_block_planes` coded
480/// every chroma plane as `DCT_DCT`, so an inherited 1-D type desynced the
481/// chroma exactly as luma did. lane-intertx fixed both -- the frame sets
482/// its own bit on the context (`encode_inter_frame`), the writer derives
483/// the chroma type from this frame's own header bit
484/// (`reduce_inherited_chroma_tx_type_flagged`) -- and the widened SEARCH
485/// names these sets through [`luma_set_for`] at its call sites, so the
486/// wider candidates are reachable and honestly priced. The intra half
487/// never needed either (an intra block's chroma type comes off its own UV
488/// mode, never off luma).
489fn inter_luma_set(tx: usize) -> Option<TxbSet> {
490 Some(match tx {
491 4 => TxbSet::Luma4Inter,
492 8 => TxbSet::Luma8Inter,
493 16 => TxbSet::Luma16Inter,
494 32 => TxbSet::Luma32Inter,
495 _ => return None,
496 })
497}
498
499fn tx_type_search() -> bool {
500 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
501 crate::envflags::var("EC_AV1_TXSET")
502 .ok()
503 .map(|v| !matches!(v.as_str(), "0" | "off"))
504 });
505 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
506}
507
508/// Whether an intra luma unit of this frame searches its own type at all:
509/// the preset lever ([`tx_type_search`]) under the screen content gate, which
510/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global
511/// [`set_intra_tx_search`] override wins over (the witness needs the search
512/// on a frame the detector called non-screen).
513fn intra_tx_search_on(screen: bool) -> bool {
514 match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
515 0 => return false,
516 1 => return true,
517 _ => {}
518 }
519 (screen || intra_tx_all_frames()) && tx_type_search()
520}
521
522/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
523/// shape [`set_inter_tx_search`] has.
524static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
525
526/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
527#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
528pub(crate) fn set_intra_tx_search(on: Option<bool>) {
529 INTRA_TX_OVERRIDE.store(
530 on.map_or(u8::MAX, u8::from),
531 std::sync::atomic::Ordering::Relaxed,
532 );
533}
534
535/// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY
536/// frame -- the unconditional arm the gate measures -- instead of the screen
537/// content gate [`tx_type_candidates`] ships behind. Any other value keeps
538/// the gate (`0`/`off` still switches the search off entirely).
539fn intra_tx_all_frames() -> bool {
540 static ENV: std::sync::LazyLock<bool> =
541 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all"));
542 *ENV
543}
544
545fn tx_select() -> bool {
546 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
547 crate::envflags::var("EC_AV1_TX_SELECT")
548 .ok()
549 .map(|v| !matches!(v.as_str(), "0" | "off"))
550 });
551 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
552}
553
554fn split_inter_8() -> bool {
555 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
556 Some(v) if cfg!(test) => v != "0",
557 _ => crate::speed::at(&crate::speed::SPLIT_8),
558 }
559}
560
561/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
562/// NEARESTMV candidate it always had.
563pub(crate) const LEAF_NEW_MV: bool = true;
564
565/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
566/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
567/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
568/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
569pub(crate) const EXTRA_REF_NEW_MV: bool = true;
570
571/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
572/// own best vector before that reference's `NEWMV` search is skipped: a
573/// factor on the search cost scale, `1.0` meaning "as good or better".
574/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
575/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
576/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
577/// extra searches drop from +27% to +4% of the base count -- and on screen
578/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
579/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
580/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
581/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
582/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
583/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
584/// own noise. 0.35 stays; the lever that did move at the new rate weight is
585/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
586const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
587
588/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
589fn extra_new_skip_margin() -> f64 {
590 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
591 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
592 _ => EXTRA_NEW_SKIP_MARGIN,
593 }
594}
595
596/// The margin on a LEAF's SECOND-reference motion search, the same early-out
597/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
598/// `NEWMV`: the search is skipped when that reference's own
599/// `NEAREST_NEARESTMV` vector already prices this many times better than the
600/// leaf's `LAST` search found. `0.0` never skips.
601///
602/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
603/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
604/// 2160p (38195 with no second-reference search at all):
605/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
606/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
607/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
608/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
609/// of its extra searches; past it the calls double for another -0.3/-0.5.
610/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
611/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
612/// so the margin is pure wall on that content (+10% searches at 0.8).
613///
614/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
615/// the native gate with local warp on, BD vs libaom / vs rav1e:
616///
617/// | margin | film 1080p | film 2160p | screen |
618/// |---|---|---|---|
619/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
620/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
621/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
622/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
623/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
624///
625/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
626/// with screen flat -- and it beats never-skipping, i.e. the early-out is
627/// still worth having, just at a looser margin than the old rate weight
628/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
629/// 32.6s at 2160p), which is the price of the extra second-reference
630/// searches.
631const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
632
633/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
634/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
635fn leaf_second_new_margin() -> f64 {
636 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
637 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
638 None => LEAF_SECOND_NEW_MARGIN,
639 }
640}
641
642/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
643fn leaf_second_new_mv() -> bool {
644 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
645 Some(v) => v != "0",
646 None => crate::speed::at(&crate::speed::LEAF_SECOND),
647 }
648}
649
650/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
651/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
652/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
653/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
654/// was missing was the encoder ever forming one below 32x32.
655pub(crate) const LEAF_COMPOUND: bool = true;
656
657/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
658fn leaf_compound() -> bool {
659 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
660 Some(v) => v != "0",
661 None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
662 }
663}
664
665/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
666fn leaf_new_mv() -> bool {
667 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
668 Some(v) if cfg!(test) => v != "0",
669 _ => LEAF_NEW_MV,
670 }
671}
672
673/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
674/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
675/// the true frame edge cut through was ever split there; inside the frame
676/// every block was coded whole, which left the partition decision the key
677/// frame already makes unmade for eleven frames out of twelve.
678pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
679
680/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
681/// measurement that keeps it is running (test builds only, like
682/// [`lambda_scale`]).
683fn split_inter_blocks() -> bool {
684 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
685 Some(v) if cfg!(test) => v != "0",
686 _ => crate::speed::at(&crate::speed::SPLIT_INTER),
687 }
688}
689
690/// Whether the inter search offers the whole superblock as ONE 64x64 block
691/// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32
692/// quadrants it would otherwise always split into.
693///
694/// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6
695/// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of
696/// them skip at 328 bytes a frame -- while every block this encoder wrote was
697/// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669
698/// bits against rav1e's 61,988, about 46% of the film B gap.
699///
700/// lane-tx64: no longer skip-only. The root also prices a REAL residual --
701/// one TX_64X64 luma transform (`transform.rs`'s forward network has always
702/// reached 64 points; what was missing was the block coder and the writer
703/// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`],
704/// which carries that arm's own gate table. Still refused at the 64 root:
705/// compound references, a depth-1 4x32x32 var-tx tree, intra, and a
706/// superblock the true frame edge cuts through.
707///
708/// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the
709/// root and restores the skip-only shape lane-b64 shipped.
710pub(crate) const B64_ROOT: bool = true;
711
712/// How many superblocks took the 64x64 root since the last
713/// [`take_b64_root_hits`], so a gate reports how often it fires rather than
714/// assuming it does (class `gate-blind-to-feature`).
715static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
716
717/// The 64x64-root count since the last call, and zero it.
718pub fn take_b64_root_hits() -> usize {
719 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
720}
721
722/// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at
723/// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off,
724/// which is the attribution arm for a 128-superblock stream: it separates
725/// what the SIZE costs from what the 128x128 BLOCK buys.
726fn b128_root() -> bool {
727 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
728 crate::envflags::var("EC_AV1_B128")
729 .ok()
730 .is_none_or(|v| v != "0")
731 });
732 *ENV
733}
734
735/// lane-b128r: whether the 128 root prices a REAL residual as well as the
736/// skip arm -- four TX_64X64 luma units interleaved with a TX_32X32 chroma
737/// pair per 64x64 mu chunk, var-tx depth 0 (the shape
738/// [`crate::tile::write_inter_block_128`] codes and `decode_inter_block`
739/// reads). Written, witnessed and byte-exact through both decoders, and
740/// **off by default** (`EC_AV1_B128RES=1` turns it on) because it is INERT
741/// on content: the RD takes it 0.7-1.9 times per frame against thousands of
742/// whole 128 roots (lane-b128res census, native 12-frame gate, every clip),
743/// and the BD effect is inside the noise on both gates -- long-GOP films
744/// -0.1/+0.1 and all five 12-frame rows within 0.1 of the off default.
745///
746/// The historical reason for the parking is CLOSED: the bars 2160p q=90
747/// frame 11 disagreement with ffmpeg (8 luma samples at the rows above a
748/// 128-superblock horizontal edge) was the CDEF search pricing a preset per
749/// 64x64 unit under a root that codes ONE literal for all four -- lane-
750/// edge128's `crate::tile::cdef_unit_owner` collapses the four to the one
751/// the decoder derives, and on this HEAD the same row re-measures three-way
752/// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
753/// every plane, both gates). The knob stays as the arm's gate, not as a
754/// defect flag.
755fn b128_residual() -> bool {
756 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
757 crate::envflags::var("EC_AV1_B128RES")
758 .ok()
759 .map(|v| v != "0")
760 });
761 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
762 && b128_root()
763}
764/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
765/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
766/// plus one half) -- price a REAL residual in the RD as well as the skip arm
767/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
768/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
769/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
770/// no rect/AB piece can come out non-skip, so the writer's refusal is never
771/// reached. The residual shape is the whole 128 block's, halved or quartered
772/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
773/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
774/// for any inter partition shape).
775fn rectres() -> bool {
776 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
777 crate::envflags::var("EC_AV1_RECTRES")
778 .ok()
779 .map(|v| v != "0")
780 });
781 ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
782}
783
784/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
785/// witness clip codes the shape rather than waiting for content on which the
786/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
787/// root). Never read outside `#[cfg(test)]` builds.
788static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
789 std::sync::atomic::AtomicBool::new(false);
790
791/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
792#[cfg(test)]
793pub(crate) fn force_b128_rectres(on: bool) {
794 FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
795}
796
797/// How many rect/AB pieces the search left WITH a residual rather than
798/// skipped, since the last [`take_b128_rectres_hits`] (class
799/// `gate-blind-to-feature`).
800static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
801
802/// The rect/AB-piece-residual count since the last call, and zero it.
803pub fn take_b128_rectres_hits() -> usize {
804 B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
805}
806
807/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
808/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
809/// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's
810/// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this
811/// arm's attribution control; the writer has always had the path
812/// (`write_inter_block_128` calls `write_compound_block` for a block that
813/// names a second reference).
814fn b128_compound() -> bool {
815 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
816 crate::envflags::var("EC_AV1_B128COMP")
817 .ok()
818 .map(|v| v != "0")
819 });
820 ENV.unwrap_or(true) && b128_root()
821}
822
823/// How many 128 roots came out COMPOUND since the last
824/// [`take_b128_compound_hits`] (class `gate-blind-to-feature`).
825static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
826
827/// The compound-128 count since the last call, and zero it.
828pub fn take_b128_compound_hits() -> usize {
829 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
830}
831
832/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ`
833/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the
834/// same skip-only single-reference/compound machinery the NONE arm ships,
835/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
836/// `EC_AV1_B128HV=0` is this arm's attribution control.
837fn b128_rect() -> bool {
838 static ENV: std::sync::LazyLock<Option<bool>> =
839 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0"));
840 ENV.unwrap_or(true) && b128_root()
841}
842
843/// lane-rectdq: whether the delta_q symbol group is priced on the root
844/// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's
845/// attribution control (the pre-lane pricing, where a 128 rect root and the
846/// four-superblock arm were both priced as if the group were free).
847fn rectdq() -> bool {
848 static ENV: std::sync::LazyLock<Option<bool>> =
849 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0"));
850 ENV.unwrap_or(true)
851}
852
853/// lane-rectdq: what `crate::tile::write_delta_q` spends to move
854/// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of
855/// `res` -- the same three pieces that writer codes, in its order: the
856/// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the
857/// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from
858/// exactly this row), the escape literal pair when `abs >= 3`, and the sign
859/// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`).
860pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 {
861 if res <= 0 {
862 return 0.0;
863 }
864 /// spec `DELTA_Q_SMALL`, as in the writer.
865 const DELTA_Q_SMALL: usize = 3;
866 let reduced = (target - cur) / res;
867 let abs = reduced.unsigned_abs() as usize;
868 // A pricing coder, not a sum of table entries: the escape's literal bits
869 // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB`
870 // floor, so each really costs a little over one bit (class
871 // `price-the-narrowing-not-the-table`). Read off the same
872 // `SymbolEncoder::bits` account the writer's own coder keeps.
873 let mut enc = crate::msac::SymbolEncoder::pricer();
874 enc.reset_bits();
875 enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q);
876 if abs >= DELTA_Q_SMALL {
877 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
878 enc.literal(rem_bits - 1, 3);
879 enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits);
880 }
881 if abs != 0 {
882 enc.literal(u32::from(reduced < 0), 1);
883 }
884 enc.bits()
885}
886
887/// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64
888/// superblock units): the group every root shape but a SKIPPED
889/// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for
890/// `side == write_w == write_h == sb_px` and neither a rect half nor a 64
891/// superblock under a 128 grid is that.
892///
893/// The target is the root's own cell of the `sb_q` grid, exactly the entry
894/// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search --
895/// the writer's `plan.cur` only advances at the roots that really code a
896/// group, and which those are is decided by this very comparison -- so the
897/// PREVIOUS 128 root's target in raster order stands in for it (the frame's
898/// `base_q_idx` at the first root of the frame, which is also the writer's
899/// own per-tile reset). Wrong only where a neighbouring root came out a
900/// skipped NONE block, and then only by the difference of two adjacent tpl
901/// cells.
902fn delta_q_bits_at_root(
903 sb_q: Option<&Vec<u8>>,
904 sb_cols: usize,
905 base_q_idx: u8,
906 res: i32,
907 (root_r, root_c): (usize, usize),
908) -> f64 {
909 if !rectdq() || res <= 0 {
910 return 0.0;
911 }
912 let Some(q) = sb_q.filter(|q| !q.is_empty()) else {
913 return 0.0;
914 };
915 let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]);
916 let target = at(root_r, root_c);
917 let cur = if root_c >= 2 {
918 at(root_r, root_c - 2)
919 } else if root_r >= 2 {
920 // The last 128 root of the row above, i.e. the previous one in the
921 // writer's raster walk.
922 at(root_r - 2, (sb_cols.saturating_sub(1)) & !1)
923 } else {
924 i32::from(base_q_idx)
925 };
926 delta_q_bits(target, cur, res)
927}
928
929/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
930/// halves since the last take (class `gate-blind-to-feature`).
931static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
932/// The VERT twin of [`B128_HORZ_HITS`].
933static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
934
935/// The HORZ-128-root count since the last call, and zero it.
936pub fn take_b128_horz_hits() -> usize {
937 B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
938}
939
940/// The VERT-128-root count since the last call, and zero it.
941pub fn take_b128_vert_hits() -> usize {
942 B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
943}
944
945/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off,
946/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because
947/// synthetic content is where the shape is cheapest to decode-check and the
948/// RD there prefers one whole block; the gate census is the unforced count.
949static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
950
951/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
952#[cfg(test)]
953pub(crate) fn force_b128_rect(which: u8) {
954 FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
955}
956
957/// lane-ab128: whether the 128 superblock root offers its four AB shapes --
958/// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
959/// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128
960/// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is
961/// the same skip-only single-reference/compound block the NONE and HORZ/VERT
962/// arms ship, at its own footprint ([`search_root_128_ab`],
963/// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this
964/// arm's attribution control.
965///
966/// **Off by default** (`EC_AV1_B128AB=1` turns it on): measured on both gates
967/// and it does not pay. The shapes fire 0-2 roots a frame against ~1000 coded
968/// blocks (`EC_AV1_B128_CENSUS`), and every row is flat or 0.1 worse --
969/// long-GOP film A +22.0/-8.5 against a +21.9/-8.6 control, film B +75.8/+0.8
970/// against the same, 12-frame film A +18.1/-6.2 against +18.0/-6.3, film B
971/// +23.1/-3.3 against +23.0/-3.5, screen byte-identical (lane-ab128). The
972/// machinery is written, witnessed sample-exact through both decoders on all
973/// four shapes, and kept for the arm that makes it pay: a non-skip piece (the
974/// 64x64 pieces could carry the 64 root's residual, which is where libaom's
975/// AB shapes earn their keep) or a cheaper partition price.
976fn b128_ab() -> bool {
977 static ENV: std::sync::LazyLock<Option<bool>> =
978 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0"));
979 ENV.unwrap_or(false) && b128_root()
980}
981
982/// How many 128 roots the search left as each AB shape since the last take,
983/// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class
984/// `gate-blind-to-feature`).
985static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
986 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
987
988/// The four per-shape AB-root counts since the last call, and zero them.
989pub fn take_b128_ab_hits() -> [usize; 4] {
990 std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
991}
992
993/// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then
994/// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic
995/// content is where the shapes are cheapest to decode-check and the RD there
996/// prefers one whole block).
997static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
998
999/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7).
1000#[cfg(test)]
1001pub(crate) fn force_b128_ab(which: u8) {
1002 FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed);
1003}
1004
1005/// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
1006/// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
1007/// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =
1008/// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR.
1009/// Each entry is the piece's own top-left in mode-info units and its
1010/// footprint in samples.
1011pub(crate) fn ab128_pieces(
1012 symbol: usize,
1013 (mi_row, mi_col): (usize, usize),
1014) -> [((usize, usize), (usize, usize)); 3] {
1015 const S: usize = SUPERBLOCK;
1016 let (r, c) = (mi_row, mi_col);
1017 let (r1, c1) = (mi_row + 16, mi_col + 16);
1018 match symbol {
1019 // PARTITION_HORZ_A
1020 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))],
1021 // PARTITION_HORZ_B
1022 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))],
1023 // PARTITION_VERT_A
1024 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))],
1025 // PARTITION_VERT_B
1026 _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))],
1027 }
1028}
1029
1030/// Test-only: take the 128 root's residual arm whatever it costs, so a
1031/// witness clip codes the shape rather than waiting for content on which the
1032/// RD picks it (the same role [`force_sb128`] plays for the superblock size).
1033/// Never read outside `#[cfg(test)]` builds.
1034static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
1035 std::sync::atomic::AtomicBool::new(false);
1036
1037/// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take
1038/// the 128 root whenever it produced a candidate at all, whatever its four
1039/// cells cost, so a witness codes the block it is about rather than waiting
1040/// for content on which the root also wins its own comparison.
1041static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1042
1043/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
1044/// forced residual block only reaches the writer if its root is taken.
1045#[cfg(test)]
1046pub(crate) fn force_b128_residual(on: bool) {
1047 FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
1048 force_b128_root(on);
1049}
1050
1051/// Arms [`FORCE_B128_ROOT`] for the rest of the process.
1052#[cfg(test)]
1053pub(crate) fn force_b128_root(on: bool) {
1054 FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed);
1055}
1056
1057/// How many 128 roots came out cheaper WITH a residual than skipped, since
1058/// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
1059static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1060
1061/// The 128-residual count since the last call, and zero it.
1062pub fn take_b128_residual_hits() -> usize {
1063 B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1064}
1065
1066/// How many 128x128 `PARTITION_NONE` roots the search took since the last
1067/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
1068/// is only attributable once the fire count is known.
1069static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1070
1071/// The 128x128-root count since the last call, and zero it.
1072pub fn take_b128_none_hits() -> usize {
1073 B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1074}
1075
1076/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
1077/// Preset-gated: it re-prices the block once per candidate level, so it buys
1078/// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
1079///
1080/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
1081/// which is what the byte pins are taken under when they name it.
1082fn rdoq_on() -> bool {
1083 static ENV: std::sync::LazyLock<Option<bool>> =
1084 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0"));
1085 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
1086}
1087
1088/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in
1089/// units of one squared AC quantiser step -- the search's own
1090/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency.
1091///
1092/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`],
1093/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock
1094/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here:
1095/// corner-cut, ceiling = a superblock the temporal map weighs away from the
1096/// frame average has its coefficients optimised at the frame's weight. The
1097/// upgrade is one `lambda` field on the trial call sites, which is the whole
1098/// mode-search argument list.
1099///
1100/// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom
1101/// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above
1102/// the mode search's own weight, and it is the same multiplier on all three
1103/// rows:
1104///
1105/// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen |
1106/// |---|---|---|---|
1107/// | 0.7 | +27.6 | +39.5 | +29.6 |
1108/// | 1.0 | +26.3 | +37.5 | +29.1 |
1109/// | 1.3 | +25.6 | +37.0 | +28.8 |
1110/// | 1.6 | +24.6 | +35.9 | +28.7 |
1111/// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 |
1112/// | 3.2 | +24.7 | +36.1 | +29.4 |
1113///
1114/// A coefficient's rate is worth twice here what the mode search prices it
1115/// at, and the likeliest reason is that the price is taken against tables
1116/// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded
1117/// late in a frame whose `txb_skip`/`base` tables have narrowed really costs
1118/// less than the pricer says, and this pass is the one decision taken per
1119/// COEFFICIENT, so it feels that error most. The honest fix is an adapted
1120/// price, not a fitted multiplier; this is the fitted multiplier, and its
1121/// bowl is measured rather than assumed.
1122const RDOQ_LAMBDA_MULT: f64 = 2.2;
1123
1124/// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term
1125/// calibration sweep).
1126fn rdoq_lambda() -> f64 {
1127 static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
1128 crate::envflags::var("EC_AV1_RDOQ_LAMBDA")
1129 .ok()
1130 .and_then(|v| v.parse().ok())
1131 .unwrap_or(RDOQ_LAMBDA_MULT)
1132 });
1133 lambda_scale() * *MULT
1134}
1135
1136/// [`B64_ROOT`], or what `EC_AV1_B64` names.
1137fn b64_root() -> bool {
1138 static ENV: std::sync::LazyLock<Option<bool>> =
1139 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0"));
1140 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
1141}
1142
1143/// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched
1144/// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64
1145/// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner)
1146/// and one TX_32X32 per chroma plane -- and compared against the four 32x32
1147/// quadrants at the same lambda, exactly the shape the inter root
1148/// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to
1149/// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`);
1150/// nothing produced one, so the key frame -- 21.6% of a real film stream --
1151/// coded every superblock split while libaom and rav1e leave 45-54% of theirs
1152/// whole.
1153///
1154/// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on
1155/// it), no filter intra (`filter_intra_size_class` has no 64 row) and no
1156/// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32
1157/// level grid, so only depth 0 is representable) -- the root is refused
1158/// outright on an `allow_intrabc` frame, whose quadrant searches carry DV
1159/// state a discarded trial would desync.
1160///
1161/// Switched off by `EC_AV1_I64=0` in any build.
1162pub(crate) const I64_ROOT: bool = true;
1163
1164/// How many key-frame superblocks were coded as one 64x64 intra block since
1165/// the last [`take_i64_root_hits`], so a gate reports the fire rate rather
1166/// than assuming it (class `gate-blind-to-feature`).
1167/// Index 1 is how many were OFFERED the trial at all, so a gate reads a
1168/// SHARE and not a bare count, and index 2 how many of the whole ones sat on
1169/// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the
1170/// `gate-blind-to-feature` guard for the edge path, which no
1171/// superblock-aligned clip fires at all.
1172static I64_HITS: [std::sync::atomic::AtomicUsize; 3] =
1173 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
1174
1175/// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the
1176/// last call, and zero them.
1177pub fn take_i64_root_hits() -> [usize; 3] {
1178 std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1179}
1180
1181/// [`I64_ROOT`], or what `EC_AV1_I64` names.
1182fn i64_root() -> bool {
1183 static ENV: std::sync::LazyLock<Option<bool>> =
1184 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0"));
1185 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
1186}
1187
1188/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
1189/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
1190/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
1191/// lane-b64 shipped, so the two can be measured against each other on the
1192/// same build.
1193///
1194/// MEASURED on the native gate (two arms of one build, baseline reproduced to
1195/// the tenth): both film rows improve on both columns -- film A
1196/// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and
1197/// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's
1198/// +-0.3 screen clause. So the caller gates this off on a screen frame
1199/// (`allow_screen_content_tools`), the same content gate the coding pyramid
1200/// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm
1201/// already codes them for nothing, and a residual there only spends bits the
1202/// intra/palette tools would have spent better.
1203///
1204/// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` +
1205/// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on:
1206///
1207/// | | skip-only | + residual |
1208/// |---|---|---|
1209/// | 64x64 share, all frames | 36.4% | 38.3% |
1210/// | 64x64 share, leaf frames | 53.3% | 56.0% |
1211/// | skip area, all frames | 80.4% | 78.8% |
1212/// | skip area, leaf frames | 90.2% | 88.5% |
1213/// | stream bytes | 34,366 | 34,295 |
1214/// | encoder wall | 13.4s | 9.6s |
1215///
1216/// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the
1217/// TX_64X64 coefficients are really being coded. The root wins MORE often
1218/// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is
1219/// 45.2%), which is also why the arm is 28% FASTER despite costing three more
1220/// transforms per superblock: a root that wins is four quadrant searches that
1221/// never run.
1222fn b64_residual() -> bool {
1223 static ENV: std::sync::LazyLock<Option<bool>> =
1224 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0"));
1225 ENV.unwrap_or(true) && b64_root()
1226}
1227
1228/// How many 64x64 roots came out cheaper with a residual than skipped, since
1229/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
1230/// rather than assuming one (class `gate-blind-to-feature`).
1231static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1232
1233/// The non-skip 64x64-root count since the last call, and zero it.
1234pub fn take_b64_residual_hits() -> usize {
1235 B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1236}
1237
1238/// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the
1239/// `LAST` + extra-reference pairs the 32x32 level already offers, at the
1240/// three modes a root can form without a second 64x64 motion search --
1241/// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half
1242/// is the vector `search_skip_64`'s own single-reference search already
1243/// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own
1244/// `NEWMV` vector, which only a second search per superblock produces -- the
1245/// wall this root exists to save -- so they are not offered here.
1246///
1247/// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
1248fn b64_compound() -> bool {
1249 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1250 crate::envflags::var("EC_AV1_B64COMP")
1251 .ok()
1252 .map(|v| v != "0")
1253 });
1254 ENV.unwrap_or(true) && b64_root()
1255}
1256
1257/// How many 64x64 roots took a COMPOUND candidate since the last
1258/// [`take_b64_compound_hits`] (class `gate-blind-to-feature`).
1259static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1260
1261/// The compound 64x64-root count since the last call, and zero it.
1262pub fn take_b64_compound_hits() -> usize {
1263 B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1264}
1265
1266/// Whether a 64x64 root that codes a residual may SPLIT its luma transform
1267/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by
1268/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by
1269/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because
1270/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose
1271/// residual has detail in the other three quadrants cannot code it at all.
1272///
1273/// Off by `EC_AV1_B64VARTX=0`.
1274fn b64_var_tx() -> bool {
1275 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1276 crate::envflags::var("EC_AV1_B64VARTX")
1277 .ok()
1278 .map(|v| v != "0")
1279 });
1280 ENV.unwrap_or(true) && b64_root()
1281}
1282
1283/// How many 64x64 roots split their luma transform since the last
1284/// [`take_b64_var_tx_hits`].
1285static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1286
1287/// The split-luma 64x64-root count since the last call, and zero it.
1288pub fn take_b64_var_tx_hits() -> usize {
1289 B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1290}
1291
1292/// Whether a superblock the true frame edge CUTS THROUGH may be left whole
1293/// (lane-b64b). AV1 asks only that the block's own half is inside
1294/// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already
1295/// codes that case; what was missing was a trial whose SSE is scored over the
1296/// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse)
1297/// instead of over the padding the encoder
1298/// invented past the edge. Both gate films are superblock-aligned, so this
1299/// only reaches the user's own arbitrary export sizes.
1300///
1301/// Off by `EC_AV1_B64EDGE=0`.
1302fn b64_edge() -> bool {
1303 edge_root_enabled() && b64_root()
1304}
1305
1306/// What `EC_AV1_B64EDGE` names on its own, without the inter root's own
1307/// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag
1308/// but is gated by [`i64_root`].
1309fn edge_root_enabled() -> bool {
1310 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1311 crate::envflags::var("EC_AV1_B64EDGE")
1312 .ok()
1313 .map(|v| v != "0")
1314 });
1315 ENV.unwrap_or(true)
1316}
1317
1318/// How many 64x64 roots the frame edge cut through since the last
1319/// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are
1320/// superblock-aligned, so nothing but a synthetic size fires this).
1321static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1322
1323/// The edge 64x64-root count since the last call, and zero it.
1324pub fn take_b64_edge_hits() -> usize {
1325 B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1326}
1327
1328/// Whether the encoder searches loop restoration at all (spec 7.17): one
1329/// Wiener filter per 64x64 luma restoration unit, picked from
1330/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
1331/// test build, like [`lambda_scale`].
1332pub(crate) const RESTORATION: bool = true;
1333
1334/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
1335fn restoration_enabled() -> bool {
1336 match std::env::var("EC_AV1_LR").ok() {
1337 Some(v) if cfg!(test) => v != "0",
1338 _ => crate::speed::at(&crate::speed::RESTORATION),
1339 }
1340}
1341
1342/// libaom's `partition_search_breakout` shape: how many non-zero luma
1343/// coefficients per 256 luma samples a block may code and still be judged
1344/// well enough predicted that the split below it is not worth trying. `0`
1345/// disables the breakout (only the existing all-skip prune applies), which
1346/// is the default until the sweep below justifies otherwise.
1347///
1348/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
1349/// is where this lane's wall would have gone: 1 cuts the three clips'
1350/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
1351/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
1352/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
1353/// encoder's inter quality lives, so `0` ships and the knob stays for a
1354/// future explicit speed preset.
1355pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
1356
1357/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
1358/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
1359/// out under `threshold * lambda` is not offered the split at all, and a
1360/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
1361/// always, as before this lever.
1362///
1363/// The census is what points here: the split trial runs on nearly every
1364/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
1365/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
1366/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
1367/// points, so the gate has to read the block's own RD cost, not its levels.
1368///
1369/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
1370/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
1371/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
1372/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
1373/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
1374/// the largest threshold whose BD stays inside the +0.3 keep rule on every
1375/// clip.
1376/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
1377/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
1378/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
1379/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
1380/// the screen wall). Neither clears the keep rule; 0.125 stays.
1381pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
1382
1383/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
1384fn split_rd_threshold() -> f64 {
1385 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
1386 crate::envflags::var("EC_AV1_SPLIT_RD")
1387 .ok()
1388 .and_then(|v| v.parse().ok())
1389 });
1390 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
1391}
1392
1393/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
1394/// [`split_rd_threshold`] withholds the split trial.
1395fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
1396 split_rd_breakout_at(split_rd_threshold(), cost, side, lambda)
1397}
1398
1399/// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own
1400/// early-out reads.
1401fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool {
1402 t > 0.0 && cost < t * lambda * (side * side) as f64
1403}
1404
1405/// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`]
1406/// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64).
1407///
1408/// The 32x32 level is allowed to loosen its breakout with the speed preset
1409/// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured
1410/// what that does one size up: at 0.5 a whole superblock is taken at 64x64
1411/// without its four quadrants ever being searched, and film B goes
1412/// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the
1413/// same per-pixel threshold withholds four times as much search -- the
1414/// preset's step is priced for the 32 level and does not carry up here.
1415fn b64_breakout_threshold() -> f64 {
1416 split_rd_threshold().min(SPLIT_RD_THRESHOLD)
1417}
1418
1419/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
1420/// build.
1421fn split_breakout_coeffs() -> usize {
1422 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
1423 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
1424 _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
1425 }
1426}
1427
1428/// How often each partition decision was taken since the last
1429/// [`take_partition_hits`], so a gate can report how often a new partition
1430/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
1431/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
1432/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
1433static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
1434 std::sync::atomic::AtomicUsize::new(0),
1435 std::sync::atomic::AtomicUsize::new(0),
1436 std::sync::atomic::AtomicUsize::new(0),
1437 std::sync::atomic::AtomicUsize::new(0),
1438];
1439
1440/// Records one such decision.
1441fn partition_hit(which: usize) {
1442 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1443}
1444
1445/// Takes (and clears) the counts.
1446#[cfg(test)]
1447pub(crate) fn take_partition_hits() -> [usize; 4] {
1448 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1449}
1450
1451/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
1452/// rate-distortion trials the block search actually runs, by kind, and where
1453/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
1454/// default, and a measurement build rather than a speed one -- the census
1455/// runs the SAD pre-pass the unpruned search otherwise skips.
1456pub fn census_on() -> bool {
1457 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1458 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
1459}
1460
1461/// What each [`CENSUS`] counter counts.
1462pub const CENSUS_KINDS: [&str; 11] = [
1463 "intra blocks searched (key frame + inter leaves)",
1464 "intra luma mode trials",
1465 "chroma searches",
1466 "chroma mode trials (each = 2 plane trials)",
1467 "tx-depth trials (transform units, depth >= 1)",
1468 "inter 32x32 blocks searched",
1469 "inter block intra-mode trials",
1470 "inter mv candidates (each = 3 mc trials)",
1471 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
1472 " of those, intra won",
1473 " of those, the NEARESTMV trial coded no residual",
1474];
1475
1476/// The census counters themselves, indexed by [`CENSUS_KINDS`].
1477static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
1478 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
1479
1480/// Where the RD winner sat in the SAD ranking, for the luma intra search and
1481/// the chroma mode search -- what says whether a top-N prune would have kept
1482/// the block the search actually chose.
1483static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
1484 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
1485static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
1486 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1487
1488fn census_add(kind: usize, n: usize) {
1489 if census_on() {
1490 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
1491 }
1492}
1493
1494/// Reads (and clears) the census, so a driver can attribute it to its own encode.
1495pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
1496 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
1497 (
1498 std::array::from_fn(|i| take(&CENSUS[i])),
1499 std::array::from_fn(|i| take(&LUMA_RANK[i])),
1500 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
1501 )
1502}
1503
1504/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
1505/// first -- the census's one shared rule, so the luma and chroma histograms
1506/// mean the same thing.
1507fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
1508 scored
1509 .iter()
1510 .filter(|&&(score, mode)| {
1511 mode != winner
1512 && score
1513 < scored
1514 .iter()
1515 .find(|&&(_, m)| m == winner)
1516 .map_or(f64::INFINITY, |&(s, _)| s)
1517 })
1518 .count()
1519}
1520
1521/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
1522/// four cost less. Set from the measurement in the lane report.
1523const SPLIT_BLOCKS: bool = true;
1524
1525/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
1526/// by calling [`encode_key_frame_inner`] both ways.
1527pub(crate) fn split_blocks() -> bool {
1528 SPLIT_BLOCKS
1529}
1530
1531/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
1532/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
1533/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
1534/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
1535/// stream's decode output actually carries 10-bit precision instead of
1536/// silently losing its low 2 bits). The encoder only ever produces values in
1537/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
1538/// decision); `Plane::source` narrows right back to `u8` at its two
1539/// construction sites, a lossless round trip for that range.
1540#[derive(Clone, Debug, PartialEq, Eq)]
1541pub struct Picture {
1542 /// The picture's width in luma samples.
1543 pub width: usize,
1544 /// Its height in luma samples.
1545 pub height: usize,
1546 /// The luma plane, `width * height` samples in raster order.
1547 pub y: Vec<u16>,
1548 /// The U plane: half the width, and the frame's own chroma height -- a
1549 /// quarter of the luma samples at 4:2:0, half at 4:2:2, all of them at
1550 /// 4:4:4. A consumer that only knows the luma size reads the chroma
1551 /// format off this sample count (see `decode::ref_chroma_shape`).
1552 pub u: Vec<u16>,
1553 /// The V plane, the same shape as U.
1554 pub v: Vec<u16>,
1555}
1556
1557impl Picture {
1558 /// A mid-grey picture of the given size.
1559 #[must_use]
1560 pub fn grey(width: usize, height: usize) -> Self {
1561 Self {
1562 width,
1563 height,
1564 y: vec![128; width * height],
1565 u: vec![128; width * height / 4],
1566 v: vec![128; width * height / 4],
1567 }
1568 }
1569
1570 pub(crate) fn check(&self) -> Result<()> {
1571 if self.width == 0
1572 || !self.width.is_multiple_of(BLOCK)
1573 || !self.height.is_multiple_of(BLOCK)
1574 || !self.height.is_multiple_of(BLOCK)
1575 {
1576 return Err(Error::unsupported(
1577 "AV1 encode",
1578 "the picture must be a whole number of 32x32 blocks in each direction",
1579 ));
1580 }
1581 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1582 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1583 return Err(Error::unsupported(
1584 "AV1 encode",
1585 "each plane must carry one sample per position at 4:2:0",
1586 ));
1587 }
1588 Ok(())
1589 }
1590
1591 /// What the public entry points require of the picture they are handed,
1592 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
1593 /// needs a whole chroma sample per two luma ones) and one sample per
1594 /// position on each plane.
1595 pub(crate) fn check_even(&self) -> Result<()> {
1596 if self.width == 0
1597 || self.height == 0
1598 || !self.width.is_multiple_of(2)
1599 || !self.height.is_multiple_of(2)
1600 {
1601 return Err(Error::unsupported(
1602 "AV1 encode",
1603 "the picture's width and height must each be even and nonzero",
1604 ));
1605 }
1606 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1607 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1608 return Err(Error::unsupported(
1609 "AV1 encode",
1610 "each plane must carry one sample per position at 4:2:0",
1611 ));
1612 }
1613 Ok(())
1614 }
1615
1616 /// This picture, padded by edge replication to the next whole number of
1617 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
1618 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
1619 /// sequence (what the inter tile writer's partition needs on top of
1620 /// that). Identity (a plain clone, not a copy through the replication
1621 /// loop) when the picture is already that size — the multiple-of-32 (or
1622 /// -64) fast path is unchanged.
1623 pub(crate) fn padded_to(&self, align: usize) -> Picture {
1624 let padded_width = self.width.next_multiple_of(align);
1625 let padded_height = self.height.next_multiple_of(align);
1626 if padded_width == self.width && padded_height == self.height {
1627 return self.clone();
1628 }
1629 Picture {
1630 width: padded_width,
1631 height: padded_height,
1632 y: pad_plane(
1633 &self.y,
1634 self.width,
1635 self.height,
1636 padded_width,
1637 padded_height,
1638 ),
1639 u: pad_plane(
1640 &self.u,
1641 self.width / 2,
1642 self.height / 2,
1643 padded_width / 2,
1644 padded_height / 2,
1645 ),
1646 v: pad_plane(
1647 &self.v,
1648 self.width / 2,
1649 self.height / 2,
1650 padded_width / 2,
1651 padded_height / 2,
1652 ),
1653 }
1654 }
1655}
1656
1657/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
1658/// (8-bit only, unchanged this round -- widening the encoder is out of this
1659/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
1660/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
1661/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
1662/// content (every value fits both ways), so this changes no encoder output.
1663#[allow(clippy::too_many_arguments)]
1664fn intra_predict_u8(
1665 mode: u8,
1666 angle_delta: i32,
1667 above: Option<&[u8]>,
1668 left: Option<&[u8]>,
1669 corner: Option<u8>,
1670 bw: usize,
1671 bh: usize,
1672 enable_edge_filter: bool,
1673 smooth_neighbor: bool,
1674 dst: &mut [u8],
1675 fctx: &crate::decode::FrameCtx,
1676) {
1677 // Three heap allocations per call became three stack buffers: this runs
1678 // once per mode per trial, and an edge is at most `bw + bh` samples while
1679 // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's
1680 // 64x64 intra root predicts through here too, and reads up to `2 * bw`
1681 // samples above).
1682 let mut above_buf = [0u16; 2 * SUPERBLOCK];
1683 let mut left_buf = [0u16; 2 * SUPERBLOCK];
1684 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
1685 // trial of every block, and a 4x4 block writes 32 bytes of it. The
1686 // predictor fills every sample it is handed, so the zeros are dead
1687 // either way -- size the scratch to the block instead of to the largest
1688 // block there is.
1689
1690 let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| {
1691 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1692 *d = u16::from(v);
1693 }
1694 };
1695 if let Some(s) = above {
1696 widen(s, &mut above_buf);
1697 }
1698 if let Some(s) = left {
1699 widen(s, &mut left_buf);
1700 }
1701 let above16 = above.map(|s| &above_buf[..s.len()]);
1702 let left16 = left.map(|s| &left_buf[..s.len()]);
1703 let mut run = |dst16: &mut [u16]| {
1704 crate::intra::predict(
1705 mode,
1706 angle_delta,
1707 above16,
1708 left16,
1709 corner.map(u16::from),
1710 bw,
1711 bh,
1712 enable_edge_filter,
1713 smooth_neighbor,
1714 dst16,
1715 fctx,
1716 );
1717 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
1718 *d = s as u8;
1719 }
1720 };
1721 let n = bw * bh;
1722 if n <= 64 {
1723 run(&mut [0u16; 64][..n]);
1724 } else if n <= 256 {
1725 run(&mut [0u16; 256][..n]);
1726 } else if n <= BLOCK * BLOCK {
1727 run(&mut [0u16; BLOCK * BLOCK][..n]);
1728 } else {
1729 run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]);
1730 }
1731}
1732
1733/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
1734/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
1735/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
1736fn filter_intra_predict_u8(
1737 mode: usize,
1738 above: Option<&[u8]>,
1739 left: Option<&[u8]>,
1740 corner: Option<u8>,
1741 side: usize,
1742 dst: &mut [u8],
1743 fctx: &crate::decode::FrameCtx,
1744) {
1745 let mut above_buf = [0u16; 2 * BLOCK];
1746 let mut left_buf = [0u16; 2 * BLOCK];
1747 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
1748 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1749 *d = u16::from(v);
1750 }
1751 };
1752 if let Some(a) = above {
1753 widen(a, &mut above_buf);
1754 }
1755 if let Some(l) = left {
1756 widen(l, &mut left_buf);
1757 }
1758 let mut dst16 = [0u16; BLOCK * BLOCK];
1759 let n = side * side;
1760 crate::intra::predict_filter_intra(
1761 mode,
1762 above.map(|a| &above_buf[..a.len()]),
1763 left.map(|l| &left_buf[..l.len()]),
1764 corner.map(u16::from),
1765 side,
1766 side,
1767 &mut dst16[..n],
1768 fctx,
1769 );
1770 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
1771 *d = v as u8;
1772 }
1773}
1774
1775/// Pads one plane to `(padded_width, padded_height)` by repeating its last
1776/// row and column, so the block coder always sees a whole number of blocks.
1777/// [`crop_plane`] undoes this on the way back out.
1778fn pad_plane<T: Copy + Default>(
1779 source: &[T],
1780 width: usize,
1781 height: usize,
1782 padded_width: usize,
1783 padded_height: usize,
1784) -> Vec<T> {
1785 let mut out = vec![T::default(); padded_width * padded_height];
1786 for row in 0..padded_height {
1787 let src = source[row.min(height - 1) * width..][..width].as_ref();
1788 let dst = &mut out[row * padded_width..][..padded_width];
1789 dst[..width].copy_from_slice(src);
1790 dst[width..].fill(src[width - 1]);
1791 }
1792 out
1793}
1794
1795/// The top-left `width` x `height` region of a plane that is `padded_width`
1796/// wide, which is the render-size crop [`Picture::padded`]'s replication
1797/// exists to let a decoder undo.
1798fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
1799 let mut out = Vec::with_capacity(width * height);
1800 for row in 0..height {
1801 out.extend_from_slice(&source[row * padded_width..][..width]);
1802 }
1803 out
1804}
1805
1806/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
1807/// region a decoder produces, which is the public contract for what a caller
1808/// sees back — the padded planes the encoder coded against never leave this
1809/// module. Identity when the reconstruction is already that size.
1810pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1811 let reconstruction = &encoded.reconstruction;
1812 let cropped = if reconstruction.width == width && reconstruction.height == height {
1813 reconstruction.clone()
1814 } else {
1815 Picture {
1816 width,
1817 height,
1818 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1819 u: crop_plane(
1820 &reconstruction.u,
1821 reconstruction.width / 2,
1822 width / 2,
1823 height / 2,
1824 ),
1825 v: crop_plane(
1826 &reconstruction.v,
1827 reconstruction.width / 2,
1828 width / 2,
1829 height / 2,
1830 ),
1831 }
1832 };
1833 Encoded {
1834 stream: encoded.stream.clone(),
1835 modes: encoded.modes.clone(),
1836 inter_block_share: encoded.inter_block_share,
1837 reconstruction: cropped,
1838 tile: encoded.tile.clone(),
1839 mi_cols: encoded.mi_cols,
1840 mi_rows: encoded.mi_rows,
1841 base_q_idx: encoded.base_q_idx,
1842 tx_select: encoded.tx_select,
1843 switchable_motion_mode: encoded.switchable_motion_mode,
1844 screen: encoded.screen,
1845 reduced_tx_set: encoded.reduced_tx_set,
1846 start_cdfs: encoded.start_cdfs.clone(),
1847 next_cdfs: encoded.next_cdfs.clone(),
1848 loop_filter: encoded.loop_filter,
1849 loop_restoration: encoded.loop_restoration,
1850 allow_intrabc: encoded.allow_intrabc,
1851 delta: encoded.delta.clone(),
1852 cdef: encoded.cdef,
1853 }
1854}
1855
1856/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1857/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1858#[derive(Clone)]
1859pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1860
1861impl std::fmt::Debug for CdfSnapshot {
1862 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1863 f.write_str("CdfSnapshot")
1864 }
1865}
1866
1867/// What one call to [`encode_key_frame`] produced.
1868#[derive(Clone, Debug)]
1869pub struct Encoded {
1870 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1871 /// OBU carrying one tile.
1872 pub stream: Vec<u8>,
1873 /// What a decoder will produce from `stream` — the encoder's own
1874 /// reconstruction, which its prediction was built on.
1875 pub reconstruction: Picture,
1876 /// The luma intra mode each block was coded under, in the order the blocks
1877 /// are coded — raster order among the quadrants of each superblock, and
1878 /// among the four 16x16 blocks of a quadrant that was split.
1879 pub modes: Vec<u8>,
1880 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1881 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1882 /// for a key frame, which has no such choice — so a caller can tell a
1883 /// frame with no motion worth coding from one that never got the chance.
1884 pub inter_block_share: f64,
1885 /// The tile payload alone, undecorated by any OBU framing, and the frame
1886 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1887 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1888 /// off the wire by parsing `stream`'s OBUs instead.
1889 pub(crate) tile: Vec<u8>,
1890 pub(crate) mi_cols: u32,
1891 pub(crate) mi_rows: u32,
1892 pub(crate) base_q_idx: u8,
1893 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1894 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1895 /// and reading it off `stream`'s header is what `decode_stream` does. A
1896 /// test that decodes `tile` directly must pass this one along, or it reads
1897 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1898 /// block.
1899 pub(crate) tx_select: bool,
1900 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1901 /// bit that makes every eligible single-reference inter block carry a
1902 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1903 /// decoding `tile` directly must pass it along or it desyncs at the
1904 /// first eligible block.
1905 pub(crate) switchable_motion_mode: bool,
1906 /// The CDF state this frame's tile writer started from -- the defaults
1907 /// for a key frame and for the first inter frame, and the previous
1908 /// frame's stored tables after that. A test that decodes `tile` directly
1909 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1910 /// the frame's `primary_ref_frame` slot holds (same class as
1911 /// `tx_select`: a header bit a raw tile decode cannot guess).
1912 pub(crate) start_cdfs: CdfSnapshot,
1913 /// What this frame stores into the slots it refreshes (spec 7.20,
1914 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1915 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1916 /// started from when it is on.
1917 pub(crate) next_cdfs: CdfSnapshot,
1918 /// This frame header's chosen deblocking parameters
1919 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1920 /// picture the decoder produces UNDER them, so a test that decodes
1921 /// `tile` directly must pass these along, exactly as it must `tx_select`
1922 /// (class: test asserts against a stale header).
1923 pub(crate) loop_filter: LoopFilterParams,
1924 /// This frame header's chosen CDEF parameters, threaded for the same
1925 /// reason as `loop_filter`.
1926 pub(crate) cdef: CdefParams,
1927 /// This frame header's `allow_screen_content_tools`
1928 /// ([`screen_content`]) -- every intra block of the tile carries the two
1929 /// palette-mode symbols under it, so a raw tile decode that guessed
1930 /// `false` would desync at the first block (same class as `tx_select`).
1931 pub(crate) screen: bool,
1932 /// This frame header's own `reduced_tx_set` (spec 5.9.2) -- the bit that
1933 /// picks the inter `tx_type` alphabets AND, on an inter block, the
1934 /// allowance the chroma transform's inherited type reduces against
1935 /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). A raw tile
1936 /// decode that guesses `true` here mis-derives every inherited chroma
1937 /// type on a `reduced_tx_set = 0` frame (lane-intertx; same class as
1938 /// `tx_select`/`screen` above).
1939 pub(crate) reduced_tx_set: bool,
1940 /// This frame header's chosen loop restoration parameters, threaded for
1941 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1942 /// filters themselves are coded in `tile`, so a decode of it under a
1943 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1944 pub(crate) loop_restoration: LoopRestorationParams,
1945 /// This frame header's `allow_intrabc` -- every intra block of the tile
1946 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1947 /// guessed `false` would desync at the first block (same class as
1948 /// `screen`/`tx_select`).
1949 pub(crate) allow_intrabc: bool,
1950 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1951 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1952 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1953 /// decode that guessed the defaults desyncs at the first superblock
1954 /// (same class as `screen`/`tx_select`).
1955 pub(crate) delta: ec_av1_syntax::DeltaParams,
1956}
1957
1958thread_local! {
1959 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
1960 /// for on the last key frame encoded on this thread -- read by the gates,
1961 /// which print it beside the block counts (class `gate-blind-to-feature`).
1962 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
1963}
1964
1965/// [`IBC_SHARE`] for the last key frame encoded on this thread.
1966#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1967pub(crate) fn intrabc_source_share() -> f64 {
1968 IBC_SHARE.with(std::cell::Cell::get)
1969}
1970
1971thread_local! {
1972 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
1973 /// header offers the per-frame `allow_screen_content_tools` bit at all.
1974 /// Armed once by the key frame ([`encode_key_frame_inner`], from
1975 /// [`screen_content`]) and read by every header builder after it, so that
1976 /// the inter frames of a screen sequence lay their headers out the same
1977 /// way the sequence header the key frame wrote says they do -- a per-call
1978 /// parameter would have to thread through `inter_frame_headers`' four
1979 /// public entry points and every hand-built-stream test that calls them.
1980 /// A sequence with no screen content leaves this false and writes exactly
1981 /// the bits it wrote before this lane.
1982 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1983}
1984
1985thread_local! {
1986 /// Overrides [`screen_content`] for the calling thread, which is what the
1987 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
1988 /// codes every block losslessly, so both arms of a mode ablation reach
1989 /// infinite PSNR and the ablation measures nothing at all (the
1990 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
1991 /// variable cannot do this -- the tests run in one process, in parallel.
1992 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1993}
1994
1995thread_local! {
1996 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
1997 /// under, AFTER the content gate: the pyramid, or `None` for a stream
1998 /// that stayed flat. Read by the BD gates, which print the requested and
1999 /// the effective pyramid side by side -- a screen clip requests one and
2000 /// codes flat, and that difference is the gate (class
2001 /// `gate-blind-to-feature`).
2002 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
2003 const { std::cell::Cell::new(None) };
2004}
2005
2006/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
2007#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2008pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
2009 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
2010}
2011
2012#[cfg(test)]
2013pub(crate) fn force_screen(value: Option<bool>) {
2014 SCREEN_FORCE.with(|c| c.set(value));
2015}
2016
2017// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
2018// ablation can measure the mode search alone. Setting it also clears the
2019// sequence header's own `enable_filter_intra` bit, so the stream the arm
2020// writes is exactly the one this encoder wrote before the lane.
2021#[cfg(test)]
2022thread_local! {
2023 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2024}
2025
2026#[cfg(test)]
2027pub(crate) fn force_filter_intra(value: Option<bool>) {
2028 FILTER_INTRA_FORCE.with(|c| c.set(value));
2029}
2030
2031pub(crate) fn arm_seq_screen(on: bool) {
2032 SEQ_SCREEN.with(|c| c.set(on));
2033}
2034
2035fn seq_screen() -> bool {
2036 SEQ_SCREEN.with(std::cell::Cell::get)
2037}
2038
2039/// How many distinct colours a 16x16 luma block may hold and still count as
2040/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
2041/// `av1_set_screen_content_options` bound is 4, which separates nothing on
2042/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
2043/// the variance floor below on the five gate clips at BOTH the native crop
2044/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
2045/// the frame is the widest-margin split of those ten rows -- every
2046/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
2047/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
2048/// native and 17.9% scaled.
2049fn screen_colors() -> usize {
2050 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2051 *N.get_or_init(|| {
2052 std::env::var("EC_AV1_SCREEN_COLORS")
2053 .ok()
2054 .and_then(|v| v.parse().ok())
2055 .unwrap_or(16)
2056 })
2057}
2058
2059/// The reciprocal of the frame area those blocks must cover, in tenths --
2060/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
2061/// 8 (an eighth) is the midpoint of the two populations
2062/// `probe_screen_detect` measures at the colour bound and variance floor
2063/// around it. `EC_AV1_SCREEN_PCT`.
2064fn screen_pct() -> usize {
2065 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2066 *N.get_or_init(|| {
2067 std::env::var("EC_AV1_SCREEN_PCT")
2068 .ok()
2069 .and_then(|v| v.parse().ok())
2070 .unwrap_or(10)
2071 })
2072}
2073
2074/// The per-pixel variance a few-colour block must clear before it counts as
2075/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
2076/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
2077/// a smooth dark film frame is all few-colour blocks and reads as a desktop
2078/// capture -- which is exactly what this detector did until 2026-09-07, when
2079/// it called BOTH real films screen content on 48/48 frames, priced every
2080/// coefficient against the default CDFs and ran the palette search over
2081/// film. `probe_screen_detect`: at 16 colours the floor takes both films
2082/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
2083/// 23.6%.
2084fn screen_var() -> u64 {
2085 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
2086 *N.get_or_init(|| {
2087 std::env::var("EC_AV1_SCREEN_VAR")
2088 .ok()
2089 .and_then(|v| v.parse().ok())
2090 .unwrap_or(16)
2091 })
2092}
2093
2094/// How many frames [`screen_content`] said yes/no to, so a gate can print
2095/// whether the detector fired at all (class `gate-blind-to-feature`).
2096pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
2097 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2098
2099/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
2100/// the distinct colours of every 16x16 block and turn the screen-content
2101/// tools on when the blocks holding between 2 and [`screen_colors`] of them
2102/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
2103/// frame. `width` is the plane's
2104/// stride, `true_*` the frame's real (decodable) extent.
2105fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
2106 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
2107 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2108 return forced;
2109 }
2110 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
2111 let on = v != "0";
2112 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2113 return on;
2114 }
2115 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
2116 let mut counted = 0usize;
2117 for by in (0..true_height).step_by(blk) {
2118 for bx in (0..true_width).step_by(blk) {
2119 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
2120 let mut seen = [false; 256];
2121 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
2122 for row in 0..h {
2123 for col in 0..w {
2124 let v = y[(by + row) * width + bx + col];
2125 sum += u64::from(v);
2126 sq += u64::from(v) * u64::from(v);
2127 if !seen[usize::from(v)] {
2128 seen[usize::from(v)] = true;
2129 colors += 1;
2130 }
2131 }
2132 }
2133 // Per-pixel variance over the block's real (edge-clipped) extent.
2134 let n = (h * w) as u64;
2135 let var = (sq - sum * sum / n) / n;
2136 if colors > 1 && colors <= limit && var > floor {
2137 counted += 1;
2138 }
2139 }
2140 }
2141 let on = counted * blk * blk * screen_pct() > true_width * true_height;
2142 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2143 on
2144}
2145
2146/// Whether this SOURCE picture reads as screen content, for a caller that has
2147/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
2148/// gates its coding pyramid on this (a desktop capture keeps the flat
2149/// one-in-one-out structure the BD gate measured it on, camera material takes
2150/// the mini-GOP). The key frame runs the same detector again when it builds
2151/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
2152/// count, so this probe undoes its own tick and leaves the gate prints
2153/// reading one detection per coded frame.
2154pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
2155 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
2156 let on = screen_content(&y, picture.width, picture.width, picture.height);
2157 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2158 on
2159}
2160
2161/// The sequence and frame headers a picture of this size is coded under: one
2162/// tile, one transform size per block, no in-loop filter parameters yet
2163/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
2164/// CDEF strengths in once the tile is coded), no CDF adaptation
2165/// and no tool the tile writer does not code.
2166///
2167/// # Errors
2168/// Returns an error when the picture is larger than the 16-bit frame size the
2169/// sequence header carries.
2170pub fn key_frame_headers(
2171 width: usize,
2172 height: usize,
2173 base_q_idx: u8,
2174) -> Result<(SequenceHeader, FrameHeader)> {
2175 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
2176}
2177
2178/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
2179/// studio (limited) range: what this crate's sequence header carried before
2180/// [`crate::encoder`]'s facade could configure it, and what
2181/// [`key_frame_headers`] still asks for.
2182fn unspecified_color_config() -> ColorConfig {
2183 ColorConfig {
2184 bit_depth: 8,
2185 mono_chrome: false,
2186 num_planes: 3,
2187 color_primaries: 2,
2188 transfer_characteristics: 2,
2189 matrix_coefficients: 2,
2190 color_range: false,
2191 subsampling_x: 1,
2192 subsampling_y: 1,
2193 chroma_sample_position: ChromaSamplePosition::Unknown,
2194 separate_uv_delta_q: false,
2195 }
2196}
2197
2198/// [`key_frame_headers`] with the sequence header's colour config named
2199/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
2200/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
2201/// which is all a player picks a colour transform from and which
2202/// [`crate::encoder::Colour`] is the facade's own name for.
2203///
2204/// # Errors
2205/// The same as [`key_frame_headers`].
2206pub(crate) fn key_frame_headers_colour(
2207 width: usize,
2208 height: usize,
2209 base_q_idx: u8,
2210 color_config: ColorConfig,
2211) -> Result<(SequenceHeader, FrameHeader)> {
2212 let bits = |n: usize| -> Result<u32> {
2213 let n = u32::try_from(n).map_err(|_| too_large())?;
2214 if n == 0 || n > 1 << 16 {
2215 return Err(too_large());
2216 }
2217 Ok((32 - (n - 1).leading_zeros()).max(1))
2218 };
2219 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
2220 let (w, h) = (width as u32, height as u32);
2221 let seq = SequenceHeader {
2222 seq_profile: 0,
2223 operating_points: vec![OperatingPoint {
2224 seq_level_idx: 8,
2225 ..OperatingPoint::default()
2226 }],
2227 frame_width_bits,
2228 frame_height_bits,
2229 max_frame_width: w,
2230 max_frame_height: h,
2231 use_128x128_superblock: sb128_on(),
2232 // lane-fintra: the encoder's intra search offers the five recursive
2233 // filter-intra modes on eligible blocks, so the sequence bit is set
2234 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
2235 // off and restores the streams this encoder wrote before the lane).
2236 enable_filter_intra: filter_intra_on(),
2237 enable_intra_edge_filter: false,
2238 enable_order_hint: true,
2239 order_hint_bits: 7,
2240 enable_superres: false,
2241 // spec 5.9.19: with the sequence bit set every frame header carries
2242 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
2243 // pair for the whole frame, chosen by `crate::filter_search` -- so no
2244 // `cdef_idx` literal is coded in the tile and a frame that wants no
2245 // CDEF simply carries zero strengths.
2246 enable_cdef: true,
2247 enable_restoration: true,
2248 // SELECT (2) when this sequence's key frame detected screen content
2249 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
2250 // is then coded in every frame header, and only the frames that want
2251 // the palette syntax set it. 0 -- the forced-off form, no bit at all
2252 // -- otherwise, which is what every non-screen stream this encoder
2253 // writes still carries.
2254 seq_force_screen_content_tools: if seq_screen() {
2255 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
2256 } else {
2257 0
2258 },
2259 seq_force_integer_mv: 0,
2260 color_config,
2261 still_picture: false,
2262 reduced_still_picture_header: false,
2263 timing_info: None,
2264 decoder_model_info: None,
2265 initial_display_delay_present_flag: false,
2266 operating_point: 0,
2267 operating_point_idc: 0,
2268 frame_id_numbers_present_flag: false,
2269 delta_frame_id_length: 0,
2270 additional_frame_id_length: 0,
2271 enable_interintra_compound: false,
2272 enable_masked_compound: false,
2273 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
2274 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
2275 // header is byte-identical to the streams before this lane.
2276 enable_warped_motion: warp_on(),
2277 enable_dual_filter: false,
2278 enable_jnt_comp: false,
2279 enable_ref_frame_mvs: false,
2280 film_grain_params_present: false,
2281 };
2282 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
2283 // own (true, unpadded) width and height, not from any block-grid
2284 // alignment — a decoder derives these straight from `frame_width`/
2285 // `frame_height` below, so this must match it exactly.
2286 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
2287 let header = FrameHeader {
2288 frame_type: FrameType::Key,
2289 frame_is_intra: true,
2290 show_frame: true,
2291 error_resilient_mode: true,
2292 // The tile writer keeps the same CDF state the decoder does and
2293 // updates it in the same order, so the frame lets the decoder adapt.
2294 disable_cdf_update: false,
2295 // Nothing reads the state this frame leaves behind: a key frame always
2296 // starts from the defaults, and this encoder emits one frame.
2297 disable_frame_end_update_cdf: true,
2298 force_integer_mv: true,
2299 refresh_frame_flags: 0xFF,
2300 primary_ref_frame: PRIMARY_REF_NONE,
2301 frame_width: w,
2302 frame_height: h,
2303 upscaled_width: w,
2304 render_width: w,
2305 render_height: h,
2306 mi_cols,
2307 mi_rows,
2308 tile_info: TileInfo {
2309 uniform_spacing: true,
2310 cols: 1,
2311 rows: 1,
2312 mi_col_starts: vec![0, mi_cols],
2313 mi_row_starts: vec![0, mi_rows],
2314 tile_size_bytes: 1,
2315 ..TileInfo::default()
2316 },
2317 quantization: QuantizationParams {
2318 base_q_idx,
2319 ..QuantizationParams::default()
2320 },
2321 tx_mode: TxMode::Largest,
2322 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
2323 // intra transform below 32x32, not only 16x16 -- the set this crate
2324 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
2325 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
2326 // so a decoder honouring the header picks the same CDF the writer
2327 // used only if this is set here too, not only on the inter variant
2328 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
2329 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
2330 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
2331 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
2332 // the arithmetic coder's `rng` register from the very first 8x8-leaf
2333 // luma transform onward with no symbol value ever differing.
2334 reduced_tx_set: true,
2335 ..FrameHeader::default()
2336 };
2337 Ok((seq, header))
2338}
2339
2340/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
2341/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
2342/// 1 still holds the key frame however long the GOP runs.
2343pub const GOLDEN_SLOT: u8 = 1;
2344
2345/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
2346/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
2347/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
2348/// one filter for the whole frame, which is what libaom does on this content
2349/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
2350/// stream, so a per-BLOCK filter search has no bits to win). The kernel
2351/// reaches the search, the trials and the recon through
2352/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
2353/// prediction the search priced are the same one.
2354/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the
2355/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
2356/// the witness that has to see a non-REGULAR kernel coded and decoded turns
2357/// it on through this while holding [`crate::speed::knob_write`].
2358static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
2359
2360/// Sets [`INTERP_OVERRIDE`]; `None` clears it.
2361#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
2362pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) {
2363 INTERP_OVERRIDE.store(
2364 filter.map_or(u8::MAX, |f| f as u8),
2365 std::sync::atomic::Ordering::Relaxed,
2366 );
2367}
2368
2369fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
2370 use ec_av1_syntax::InterpolationFilter as F;
2371 match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2372 0 => return F::Eighttap,
2373 1 => return F::EighttapSmooth,
2374 2 => return F::EighttapSharp,
2375 _ => {}
2376 }
2377 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2378 crate::envflags::var("EC_AV1_INTERP")
2379 .ok()
2380 .map(|v| match v.as_str() {
2381 "smooth" => F::EighttapSmooth,
2382 "sharp" => F::EighttapSharp,
2383 _ => F::Eighttap,
2384 })
2385 });
2386 ENV.unwrap_or(F::Eighttap)
2387}
2388
2389/// The frame header for a shown inter frame that predicts from the single
2390/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
2391/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
2392/// reused verbatim: an inter frame never changes the sequence.
2393///
2394/// # Errors
2395/// Returns an error under the same conditions as [`key_frame_headers`].
2396pub fn inter_frame_headers(
2397 width: usize,
2398 height: usize,
2399 base_q_idx: u8,
2400 order_hint: u32,
2401 last_slot: u8,
2402) -> Result<(SequenceHeader, FrameHeader)> {
2403 inter_frame_headers_slots(
2404 width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot,
2405 )
2406}
2407
2408/// [`inter_frame_headers`] with the three slots named apart: the one read as
2409/// `LAST_FRAME`, the one this frame refreshes, and the one read as
2410/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
2411/// so that the frame two back is still intact in the slot this one is about
2412/// to overwrite -- read before write, spec 7.20's decode order.
2413///
2414/// # Errors
2415/// As [`inter_frame_headers`].
2416pub fn inter_frame_headers_slots(
2417 width: usize,
2418 height: usize,
2419 base_q_idx: u8,
2420 order_hint: u32,
2421 last_slot: u8,
2422 self_slot: u8,
2423 altref_slot: u8,
2424) -> Result<(SequenceHeader, FrameHeader)> {
2425 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
2426 let header = FrameHeader {
2427 frame_type: FrameType::Inter,
2428 frame_is_intra: false,
2429 show_frame: true,
2430 error_resilient_mode: false,
2431 disable_cdf_update: false,
2432 // The tile writer hands its end-of-tile tables to the next frame
2433 // (`encode_sequence_with_ctx`), so the frame stores them the way the
2434 // decoder will load them (spec 7.20).
2435 disable_frame_end_update_cdf: false,
2436 force_integer_mv: false,
2437 order_hint,
2438 primary_ref_frame: 0,
2439 refresh_frame_flags: 1 << self_slot,
2440 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
2441 // names the slot this frame both predicts from and refreshes;
2442 // GOLDEN names slot 1, which the key frame wrote when it refreshed
2443 // all eight and which no inter frame ever overwrites, so it holds
2444 // the key frame's own picture for the whole GOP.
2445 ref_frame_idx: {
2446 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
2447 idx[3] = GOLDEN_SLOT;
2448 idx[6] = altref_slot;
2449 idx
2450 },
2451 // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`:
2452 // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's
2453 // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in
2454 // every frame this constructor builds, so no further guard is needed.
2455 allow_high_precision_mv: high_precision_mv_at(base_q_idx),
2456 // A FIXED frame-level filter, so no block codes an `interp_filter`
2457 // symbol. lane-obmc3 instrumented whether that costs anything: a
2458 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
2459 // (45941 B, the same point `lanes/libcen.report.md` matched) read
2460 // back through `EC_AV1_BITCENSUS=1 syntax_census` codes
2461 // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed
2462 // frame filter here too, so there are ZERO per-block filter bits at
2463 // stake on this content and the per-block switchable search was not
2464 // built (the charter's premise that libaom codes switchable interp
2465 // per block on film B is refuted by its own stream).
2466 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
2467 // lane-av1obmc: with this bit set every single-reference inter block
2468 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
2469 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
2470 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
2471 // to the OBMC knob rather than always on: with every block choosing
2472 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
2473 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
2474 // and stays byte-identical to the streams before this lane.
2475 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
2476 // `allow_warped_motion` besides -- which is what makes an eligible
2477 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
2478 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2479 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on(),
2480 allow_warped_motion: warp_on(),
2481 use_ref_frame_mvs: false,
2482 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
2483 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
2484 // set this crate carries a table for at 16x16 (see
2485 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
2486 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
2487 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
2488 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
2489 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
2490 // path) -- with this flag set, `get_tx_set`'s intra branch returns
2491 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
2492 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
2493 reduced_tx_set: true,
2494 ..key
2495 };
2496 Ok((seq, header))
2497}
2498
2499fn too_large() -> Error {
2500 Error::unsupported(
2501 "AV1 encode",
2502 "the picture is larger than a frame size can carry",
2503 )
2504}
2505
2506/// One plane of the picture being coded, and the reconstruction being built
2507/// beside it.
2508/// What one committed 4x4 cell left behind for the coefficient contexts of
2509/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
2510/// is the same state decode.rs records.
2511#[derive(Clone, Copy, Default, PartialEq, Eq)]
2512struct CoefCtx {
2513 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
2514 level: u8,
2515 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
2516 /// the DC itself was zero (tile.rs `dc_vote`).
2517 dc: i8,
2518}
2519
2520/// One plane's coefficient contexts, committed in CODING ORDER: the search
2521/// prices partition TREES, so the neighbour state a candidate reads has to be
2522/// whatever the blocks coded before it left -- the parent's committed
2523/// neighbours for a tree's first child, the just-committed sibling for the
2524/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
2525/// writer's two running bands is what makes that fall out: a trial commits
2526/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
2527/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
2528/// to its left is exactly what the tile writer's `Neighbours` bands will hold
2529/// when it gets there.
2530///
2531/// Before this map the pricer took both contexts as zero, which is exact for
2532/// a luma transform covering its whole block and the largest remaining row of
2533/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
2534#[derive(Default)]
2535struct CoefCtxMap {
2536 cells: Vec<CoefCtx>,
2537 stride: usize,
2538 /// Whether the transforms being priced right now are SMALLER than the
2539 /// block they sit in -- a `TxMode::Select` depth split
2540 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
2541 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
2542 /// trial cannot tell, and it is what decides whether luma reads context 0
2543 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
2544 tu_split: bool,
2545}
2546
2547/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
2548/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
2549/// padding-inclusive score the search used before lane-sse, which is how the
2550/// before/after arms of the straddling gate rows are read off ONE binary.
2551fn edge_sse() -> bool {
2552 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
2553 crate::envflags::var("EC_AV1_EDGESSE")
2554 .ok()
2555 .map(|v| v != "0")
2556 });
2557 ENV.unwrap_or(true)
2558}
2559
2560/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
2561/// through and the share of their raw squared error that sat in the padding
2562/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
2563/// it, but the numbers are an instrument, not a decision (class
2564/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
2565/// without this census no gate row can say the clip fires at all).
2566fn edge_census() -> bool {
2567 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
2568 crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1")
2569 });
2570 *ENV
2571}
2572
2573/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
2574/// 128x128): how many scores clipped, the inside squared error they kept and
2575/// the padding squared error they dropped.
2576static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
2577 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
2578
2579/// One clipped score, for [`take_edge_census`].
2580fn record_edge_score(side: usize, inside: u64, padding: u64) {
2581 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
2582 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2583 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
2584 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
2585}
2586
2587/// The straddling-block census since the last call, and zero it: one
2588/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
2589#[must_use]
2590pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
2591 EDGE_SCORES
2592 .iter()
2593 .enumerate()
2594 .filter_map(|(log2, row)| {
2595 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
2596 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
2597 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
2598 (n != 0).then_some((1usize << log2, n, inside, padding))
2599 })
2600 .collect()
2601}
2602
2603struct Plane<'a> {
2604 source: &'a [u8],
2605 reconstruction: Vec<u8>,
2606 width: usize,
2607 height: usize,
2608 /// The frame's true, decodable extent in this plane's own units --
2609 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
2610 /// not `width`/`height` above, which is the padded coding-surface size.
2611 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
2612 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
2613 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
2614 /// this bound, even though the padded reconstruction buffer holds real
2615 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
2616 /// those instead of stopping here is what desyncs prediction at the true
2617 /// edge.
2618 true_width: usize,
2619 true_height: usize,
2620 /// This plane's own tile's pixel bounds, in this plane's units -- the
2621 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
2622 /// prediction never reaches across a tile edge even though the
2623 /// neighbouring tile's real samples sit right there in the shared
2624 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
2625 /// leaves every edge exactly as it was before tiles existed.
2626 tile_x0: usize,
2627 tile_y0: usize,
2628 tile_x1: usize,
2629 tile_y1: usize,
2630 /// [`CoefCtxMap`]: what the blocks already committed left for the
2631 /// coefficient contexts of the ones still being priced. Sized on the
2632 /// first commit, so a plane literal does not have to know its own extent
2633 /// twice.
2634 ctx: CoefCtxMap,
2635}
2636
2637impl Plane<'_> {
2638 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
2639 /// called at every superblock of the frame-raster search with the rect
2640 /// of the tile that superblock belongs to.
2641 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
2642 self.tile_x0 = x0;
2643 self.tile_y0 = y0;
2644 self.tile_x1 = x1.min(self.width);
2645 self.tile_y1 = y1.min(self.height);
2646 }
2647 /// The reconstructed samples a block at `(x, y)` predicts from: the row
2648 /// above it, the column to its left and the sample between them, each
2649 /// missing where the block sits against an edge of the frame.
2650 ///
2651 /// `reach` says whether the samples above the block's right and below its
2652 /// left are decoded, which is what a directional mode reads into; where
2653 /// they are not, or where the frame ends first, the edge is shorter and
2654 /// the predictor repeats its last sample, exactly as the decoder's clamp
2655 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
2656 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
2657 /// a free per mode per block, on the search's hottest path -- while an
2658 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
2659 /// samples, on the caller's stack.
2660 fn edges_into<'a>(
2661 &self,
2662 x: usize,
2663 y: usize,
2664 side: usize,
2665 reach: Reach,
2666 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
2667 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
2668 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
2669 // Even a block's *own* edge is clamped to the true frame bound, not
2670 // just a `reach` extension: libaom's `av1_predict_intra_block`
2671 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
2672 // this block's own right/bottom to the frame edge -- from
2673 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
2674 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
2675 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
2676 // samples the row/column above/left holds before the decoder starts
2677 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
2678 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
2679 // extent straddles that edge legally (`has_half`) -- the transform
2680 // still covers the whole block, but prediction does not get to read
2681 // real reconstructed pixels past the true edge for its own row/column,
2682 // only for the padded tail it invents.
2683 let own_across = x + side.min(self.true_width.saturating_sub(x));
2684 let across = if reach.above_right {
2685 own_across + side.min(self.true_width.saturating_sub(own_across))
2686 } else {
2687 own_across
2688 }
2689 .min(self.width);
2690 let own_down = y + side.min(self.true_height.saturating_sub(y));
2691 let down = if reach.below_left {
2692 own_down + side.min(self.true_height.saturating_sub(own_down))
2693 } else {
2694 own_down
2695 }
2696 .min(self.height);
2697 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
2698 // whose own origin already sits past the true edge -- only reachable
2699 // through a partition trial priced for comparison on a split this
2700 // frame's straddling quadrant will go on to refuse (see
2701 // `a_picture_off_the_block_grid_is_refused`), never through a block
2702 // this encoder actually commits. Such a block has no true-edge
2703 // samples above or left of it at all, same as `y == 0`/`x == 0`.
2704 let across = across.min(self.tile_x1);
2705 let down = down.min(self.tile_y1);
2706 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
2707 if let Some(n) = above_n {
2708 above_buf[..n].copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
2709 }
2710 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
2711 if let Some(n) = left_n {
2712 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
2713 *d = self.reconstruction[row * self.width + x - 1];
2714 }
2715 }
2716 let corner = (x > self.tile_x0 && y > self.tile_y0)
2717 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
2718 (
2719 above_n.map(|n| &above_buf[..n]),
2720 left_n.map(|n| &left_buf[..n]),
2721 corner,
2722 )
2723 }
2724
2725 /// Codes one block under one mode without committing it: hands back the
2726 /// levels, the block the decoder would reconstruct, the squared error
2727 /// against the source and an estimate of what the levels cost in bits.
2728 fn trial(
2729 &self,
2730 at: At,
2731 mode: u8,
2732 angle_delta: i32,
2733 base_q_idx: u8,
2734 deadzone: f64,
2735 fctx: &crate::decode::FrameCtx,
2736 ) -> Trial {
2737 self.trial_typed(
2738 at,
2739 mode,
2740 angle_delta,
2741 base_q_idx,
2742 deadzone,
2743 TxType::DctDct,
2744 fctx,
2745 )
2746 }
2747
2748 /// [`Self::trial`] under a named transform type -- what an intra chroma
2749 /// block gets, since chroma codes no `tx_type` symbol and the decoder
2750 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
2751 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
2752 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
2753 #[allow(clippy::too_many_arguments)]
2754 /// Sum of absolute differences between the source block at `(x, y)` and a
2755 /// `side x side` prediction, as the whole number it is.
2756 ///
2757 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
2758 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
2759 /// exactly, so no add here rounds and the order of the adds cannot change
2760 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
2761 /// integer division per sample -- is what lets the row walk vectorize.
2762 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
2763 let mut sad = 0u32;
2764 for row in 0..side {
2765 let source = &self.source[(y + row) * self.width + x..][..side];
2766 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
2767 sad += u32::from(s.abs_diff(p));
2768 }
2769 }
2770 f64::from(sad)
2771 }
2772
2773 /// Squared error between the source block at `(x, y)` and a reconstruction
2774 /// of it, over the part of the block that is INSIDE the true frame.
2775 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
2776 /// `255^2 * 64 * 64`, under 2^28.
2777 ///
2778 /// A block the frame edge cuts through is still coded whole -- the
2779 /// decoder reconstructs its outside samples too and the display crop
2780 /// throws them away -- so scoring the padding would rank a mode, a
2781 /// transform or a partition tree by how well it codes samples the source
2782 /// does not have (libaom clips the same way: `av1_dist_block` measures
2783 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
2784 /// edge pixels, so predicting it is nearly free, but coding coefficients
2785 /// for it spends real bits. Both gate films are superblock-aligned; this
2786 /// only reaches arbitrary export sizes (lane-sse, generalising
2787 /// lane-b64b's 64-root-only rescore of the 64 root).
2788 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
2789 let inside_rows = side.min(self.true_height.saturating_sub(y));
2790 let inside_cols = side.min(self.true_width.saturating_sub(x));
2791 let straddles = inside_rows < side || inside_cols < side;
2792 // The knob is read only for a block the edge cuts, so the interior
2793 // path -- the hot one -- carries no extra load at all.
2794 let (rows, cols) = match straddles && !edge_sse() {
2795 true => (side, side),
2796 false => (inside_rows, inside_cols),
2797 };
2798 let mut sse = 0u64;
2799 for row in 0..rows {
2800 let source = &self.source[(y + row) * self.width + x..][..cols];
2801 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
2802 let d = u32::from(s.abs_diff(r));
2803 sse += u64::from(d * d);
2804 }
2805 }
2806 if straddles && edge_census() {
2807 let (mut inside, mut whole) = (0u64, 0u64);
2808 for row in 0..side {
2809 let source = &self.source[(y + row) * self.width + x..][..side];
2810 for (col, (&s, &r)) in source
2811 .iter()
2812 .zip(&reconstruction[row * side..][..side])
2813 .enumerate()
2814 {
2815 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
2816 whole += d;
2817 if row < inside_rows && col < inside_cols {
2818 inside += d;
2819 }
2820 }
2821 }
2822 record_edge_score(side, inside, whole - inside);
2823 }
2824 sse as f64
2825 }
2826
2827 fn trial_typed(
2828 &self,
2829 at: At,
2830 mode: u8,
2831 // This block's `angle_delta_y`/`angle_delta_uv` (spec
2832 // `read_intra_angle_info`, -3..=3), zero for every non-directional
2833 // mode -- the predictor's own `angle_delta` argument.
2834 angle_delta: i32,
2835 base_q_idx: u8,
2836 deadzone: f64,
2837 tx_type: TxType,
2838 fctx: &crate::decode::FrameCtx,
2839 ) -> Trial {
2840 let At {
2841 x, y, side, reach, ..
2842 } = at;
2843 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2844 let (above, left, corner) =
2845 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2846 // Per-candidate scratch on the search's hottest path, so both buffers
2847 // live on the stack -- `side` is at most `BLOCK` -- rather than
2848 // costing a malloc/free pair per trial (`mc_trial` already does this).
2849 let mut prediction = [0u8; BLOCK * BLOCK];
2850 let prediction = &mut prediction[..side * side];
2851 intra_predict_u8(
2852 mode,
2853 angle_delta,
2854 above,
2855 left,
2856 corner,
2857 side,
2858 side,
2859 false,
2860 false,
2861 prediction,
2862 fctx,
2863 );
2864
2865 let mut residual = [0i32; BLOCK * BLOCK];
2866 let residual = &mut residual[..side * side];
2867 for row in 0..side {
2868 for col in 0..side {
2869 residual[row * side + col] =
2870 i32::from(self.source[(y + row) * self.width + x + col])
2871 - i32::from(prediction[row * side + col]);
2872 }
2873 }
2874 #[cfg(test)]
2875 let t = stage_start();
2876 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
2877 // reconstruction below and the price further down are both of the
2878 // grid this trial would really code.
2879 let (levels, rdoq_bits) = if rdoq_on() {
2880 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2881 residual,
2882 side,
2883 8,
2884 i32::from(base_q_idx),
2885 deadzone,
2886 tx_type,
2887 );
2888 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2889 let bits = crate::tile::rdoq(
2890 &mut levels,
2891 &scaled,
2892 side,
2893 base_q_idx,
2894 at.set,
2895 skip_ctx,
2896 sign_ctx,
2897 rdoq_lambda(),
2898 tx_type,
2899 );
2900 (levels, Some(bits))
2901 } else {
2902 (
2903 forward_and_quantize_typed(
2904 residual,
2905 side,
2906 8,
2907 i32::from(base_q_idx),
2908 deadzone,
2909 tx_type,
2910 ),
2911 None,
2912 )
2913 };
2914 // lane-av1speed2: 60% of the transform units of an inter stream carry
2915 // no coefficient at all, and the square entry point re-inflates that
2916 // case into `side * side` zeros (one allocate-and-memset per trial)
2917 // only for the sum below to add them to the prediction. The `_wh`
2918 // entry hands back the empty all-zero marker instead, and a zero
2919 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
2920 // `p` for a `u8`, so the bytes are the same.
2921 let coded = dequant_and_inverse_typed_wh(
2922 &levels,
2923 side,
2924 side,
2925 8,
2926 i32::from(base_q_idx),
2927 0,
2928 0,
2929 tx_type,
2930 None,
2931 );
2932 #[cfg(test)]
2933 stage_since(2, t);
2934
2935 let reconstruction: Vec<u8> = if coded.is_empty() {
2936 prediction.to_vec()
2937 } else {
2938 prediction
2939 .iter()
2940 .zip(&coded)
2941 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2942 .collect()
2943 };
2944 let sse = self.block_sse(x, y, side, &reconstruction);
2945 // What the levels cost is priced through the same CDFs the tile writer
2946 // will code them with, so the search ranks modes -- and the partition
2947 // trial ranks trees -- by the bits they actually spend.
2948 #[cfg(test)]
2949 let t = stage_start();
2950 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2951 // What the search used before it could price a block exactly: a
2952 // level costs its magnitude's width plus a sign and a run. Kept
2953 // reachable from the sweep so the two rate terms can be compared
2954 // on one build.
2955 levels
2956 .iter()
2957 .filter(|&&level| level != 0)
2958 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2959 .sum()
2960 } else if let Some(bits) = rdoq_bits {
2961 // Already priced, against the grid the pass settled on.
2962 bits
2963 } else {
2964 {
2965 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2966 crate::tile::coeff_bits_typed(
2967 &levels,
2968 at.set,
2969 crate::decode::q_ctx_of(base_q_idx),
2970 skip_ctx,
2971 sign_ctx,
2972 tx_type,
2973 )
2974 }
2975 };
2976 #[cfg(test)]
2977 stage_since(3, t);
2978 Trial {
2979 levels,
2980 reconstruction,
2981 sse,
2982 bits,
2983 }
2984 }
2985
2986 /// [`Self::trial`] with the prediction already built, so that an inter
2987 /// block's motion-compensated prediction can go through the same
2988 /// residual/quantize/reconstruct path an intra block's does. `skip`
2989 /// takes the prediction as the reconstruction outright, coding no
2990 /// residual at all — what a `NEARESTMV` block that names no coefficients
2991 /// codes.
2992 #[allow(clippy::too_many_arguments)]
2993 fn code_from_prediction(
2994 &self,
2995 x: usize,
2996 y: usize,
2997 side: usize,
2998 prediction: &[u8],
2999 skip: bool,
3000 base_q_idx: u8,
3001 deadzone: f64,
3002 set: TxbSet,
3003 ) -> Trial {
3004 self.code_from_prediction_typed(
3005 x,
3006 y,
3007 side,
3008 prediction,
3009 skip,
3010 base_q_idx,
3011 deadzone,
3012 set,
3013 TxType::DctDct,
3014 )
3015 }
3016
3017 /// [`Self::code_from_prediction`] coding the residual with a NAMED
3018 /// transform type (lane-txset2): the inter luma sets carry a two-type
3019 /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
3020 /// a symbol for, and [`commit_inter_luma`] prices both through this.
3021 #[allow(clippy::too_many_arguments)]
3022 fn code_from_prediction_typed(
3023 &self,
3024 x: usize,
3025 y: usize,
3026 side: usize,
3027 prediction: &[u8],
3028 skip: bool,
3029 base_q_idx: u8,
3030 deadzone: f64,
3031 set: TxbSet,
3032 tx_type: TxType,
3033 ) -> Trial {
3034 if skip {
3035 let sse = self.block_sse(x, y, side, prediction);
3036 return Trial {
3037 levels: vec![0i32; side * side],
3038 reconstruction: prediction.to_vec(),
3039 sse,
3040 bits: 0.0,
3041 };
3042 }
3043 // A 64x64 root's residual is four times the scratch every other
3044 // block coder here sizes for [`BLOCK`]; only that one case pays for
3045 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
3046 let mut small = [0i32; BLOCK * BLOCK];
3047 let mut big = if side > BLOCK {
3048 vec![0i32; side * side]
3049 } else {
3050 Vec::new()
3051 };
3052 let residual: &mut [i32] = if side > BLOCK {
3053 &mut big
3054 } else {
3055 &mut small[..side * side]
3056 };
3057 for row in 0..side {
3058 for col in 0..side {
3059 residual[row * side + col] =
3060 i32::from(self.source[(y + row) * self.width + x + col])
3061 - i32::from(prediction[row * side + col]);
3062 }
3063 }
3064 #[cfg(test)]
3065 let t = stage_start();
3066 // lane-rdoq, as in [`Self::trial_typed`].
3067 let (levels, rdoq_bits) = if rdoq_on() {
3068 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
3069 residual,
3070 side,
3071 8,
3072 i32::from(base_q_idx),
3073 deadzone,
3074 tx_type,
3075 );
3076 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3077 let bits = crate::tile::rdoq(
3078 &mut levels,
3079 &scaled,
3080 side,
3081 base_q_idx,
3082 set,
3083 skip_ctx,
3084 sign_ctx,
3085 rdoq_lambda(),
3086 tx_type,
3087 );
3088 (levels, Some(bits))
3089 } else {
3090 (
3091 forward_and_quantize_typed(
3092 residual,
3093 side,
3094 8,
3095 i32::from(base_q_idx),
3096 deadzone,
3097 tx_type,
3098 ),
3099 None,
3100 )
3101 };
3102 // The same all-zero shortcut [`Self::trial_typed`] takes.
3103 let coded = dequant_and_inverse_typed_wh(
3104 &levels,
3105 side,
3106 side,
3107 8,
3108 i32::from(base_q_idx),
3109 0,
3110 0,
3111 tx_type,
3112 None,
3113 );
3114 #[cfg(test)]
3115 stage_since(2, t);
3116 let reconstruction: Vec<u8> = if coded.is_empty() {
3117 prediction.to_vec()
3118 } else {
3119 prediction
3120 .iter()
3121 .zip(&coded)
3122 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
3123 .collect()
3124 };
3125 let sse = self.block_sse(x, y, side, &reconstruction);
3126 // A 64-point transform codes only its top-left 32x32 corner (spec
3127 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
3128 // key frame writer takes a 32x32 level grid for one). The inverse
3129 // above reads the whole 64x64 array, but the price below and the
3130 // levels the writer takes are that corner.
3131 let levels = if side > BLOCK {
3132 coded_corner(&levels, side, BLOCK)
3133 } else {
3134 levels
3135 };
3136 #[cfg(test)]
3137 let t = stage_start();
3138 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
3139 levels
3140 .iter()
3141 .filter(|&&level| level != 0)
3142 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
3143 .sum()
3144 } else if let Some(bits) = rdoq_bits {
3145 bits
3146 } else {
3147 {
3148 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3149 crate::tile::coeff_bits_typed(
3150 &levels,
3151 set,
3152 crate::decode::q_ctx_of(base_q_idx),
3153 skip_ctx,
3154 sign_ctx,
3155 tx_type,
3156 )
3157 }
3158 };
3159 #[cfg(test)]
3160 stage_since(3, t);
3161 Trial {
3162 levels,
3163 reconstruction,
3164 sse,
3165 bits,
3166 }
3167 }
3168
3169 /// Codes this block's luma at transform depth `depth`: the
3170 /// `(side >> depth)^2` transform units in raster order, each predicted
3171 /// from the reconstruction the units before it left behind -- exactly
3172 /// what the decoder's multi-transform-unit branch does (decode.rs
3173 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
3174 /// reconstructed on its own. Commits the result and hands back the
3175 /// block-coordinate levels, the block's squared error and what its
3176 /// coefficients cost.
3177 #[allow(clippy::too_many_arguments)]
3178 fn code_tx_depth(
3179 &mut self,
3180 at: At,
3181 mode: u8,
3182 angle_delta: i32,
3183 depth: usize,
3184 // This block's `filter_intra_mode` when it is coded with one, in
3185 // which case every transform unit predicts recursively off the
3186 // reconstruction the units before it left -- what the decoder does
3187 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
3188 // `filter_intra`), not once over the whole block.
3189 filter_intra: Option<u8>,
3190 search: &Search,
3191 fctx: &crate::decode::FrameCtx,
3192 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
3193 let At {
3194 x, y, side, reach, ..
3195 } = at;
3196 let tx = side >> depth;
3197 let n = 1usize << depth;
3198 let set = luma_set_for(
3199 match tx {
3200 32 => TxbSet::Luma32,
3201 16 => TxbSet::Luma16,
3202 8 => TxbSet::Luma8,
3203 _ => TxbSet::Luma4,
3204 },
3205 search.screen,
3206 );
3207 let mut levels = vec![0i32; side * side];
3208 census_add(4, n * n);
3209 // A unit smaller than its block reads the neighbour magnitude table
3210 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
3211 self.ctx.tu_split = n > 1;
3212 let (mut sse, mut bits) = (0.0, 0.0);
3213 // One entry per unit at its own `tu_row * n + tu_col`, which is how
3214 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
3215 // frame edge cuts away is never coded there, so a compacted list
3216 // would slide every later unit's type onto the wrong transform.
3217 let mut tx_types = vec![TxType::DctDct; n * n];
3218 for tu_row in 0..n {
3219 for tu_col in 0..n {
3220 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3221 let tu = At {
3222 x: x + col_off,
3223 y: y + row_off,
3224 side: tx,
3225 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
3226 set,
3227 };
3228 let trial = match filter_intra {
3229 Some(fi) => {
3230 let (mut above_buf, mut left_buf) =
3231 ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3232 let (above, left, corner) = self.edges_into(
3233 tu.x,
3234 tu.y,
3235 tx,
3236 tu.reach,
3237 &mut above_buf,
3238 &mut left_buf,
3239 );
3240 let mut prediction = vec![0u8; tx * tx];
3241 filter_intra_predict_u8(
3242 usize::from(fi),
3243 above,
3244 left,
3245 corner,
3246 tx,
3247 &mut prediction,
3248 fctx,
3249 );
3250 self.code_from_prediction(
3251 tu.x,
3252 tu.y,
3253 tx,
3254 &prediction,
3255 false,
3256 search.base_q_idx,
3257 search.deadzone,
3258 set,
3259 )
3260 }
3261 None => {
3262 // lane-txset: the unit picks its own transform type
3263 // out of the set the writer can name it in, priced
3264 // through the same RDOQ'd trial path (its `bits`
3265 // already carry the `tx_type` symbol itself).
3266 let mut best: Option<(f64, TxType, Trial)> = None;
3267 for &tx_type in tx_type_candidates(set, search.screen) {
3268 let candidate = self.trial_typed(
3269 tu,
3270 mode,
3271 angle_delta,
3272 search.base_q_idx,
3273 search.deadzone,
3274 tx_type,
3275 fctx,
3276 );
3277 // lane-txi: a non-`DCT_DCT` type is charged its
3278 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
3279 // search's weight (default 1 = unchanged). The
3280 // film rows buy 0.04 dB for 1.2% more bytes at
3281 // weight 1 on every frame and every PLANE, key
3282 // frame included -- a rate term this decision
3283 // under-charges (class
3284 // `rd-rate-term-calibration`), not the
3285 // propagation loss the leaves would have shown.
3286 let cost = candidate.sse
3287 + search.lambda * candidate.bits
3288 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
3289 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
3290 best = Some((cost, tx_type, candidate));
3291 }
3292 }
3293 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
3294 tx_types[tu_row * n + tu_col] = tx_type;
3295 TX_TYPE_HITS[tx_type as usize]
3296 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3297 trial
3298 }
3299 };
3300 sse += trial.sse;
3301 bits += trial.bits;
3302 self.commit(tu.x, tu.y, tx, &trial);
3303 for row in 0..tx {
3304 levels[(row_off + row) * side + col_off..][..tx]
3305 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3306 }
3307 }
3308 }
3309 self.ctx.tu_split = false;
3310 (levels, sse, bits, tx_types)
3311 }
3312
3313 /// Writes a trial's reconstruction back into the plane, and the
3314 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
3315 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
3316 for row in 0..side {
3317 self.reconstruction[(y + row) * self.width + x..][..side]
3318 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
3319 }
3320 self.commit_ctx(x, y, side, &trial.levels);
3321 }
3322
3323 /// Publishes one committed transform's own context over every 4x4 cell it
3324 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
3325 /// which is what the writer will read when it reaches the next block.
3326 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
3327 if self.ctx.cells.is_empty() {
3328 self.ctx.stride = self.width.div_ceil(4);
3329 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
3330 }
3331 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
3332 let state = CoefCtx {
3333 level: cul,
3334 dc: match levels[0].signum() {
3335 0 => 0,
3336 -1 => -1,
3337 _ => 1,
3338 },
3339 };
3340 let n = (side / 4).max(1);
3341 // Only up to the frame's TRUE extent: the writer's own
3342 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
3343 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
3344 // and leaves the cells past it uncoded even mid-block, so a
3345 // straddling block publishes context for its inside part only.
3346 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
3347 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
3348 for row in 0..rows {
3349 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3350 let end = (start + cols).min(self.ctx.cells.len());
3351 if start < end {
3352 self.ctx.cells[start..end].fill(state);
3353 }
3354 }
3355 }
3356
3357 /// A block committed without any residual at all ([`ibc_commit`]): the
3358 /// cells it covers coded nothing, and leaving an earlier trial's state
3359 /// there would price its neighbours off a block that was never coded.
3360 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
3361 self.commit_ctx(x, y, side, &[0i32]);
3362 }
3363
3364 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
3365 /// plane reads, off what the blocks before it in coding order committed
3366 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
3367 /// the above/left neighbours coded anything (tile.rs
3368 /// `write_block_planes`), luma reads context 0 when its transform covers
3369 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
3370 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
3371 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
3372 /// the same neighbours (tile.rs `dc_sign_ctx`).
3373 ///
3374 /// A neighbour outside this plane's own TILE does not exist, exactly as
3375 /// the writer's per-tile `Neighbours` bands start blank.
3376 ///
3377 /// CLOSED (lane-av1straddle): the decisions this price changes used to
3378 /// make `decode_stream_round_trips_an_odd_size_gop` and
3379 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
3380 /// fail at 216x96. Never this map: the writer coded the phantom
3381 /// transform units of a right-edge-straddling 32x32 (tile.rs
3382 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
3383 /// like decode.rs and libaom), which libdav1d and libaom both refused
3384 /// outright while a decision change was what first walked into it.
3385 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
3386 if self.ctx.cells.is_empty() {
3387 return (0, 0);
3388 }
3389 let n = (side / 4).max(1);
3390 let (cx, cy) = (x / 4, y / 4);
3391 let (mut top, mut left) = (0u8, 0u8);
3392 let mut vote = 0i32;
3393 if y > self.tile_y0 && cy > 0 {
3394 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
3395 top |= cell.level;
3396 vote += i32::from(cell.dc);
3397 }
3398 }
3399 if x > self.tile_x0 && cx > 0 {
3400 for row in 0..n {
3401 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
3402 left |= cell.level;
3403 vote += i32::from(cell.dc);
3404 }
3405 }
3406 let skip_ctx = if set.is_chroma() {
3407 usize::from(top != 0) + usize::from(left != 0)
3408 } else if self.ctx.tu_split {
3409 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3410 } else {
3411 0
3412 };
3413 let sign_ctx = match vote.signum() {
3414 0 => 0,
3415 -1 => 1,
3416 _ => 2,
3417 };
3418 (skip_ctx, sign_ctx)
3419 }
3420
3421 /// The source samples of one square, contiguous — what a motion search
3422 /// compares its candidates' predictions against ([`motion::search`]'s
3423 /// `source`), since [`Self::source`] itself is the whole plane, strided
3424 /// by [`Self::width`].
3425 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
3426 rows_of(self.source, self.width, x, y, side)
3427 }
3428
3429 /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
3430 /// root's own HORZ/VERT motion search.
3431 fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
3432 let mut out = vec![0u8; w * h];
3433 for row in 0..h {
3434 out[row * w..][..w].copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3435 }
3436 out
3437 }
3438
3439 /// The reconstructed samples of one square, so that a partition trial can
3440 /// be undone.
3441 /// The reconstructed samples of one square AND the coefficient contexts
3442 /// its cells hold, so that a partition trial can be undone whole: a
3443 /// losing trial that left its own nz/DC state behind would price the
3444 /// blocks after it off a block the tile writer never codes.
3445 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
3446 (
3447 rows_of(&self.reconstruction, self.width, x, y, side),
3448 self.ctx_rows(x, y, side),
3449 )
3450 }
3451
3452 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
3453 if self.ctx.cells.is_empty() {
3454 return Vec::new();
3455 }
3456 let n = (side / 4).max(1);
3457 (0..n)
3458 .flat_map(|row| {
3459 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3460 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
3461 })
3462 .collect()
3463 }
3464
3465 /// Puts a snapshot back.
3466 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
3467 for row in 0..side {
3468 self.reconstruction[(y + row) * self.width + x..][..side]
3469 .copy_from_slice(&saved.0[row * side..][..side]);
3470 }
3471 if saved.1.is_empty() {
3472 return;
3473 }
3474 let n = (side / 4).max(1);
3475 for row in 0..n {
3476 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3477 let end = (start + n).min(self.ctx.cells.len());
3478 if start < end {
3479 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
3480 }
3481 }
3482 }
3483
3484 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
3485 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
3486 /// prescreen by the identical rule rather than a second one that could
3487 /// drift from it.
3488 fn intra_scores(
3489 &self,
3490 at: At,
3491 modes: &[u8],
3492 mode_bits: &[f64; 13],
3493 lambda: f64,
3494 fctx: &crate::decode::FrameCtx,
3495 ) -> Vec<(f64, u8)> {
3496 let At {
3497 x, y, side, reach, ..
3498 } = at;
3499 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3500 let (above, left, corner) =
3501 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3502 modes
3503 .iter()
3504 .map(|&mode| {
3505 let mut prediction = vec![0u8; side * side];
3506 intra_predict_u8(
3507 mode,
3508 0,
3509 above,
3510 left,
3511 corner,
3512 side,
3513 side,
3514 false,
3515 false,
3516 &mut prediction,
3517 fctx,
3518 );
3519 let sad = self.block_sad(x, y, side, &prediction);
3520 (sad + lambda * mode_bits[usize::from(mode)], mode)
3521 })
3522 .collect()
3523 }
3524
3525 /// Codes one block under every mode the search offers (or, when
3526 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
3527 /// pre-pass plus DC) and commits the one whose squared error and
3528 /// estimated rate come out cheapest.
3529 ///
3530 /// The prediction is built once per mode regardless -- the full RD trial
3531 /// needs it too -- so ranking modes by SAD on that same prediction before
3532 /// running the expensive part (forward transform, quantize, reconstruct,
3533 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
3534 /// only to sum.
3535 fn search_block(
3536 &mut self,
3537 at: At,
3538 search: &Search,
3539 mode_bits: &[f64; 13],
3540 fctx: &crate::decode::FrameCtx,
3541 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
3542 let At {
3543 x, y, side, reach, ..
3544 } = at;
3545 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3546 let (above, left, corner) =
3547 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3548 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
3549 // the census reports it), so summing it under the default unpruned
3550 // search is `side * side` absolute differences per mode spent on a
3551 // number no one reads.
3552 let want_sad = search.top_k.is_some() || census_on();
3553 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
3554 .modes
3555 .iter()
3556 .map(|&mode| {
3557 let mut prediction = vec![0u8; side * side];
3558 intra_predict_u8(
3559 mode,
3560 0,
3561 above,
3562 left,
3563 corner,
3564 side,
3565 side,
3566 false,
3567 false,
3568 &mut prediction,
3569 fctx,
3570 );
3571 let sad = if want_sad {
3572 self.block_sad(x, y, side, &prediction)
3573 } else {
3574 0.0
3575 };
3576 (
3577 sad + search.lambda * mode_bits[usize::from(mode)],
3578 mode,
3579 prediction,
3580 )
3581 })
3582 .collect();
3583 if let Some(k) = search.top_k {
3584 if k < scored.len() {
3585 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
3586 let dc_entry = dc_pos.map(|i| scored.remove(i));
3587 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3588 scored.truncate(if dc_entry.is_some() {
3589 k.saturating_sub(1)
3590 } else {
3591 k
3592 });
3593 if let Some(dc_entry) = dc_entry {
3594 scored.push(dc_entry);
3595 }
3596 }
3597 }
3598 let ranking: Vec<(f64, u8)> = if census_on() {
3599 scored
3600 .iter()
3601 .map(|&(score, mode, _)| (score, mode))
3602 .collect()
3603 } else {
3604 Vec::new()
3605 };
3606 census_add(0, 1);
3607 census_add(1, scored.len());
3608 let mut best: Option<(f64, u8, Trial)> = None;
3609 for (_, mode, prediction) in scored {
3610 let trial = self.code_from_prediction(
3611 x,
3612 y,
3613 side,
3614 &prediction,
3615 false,
3616 search.base_q_idx,
3617 search.deadzone,
3618 at.set,
3619 );
3620 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
3621 if best
3622 .as_ref()
3623 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
3624 {
3625 best = Some((cost, mode, trial));
3626 }
3627 }
3628 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
3629 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
3630 // directional modes each carry a -3..=3 delta, three degrees a step,
3631 // which the writer has always coded as ZERO because nothing searched
3632 // it. Refined on the winning mode only -- libaom's own ordering, and
3633 // six extra trials on the directional blocks instead of on every
3634 // block times every mode. The edges are the ones the base angle
3635 // already read (`enable_intra_edge_filter` is off in this encoder's
3636 // sequence header, so no delta changes which samples exist), and the
3637 // predictor is the decoder's, `angle_delta` argument and all.
3638 let mut angle_delta = 0i32;
3639 // Not on a screen frame: measured on the 5-row native gate, the
3640 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
3641 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
3642 // synthetic edges land on the base angles, so every delta there buys
3643 // a symbol and no prediction. Same `search.screen` gate palette and
3644 // intrabc already stand behind.
3645 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
3646 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
3647 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
3648 let mut prediction = vec![0u8; side * side];
3649 for delta in [-3i32, -2, -1, 1, 2, 3] {
3650 intra_predict_u8(
3651 mode,
3652 delta,
3653 above,
3654 left,
3655 corner,
3656 side,
3657 side,
3658 false,
3659 false,
3660 &mut prediction,
3661 fctx,
3662 );
3663 let candidate = self.code_from_prediction(
3664 x,
3665 y,
3666 side,
3667 &prediction,
3668 false,
3669 search.base_q_idx,
3670 search.deadzone,
3671 at.set,
3672 );
3673 let bits =
3674 symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3675 - zero_bits;
3676 let cost_d = candidate.sse
3677 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
3678 if cost_d < cost {
3679 cost = cost_d;
3680 angle_delta = delta;
3681 trial = candidate;
3682 }
3683 }
3684 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
3685 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3686 }
3687 // lane-txset: the block's own transform type, searched on the mode
3688 // and angle the trials above settled -- the same ordering the angle
3689 // refinement uses, and the same RD terms.
3690 let mut tx_type = TxType::DctDct;
3691 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
3692 let candidate = self.trial_typed(
3693 at,
3694 mode,
3695 angle_delta,
3696 search.base_q_idx,
3697 search.deadzone,
3698 candidate_type,
3699 fctx,
3700 );
3701 let cost_t =
3702 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3703 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3704 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3705 // block's true one for the caller's own decision.
3706 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3707 cost = cost_t;
3708 tx_type = candidate_type;
3709 trial = candidate;
3710 }
3711 }
3712 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3713 if census_on() {
3714 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
3715 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3716 }
3717 self.commit(x, y, side, &trial);
3718 // A 64-point transform codes only its top-left 32x32 corner, which is
3719 // the grid `code_from_prediction` hands back (lane-i64).
3720 (
3721 coeffs(&trial.levels, side.min(BLOCK)),
3722 mode,
3723 angle_delta,
3724 cost,
3725 tx_type,
3726 )
3727 }
3728}
3729
3730/// Where one block sits in its plane, and how far past its own edges its
3731/// prediction may read.
3732#[derive(Clone, Copy)]
3733struct At {
3734 x: usize,
3735 y: usize,
3736 side: usize,
3737 reach: Reach,
3738 /// Which of the tile writer's coefficient tables this block's levels are
3739 /// coded with, and so which the search prices them through.
3740 set: TxbSet,
3741}
3742
3743/// Which of the samples past a block's own edges the decoder has decoded by
3744/// the time it predicts the block, and so which a directional mode may read.
3745///
3746/// The decoder derives these from its `BlockDecoded` flags, which are cleared
3747/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
3748/// that map, this reads the answer the same way libaom and rav1e do: for a
3749/// block whose transform covers it whole, whether the samples above its right
3750/// (or below its left) are decoded depends only on where the block sits inside
3751/// its 64x64 superblock, which is a pinned table per block size.
3752#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3753pub(crate) struct Reach {
3754 pub(crate) above_right: bool,
3755 pub(crate) below_left: bool,
3756}
3757
3758/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
3759/// libaom): for a block that is neither in the superblock's top row nor its
3760/// rightmost column, whether the block above and to its right is coded before
3761/// it. Indexed by the block's position in the superblock, in blocks of its own
3762/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
3763/// 128, not this crate's 64 superblock -- bit by bit from the low end.
3764const HAS_TOP_RIGHT: [&[u8]; 4] = [
3765 &[255, 85, 119, 85, 127, 85, 119, 85],
3766 &[95, 87],
3767 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
3768 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
3769 &[
3770 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
3771 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
3772 ],
3773 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
3774 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
3775 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
3776 // with side 4 outside a TX4 split; without their own row they clamped
3777 // into the 8x8 table and read above-right samples the decoder has not
3778 // written yet (all-zero pixels in the bottom-right triangle of a
3779 // directional 4x4 leaf).
3780 &[
3781 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
3782 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
3783 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
3784 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
3785 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
3786 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
3787 119, 119, 119, 119, 85, 85, 85, 85,
3788 ],
3789];
3790
3791/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
3792/// left.
3793const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
3794 &[84, 16, 84, 0, 84, 16, 84, 0],
3795 &[4, 4],
3796 // has_bl_8x8 (libaom av1/common/reconintra.c)
3797 &[
3798 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
3799 84, 85, 16, 17, 84, 85, 0, 0,
3800 ],
3801 // has_bl_4x4 (same source, same order).
3802 &[
3803 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
3804 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,
3805 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
3806 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,
3807 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
3808 85, 85, 0, 0, 0, 0,
3809 ],
3810];
3811
3812/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
3813/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
3814/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
3815/// rather than in raster order, so the bottom-left square's top-right
3816/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
3817/// libaom switches tables on the partition type (`get_has_tr_table`); the
3818/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
3819/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
3820/// lane-part32 r5 caught reading undecoded samples.
3821const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
3822 // has_tr_vert_16x16
3823 &[255, 0, 119, 0, 127, 0, 119, 0],
3824 // has_tr_vert_32x32
3825 &[15, 7],
3826 // has_tr_vert_8x8
3827 &[
3828 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
3829 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
3830 ],
3831];
3832
3833/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
3834const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
3835 // has_bl_vert_16x16
3836 &[254, 16, 254, 0, 254, 16, 254, 0],
3837 // has_bl_vert_32x32
3838 &[14, 14],
3839 // has_bl_vert_8x8
3840 &[
3841 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
3842 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
3843 ],
3844];
3845
3846thread_local! {
3847 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
3848 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
3849 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
3850 /// threading one bool through this crate's already twenty-argument
3851 /// `decode_block` would touch every call site instead of the two arms
3852 /// that need it.
3853 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3854}
3855
3856/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
3857pub(crate) struct VertAbGuard(bool);
3858
3859impl Drop for VertAbGuard {
3860 fn drop(&mut self) {
3861 VERT_AB_PARTITION.with(|c| c.set(self.0));
3862 }
3863}
3864
3865/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
3866/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
3867/// so no byte is retyped). Each is indexed by
3868/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
3869/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
3870/// superblock grid; on this crate's 64-pixel superblock the highest index a
3871/// shape can reach stays inside its own table, so no wrap is involved.
3872///
3873/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
3874/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
3875/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
3876/// 10 of the 21 reachable superblock positions for above-right and 7 for
3877/// below-left.
3878/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3879const HAS_TR_4X8: [u8; 64] = [
3880 255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255,
3881 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119,
3882 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127,
3883 127, 127, 127, 119, 119, 119, 119,
3884];
3885/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3886const HAS_BL_4X8: [u8; 64] = [
3887 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,
3888 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,
3889 1, 1, 16, 17, 17, 17, 0, 0, 0, 0,
3890];
3891/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3892const HAS_TR_8X4: [u8; 64] = [
3893 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,
3894 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,
3895 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0,
3896];
3897/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3898const HAS_BL_8X4: [u8; 64] = [
3899 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254,
3900 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255,
3901 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0,
3902];
3903/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3904const HAS_TR_8X16: [u8; 16] = [
3905 255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119,
3906];
3907/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3908const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
3909/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3910const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
3911/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3912const HAS_BL_16X8: [u8; 16] = [
3913 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0,
3914];
3915/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3916const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
3917/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3918const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
3919/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3920const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
3921/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3922const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
3923/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3924const HAS_TR_32X64: [u8; 1] = [127];
3925/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3926const HAS_BL_32X64: [u8; 1] = [0];
3927/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3928const HAS_TR_64X32: [u8; 1] = [19];
3929/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3930const HAS_BL_64X32: [u8; 1] = [34];
3931/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3932const HAS_TR_4X16: [u8; 32] = [
3933 255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255,
3934 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127,
3935];
3936/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3937const HAS_BL_4X16: [u8; 32] = [
3938 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,
3939];
3940/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3941const HAS_TR_16X4: [u8; 32] = [
3942 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,
3943 85, 0, 0, 0,
3944];
3945/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3946const HAS_BL_16X4: [u8; 32] = [
3947 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84,
3948 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0,
3949];
3950/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3951const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
3952/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3953const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
3954/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3955const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
3956/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3957const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
3958/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3959const HAS_TR_16X64: [u8; 2] = [255, 127];
3960/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3961const HAS_BL_16X64: [u8; 2] = [0, 0];
3962/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3963const HAS_TR_64X16: [u8; 2] = [3, 1];
3964/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3965const HAS_BL_64X16: [u8; 2] = [42, 42];
3966
3967/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
3968fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
3969 match (bw, bh) {
3970 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
3971 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
3972 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
3973 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
3974 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
3975 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
3976 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
3977 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
3978 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
3979 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
3980 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
3981 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
3982 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
3983 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
3984 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
3985 }
3986}
3987
3988impl Reach {
3989 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3990 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
3991 /// own answer is `block` -- a different rule from the standalone-block
3992 /// tables, because a unit's neighbours are mostly its own block's
3993 /// already-reconstructed units:
3994 /// * top-right: available while the unit to the right is still inside
3995 /// the block (`col_off + tx < bw`); otherwise only the block's top row
3996 /// of units reaches past it, through the block-level answer
3997 /// (libaom's `row_off > 0` branch returns exactly
3998 /// `col_off + txw < plane_bw`).
3999 /// * bottom-left: a unit outside the block's left column has none
4000 /// (libaom returns 0 for `col_off > 0`); inside the block
4001 /// (`row_off + tx < bh`) they are the left unit's, already
4002 /// reconstructed; the bottom row falls back to the block-level answer.
4003 pub(crate) fn of_tu(
4004 bw: usize,
4005 bh: usize,
4006 col_off: usize,
4007 row_off: usize,
4008 // The unit's own width and height in pixels; equal for a square
4009 // transform, different for the rect unit a 1:4 strip's first split
4010 // produces (lane-rectsplitx r1).
4011 tx_w: usize,
4012 tx_h: usize,
4013 block: Self,
4014 ) -> Self {
4015 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
4016 // order, so both libaom predicates special-case it (lane-sb128c r10);
4017 // without this the last unit column of every chunk of a 128x64 block
4018 // predicts from a chunk libaom has not decoded yet.
4019 let wide = bw > 64;
4020 Self {
4021 above_right: if row_off > 0 {
4022 // `has_top_right`'s `row_off > 0` branch: the offset is taken
4023 // modulo the 64-wide chunk, except for the one unit whose
4024 // top-right corner is the centre of a 128x128 block.
4025 if wide {
4026 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
4027 } else {
4028 col_off + tx_w < bw
4029 }
4030 } else if col_off + tx_w < bw {
4031 true
4032 } else {
4033 block.above_right
4034 },
4035 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
4036 // `has_bottom_left`: at the left edge of a right-hand chunk
4037 // the bottom-left pixels are in the already-coded left chunk,
4038 // provided they stay inside it.
4039 (row_off % 64) + tx_h < bh.min(64)
4040 } else if col_off > 0 {
4041 false
4042 } else if row_off + tx_h < bh {
4043 true
4044 } else {
4045 block.below_left
4046 },
4047 }
4048 }
4049
4050 /// What a block of `side` samples at `(x, y)` may read past its own edges,
4051 /// in a frame of `width` by `height`.
4052 pub(crate) fn of(
4053 side: usize,
4054 x: usize,
4055 y: usize,
4056 width: usize,
4057 height: usize,
4058 fctx: &crate::decode::FrameCtx,
4059 ) -> Self {
4060 Self {
4061 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
4062 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
4063 }
4064 }
4065
4066 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
4067 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
4068 /// block's own width for the row stride and by its own height for the
4069 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
4070 /// unlike the square [`Self::of`] which uses one `side` for everything.
4071 pub(crate) fn of_rect(
4072 bw: usize,
4073 bh: usize,
4074 x: usize,
4075 y: usize,
4076 width: usize,
4077 height: usize,
4078 fctx: &crate::decode::FrameCtx,
4079 ) -> Self {
4080 Self {
4081 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
4082 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
4083 }
4084 }
4085
4086 /// [`Self::of`] for one transform unit of a square block whose transform
4087 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
4088 /// non-zero `row_off`/`col_off`): interior units answer from the block's
4089 /// own geometry, and only a unit on the block's top row (resp. left
4090 /// column) reaches the table -- which is the BLOCK's table read at the
4091 /// BLOCK's position, never a table row for the transform's size. Letting
4092 /// the unit stand in for a block of its own size agrees with libaom for
4093 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
4094 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
4095 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
4096 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
4097 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
4098 /// the transform covering the whole block, luma): everything before the
4099 /// table lookup is that function's own early-exit ladder.
4100 fn top_right_rect(
4101 bw: usize,
4102 bh: usize,
4103 x: usize,
4104 y: usize,
4105 fctx: &crate::decode::FrameCtx,
4106 ) -> bool {
4107 let sb_mi: usize = reach_sb_px(fctx) / 4;
4108 let (mi_row, mi_col) = (y / 4, x / 4);
4109 let bw_log2 = (bw / 4).trailing_zeros() as usize;
4110 let bh_log2 = (bh / 4).trailing_zeros() as usize;
4111 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
4112 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
4113 // Top row of the superblock: the top-right pixels are in the (already
4114 // decoded) superblock above.
4115 if blk_row == 0 {
4116 return true;
4117 }
4118 // Rightmost column: they fall in the superblock to the right.
4119 if ((blk_col + 1) << bw_log2) >= sb_mi {
4120 return false;
4121 }
4122 let table = rect_reach_tables(bw, bh).0;
4123 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4124 }
4125
4126 /// libaom `has_top_right`'s own index arithmetic:
4127 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
4128 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
4129 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
4130 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
4131 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
4132 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
4133 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
4134 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
4135 (blk_row << (5 - bw_log2)) + blk_col
4136 }
4137
4138 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
4139 fn bottom_left_rect(
4140 bw: usize,
4141 bh: usize,
4142 x: usize,
4143 y: usize,
4144 fctx: &crate::decode::FrameCtx,
4145 ) -> bool {
4146 let sb_mi: usize = reach_sb_px(fctx) / 4;
4147 let (mi_row, mi_col) = (y / 4, x / 4);
4148 let bw_log2 = (bw / 4).trailing_zeros() as usize;
4149 let bh_log2 = (bh / 4).trailing_zeros() as usize;
4150 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
4151 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
4152 // Leftmost column of the superblock: the bottom-left pixels are in
4153 // the left superblock iff they stay inside its height.
4154 if blk_col == 0 {
4155 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
4156 }
4157 // Bottom row (and not the leftmost column): they fall in the
4158 // superblock below, which is not decoded yet.
4159 if ((blk_row + 1) << bh_log2) >= sb_mi {
4160 return false;
4161 }
4162 let table = rect_reach_tables(bw, bh).1;
4163 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4164 }
4165
4166 /// Marks every [`Reach::of`] made until the returned guard drops as being
4167 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
4168 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
4169 /// unaffected: libaom's own comment says vertical rectangles keep their
4170 /// non-vert table, which is what [`Reach::of_rect`] already reads.
4171 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
4172 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
4173 /// can count the sub-block work that partition creates (lane-ab16).
4174 pub(crate) fn in_vert_ab() -> bool {
4175 VERT_AB_PARTITION.with(std::cell::Cell::get)
4176 }
4177
4178 pub(crate) fn vert_ab_partition() -> VertAbGuard {
4179 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
4180 }
4181
4182 /// Neither, which is all a mode that reads no further than its own edges
4183 /// needs.
4184 pub(crate) fn none() -> Self {
4185 Self {
4186 above_right: false,
4187 below_left: false,
4188 }
4189 }
4190
4191 /// `has_top_right` for a block whose transform covers it whole: the top
4192 /// row of a superblock reads into the superblock above, which is decoded;
4193 /// the rightmost column would read into the superblock to the right, which
4194 /// is not; and everything between is the table's to answer.
4195 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4196 let (row, col, per_side) = Self::position(side, x, y, fctx);
4197 if row == 0 {
4198 return true;
4199 }
4200 if col + 1 == per_side {
4201 return false;
4202 }
4203 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4204 // (the clamp corner-cut that used to live here is gone); sides
4205 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4206 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4207 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4208 // -- a reach over-estimate (extra above-right reference pixels),
4209 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4210 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4211 // NB: named `table_row`, not `row` -- `row` above is the block's
4212 // position inside the superblock and is what the bit index below
4213 // steps by (a merge that shadowed it desynced every block size).
4214 let table_row = Self::table(side);
4215 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
4216 && table_row < HAS_TOP_RIGHT_VERT.len()
4217 {
4218 HAS_TOP_RIGHT_VERT[table_row]
4219 } else {
4220 HAS_TOP_RIGHT[table_row]
4221 };
4222 Self::bit(
4223 table,
4224 (row * Self::table_stride(side) + col) % (table.len() * 8),
4225 )
4226 }
4227
4228 /// `has_bottom_left` for such a block: the leftmost column of a superblock
4229 /// reads into the superblock to its left, which is decoded only as far
4230 /// down as its own bottom; the bottom row would read into the superblock
4231 /// below, which is not decoded at all; and the table answers the rest.
4232 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4233 let (row, col, per_side) = Self::position(side, x, y, fctx);
4234 if col == 0 {
4235 return row * side + side < reach_sb_px(fctx);
4236 }
4237 if row + 1 == per_side {
4238 return false;
4239 }
4240 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4241 // (the clamp corner-cut that used to live here is gone); sides
4242 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4243 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4244 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4245 // -- a reach over-estimate (extra above-right reference pixels),
4246 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4247 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4248 // NB: named `table_row`, not `row` -- `row` above is the block's
4249 // position inside the superblock and is what the bit index below
4250 // steps by (a merge that shadowed it desynced every block size).
4251 let table_row = Self::table(side);
4252 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
4253 && table_row < HAS_BOTTOM_LEFT_VERT.len()
4254 {
4255 HAS_BOTTOM_LEFT_VERT[table_row]
4256 } else {
4257 HAS_BOTTOM_LEFT[table_row]
4258 };
4259 Self::bit(
4260 table,
4261 (row * Self::table_stride(side) + col) % (table.len() * 8),
4262 )
4263 }
4264
4265 /// Where a block sits inside its superblock, in blocks of its own size,
4266 /// and how many of them a superblock is across.
4267 fn position(
4268 side: usize,
4269 x: usize,
4270 y: usize,
4271 fctx: &crate::decode::FrameCtx,
4272 ) -> (usize, usize, usize) {
4273 let sb = reach_sb_px(fctx);
4274 ((y % sb) / side, (x % sb) / side, sb / side)
4275 }
4276
4277 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
4278 /// these tables to its compile-time maximum superblock (128, spec
4279 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
4280 /// size an encode actually uses, so a block's row in the bit index steps
4281 /// by 128 / `side` even though this crate only ever codes a 64
4282 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
4283 /// here instead indexes the wrong bit for every block size but the one
4284 /// where 64 and 128 give the same stride.
4285 fn table_stride(side: usize) -> usize {
4286 128 / side
4287 }
4288
4289 /// Which of the three block sizes the encoder codes a table row is for.
4290 fn table(side: usize) -> usize {
4291 if side == BLOCK {
4292 1
4293 } else if side == 8 {
4294 2
4295 } else if side == 4 {
4296 3
4297 } else {
4298 0
4299 }
4300 }
4301
4302 /// One bit of a table, counting from the low end of its first byte.
4303 fn bit(table: &[u8], index: usize) -> bool {
4304 (table[index / 8] >> (index % 8)) & 1 != 0
4305 }
4306}
4307
4308/// What one symbol costs against a CDF, in bits.
4309/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
4310/// search, the frame header's `allow_warped_motion` and the sequence's
4311/// `enable_warped_motion`, all three together. ON by default since
4312/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
4313/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
4314/// bits -- back off for an A/B on one build.
4315pub(crate) fn warp_on() -> bool {
4316 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4317 crate::envflags::var("EC_AV1_WARP")
4318 .ok()
4319 .map(|v| !matches!(v.as_str(), "0" | "off"))
4320 });
4321 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
4322}
4323
4324/// The smallest LEAF an OBMC candidate is offered for, so the census can
4325/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
4326/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
4327/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
4328///
4329/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
4330/// (12 frames, four quantizers, the standing keep table):
4331///
4332/// | min side | film 1080p | film 2160p | screen |
4333/// |---|---|---|---|
4334/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
4335/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
4336/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
4337/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
4338///
4339/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
4340/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
4341/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
4342/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
4343/// that wins the local RD on five blocks in six and loses ladder bytes is
4344/// the `local-RD-on-references` class again, not a missing footprint.
4345///
4346/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
4347/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
4348/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
4349/// loss on the 1080p film became a 0.3-point win and the other two rows went
4350/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
4351/// of the "local win, ladder loss" it was charged with was the rate weight.
4352/// It still does not meet the keep rule (two down, one flat, both columns).
4353/// The tool stays OFF by default; the upgrade path is the price, not the size
4354/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
4355/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
4356/// 1080p film up, i.e. the same disagreement between the two gates).
4357///
4358/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
4359/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
4360/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
4361/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
4362/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
4363/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
4364/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
4365/// the margin's gain are the same bytes. It stays OFF.
4366///
4367/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
4368/// judgement above was taken when the gate's "film" rows were the `testsrc2`
4369/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
4370/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
4371/// the standing native keep table (`bd_rate_screen_native`):
4372///
4373/// | arm | film A | film B | screen | OBMC fire A/B |
4374/// |---|---|---|---|---|
4375/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
4376/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
4377/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
4378///
4379/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
4380/// only), where the anchors' non-skip area is the known gap:
4381///
4382/// | arm | film B long GOP | wall ours |
4383/// |---|---|---|
4384/// | off (control) | +89.8 / +9.1 | 477.5s |
4385/// | min side 8 | +89.6 / +9.0 | 514.1s |
4386///
4387/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
4388/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
4389/// only at min side 16, which is exactly where film B loses 0.7 on both
4390/// columns. Nothing here meets the keep rule (both films down on both
4391/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
4392/// costs +7.7% wall. OBMC stays OFF at every preset.
4393fn obmc_min_side() -> usize {
4394 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4395 *N.get_or_init(|| {
4396 std::env::var("EC_AV1_OBMC_MIN")
4397 .ok()
4398 .and_then(|v| v.parse().ok())
4399 .unwrap_or(8)
4400 })
4401}
4402
4403/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
4404/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
4405/// same frame-CDF price the coefficients of a non-screen frame are estimated
4406/// with, not the static default table.
4407/// The same price for whichever alphabet the writer will really use for this
4408/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
4409/// (`allow_warped_motion` and at least one warp sample), otherwise the
4410/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
4411/// search pay it, so the alphabet cancels out of a comparison and only its
4412/// per-value spread decides.
4413fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
4414 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
4415 return 0.0;
4416 };
4417 match warp_alphabet {
4418 true => crate::tile::motion_mode_symbol_bits(row, motion),
4419 false => crate::tile::obmc_symbol_bits(row, motion == 1),
4420 }
4421}
4422
4423/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
4424/// candidate, the header's `allow_warped_motion` and the sequence's
4425/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
4426/// native keep table, against the same build with the knob off:
4427///
4428/// | clip | warp on | off |
4429/// |---|---|---|
4430/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
4431/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
4432/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
4433///
4434/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
4435/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
4436/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
4437/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
4438/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
4439/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
4440/// this is a measured loss, not an inert knob. Same shape as the OBMC
4441/// candidate above it (`obmc_min_side`): a local RD win that does not convert
4442/// into ladder bytes.
4443///
4444/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
4445/// because a tool whose gain is local and whose cost is the rate it adds is
4446/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
4447///
4448/// | clip | warp on | off (both at lambda 0.05) |
4449/// |---|---|---|
4450/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
4451/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
4452/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
4453///
4454/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
4455/// column inside 0.1 everywhere -- which reads as a keep rather than the
4456/// 0.7/0.9 loss it was.
4457///
4458/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
4459/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
4460/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
4461/// ran the conformance shape the lambda lane deferred: every warp stream
4462/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
4463/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
4464/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
4465/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
4466/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
4467/// `allow_warped_motion` and `enable_warped_motion` back off together.
4468///
4469/// The WARPED_CAUSAL prediction of one square single-reference block: the
4470/// decoder's own warp-sample walk (`decode::find_samples` +
4471/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
4472/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
4473/// grid -- never a second implementation of any of the three. `None` when the
4474/// block would code no motion_mode symbol at all, when it has no warp sample
4475/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
4476/// or when the projection is not filter-representable (the decoder would then
4477/// predict translationally, so the mode is pure cost).
4478#[allow(clippy::too_many_arguments)]
4479fn warp_prediction(
4480 grid: &MiGrid,
4481 (mi_row, mi_col): (usize, usize),
4482 (mi_rows, mi_cols): (usize, usize),
4483 (x, y): (usize, usize),
4484 side: usize,
4485 mv: (i32, i32),
4486 ref_frame: i8,
4487 ref_planes: [(&[u16], usize, usize, usize); 3],
4488 fctx: &crate::decode::FrameCtx,
4489) -> Option<[Vec<u8>; 3]> {
4490 let n4 = side / 4;
4491 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
4492 return None;
4493 }
4494 let mut samples = crate::decode::find_samples(
4495 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
4496 );
4497 if samples.is_empty() {
4498 return None;
4499 }
4500 if samples.len() > 1 {
4501 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
4502 }
4503 let params = crate::warp::find_projection(
4504 &samples,
4505 side as i32,
4506 side as i32,
4507 mv.1,
4508 mv.0,
4509 mi_row as i32,
4510 mi_col as i32,
4511 )?;
4512 let mut pred = [
4513 vec![0u16; side * side],
4514 vec![0u16; side * side / 4],
4515 vec![0u16; side * side / 4],
4516 ];
4517 // The translational prediction first, exactly as the decoder builds it,
4518 // then the affine one over the planes whose OWN block is at least 8x8
4519 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
4520 // 4x4 chroma stays translational).
4521 for (i, r) in ref_planes.into_iter().enumerate() {
4522 let luma_plane = i == 0;
4523 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
4524 let s = if luma_plane { side } else { side / 2 };
4525 mc::predict(
4526 r.0,
4527 r.1,
4528 r.2,
4529 r.3,
4530 mv_to_q4(px, mv.1, luma_plane),
4531 mv_to_q4(py, mv.0, luma_plane),
4532 s,
4533 s,
4534 &mut pred[i],
4535 fctx,
4536 );
4537 if crate::decode::warp_plane_allowed(s, s) {
4538 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
4539 crate::warp::warp_affine(
4540 &params,
4541 r.0,
4542 r.2 as i32,
4543 r.3 as i32,
4544 r.1 as i32,
4545 &mut pred[i],
4546 px as i32,
4547 py as i32,
4548 cside,
4549 cside,
4550 cside,
4551 sub,
4552 sub,
4553 fctx,
4554 );
4555 }
4556 }
4557 let [py_buf, pu_buf, pv_buf] = pred;
4558 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4559 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4560}
4561
4562/// What tile.rs' `write_compound_ref_frames` pays for the pair
4563/// `(ref0, ref1)`, symbol for symbol, each at the context its own
4564/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
4565/// derives from the block's above/left neighbours -- plus the `comp_mode`
4566/// symbol itself at `reference_mode_ctx`.
4567///
4568/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
4569/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
4570/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
4571/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4572pub(crate) fn compound_ref_bits((ref0, ref1): (i8, i8), stack: &crate::mvstack::MvStack) -> f64 {
4573 use crate::mvstack::{
4574 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4575 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
4576 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
4577 uni_comp_ref_p1_ctx,
4578 };
4579 let (a, a1) = stack.above_refs;
4580 let (l, l1) = stack.left_refs;
4581 let unidir = is_uni_comp_ref(ref0, ref1);
4582 let comp_mode = symbol_bits(
4583 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4584 1,
4585 );
4586 let ref_type = symbol_bits(
4587 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
4588 usize::from(!unidir),
4589 );
4590 if unidir {
4591 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
4592 let p0 = symbol_bits(
4593 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4594 usize::from(both_backward),
4595 );
4596 if both_backward {
4597 return comp_mode + ref_type + p0;
4598 }
4599 let past_last2 = ref1 != LAST2_FRAME;
4600 let p1 = symbol_bits(
4601 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
4602 usize::from(past_last2),
4603 );
4604 let p2 = if past_last2 {
4605 symbol_bits(
4606 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4607 usize::from(ref1 == GOLDEN_FRAME),
4608 )
4609 } else {
4610 0.0
4611 };
4612 return comp_mode + ref_type + p0 + p1 + p2;
4613 }
4614 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
4615 let fwd = symbol_bits(
4616 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
4617 usize::from(far),
4618 ) + if far {
4619 symbol_bits(
4620 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4621 usize::from(ref0 == GOLDEN_FRAME),
4622 )
4623 } else {
4624 symbol_bits(
4625 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
4626 usize::from(ref0 == LAST2_FRAME),
4627 )
4628 };
4629 let is_altref = ref1 == ALTREF_FRAME;
4630 let bwd = symbol_bits(
4631 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
4632 usize::from(is_altref),
4633 ) + if is_altref {
4634 0.0
4635 } else {
4636 symbol_bits(
4637 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
4638 usize::from(ref1 == ALTREF2_FRAME),
4639 )
4640 };
4641 comp_mode + ref_type + fwd + bwd
4642}
4643
4644/// What the `skip` symbol costs at the context tile.rs really codes it with
4645/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
4646/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
4647/// exactly the difference between this symbol's two values, so the row it is
4648/// read from moves that decision (class pricer-context-zero, lane-ctx).
4649pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
4650 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
4651 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
4652}
4653
4654/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
4655/// neighbours' intra/inter state, with an out-of-tile side contributing
4656/// nothing, off the same two cells (lane-ctx).
4657pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
4658 let ctx = crate::tile::intra_inter_ctx(
4659 stack.above_nbr.is_some(),
4660 stack.left_nbr.is_some(),
4661 stack.above_nbr.is_some_and(|n| n.is_inter),
4662 stack.left_nbr.is_some_and(|n| n.is_inter),
4663 );
4664 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
4665}
4666
4667/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
4668/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
4669/// context -- zero on a frame that carries no `reference_select` bit, where
4670/// the writer codes no symbol at all.
4671fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
4672 if !reference_select() {
4673 return 0.0;
4674 }
4675 symbol_bits(
4676 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4677 0,
4678 )
4679}
4680
4681/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
4682/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
4683/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
4684/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
4685/// LAST is p1=0,p3=0,p4=0,
4686/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
4687/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
4688/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
4689/// symbols off the wrong CDFs -- which is what made the search believe an
4690/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
4691/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
4692/// paid nothing at all, so compound was overcharged by the whole symbol.
4693pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
4694 use crate::mvstack::{
4695 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4696 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4697 single_ref_p5_ctx, single_ref_p6_ctx,
4698 };
4699 let (a, a1) = stack.above_refs;
4700 let (l, l1) = stack.left_refs;
4701 let comp_mode = comp_mode_single_bits(stack);
4702 let backward = ref_frame >= BWDREF_FRAME;
4703 let p1 = symbol_bits(
4704 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4705 usize::from(backward),
4706 );
4707 if backward {
4708 let is_altref = ref_frame == ALTREF_FRAME;
4709 let p2 = symbol_bits(
4710 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
4711 usize::from(is_altref),
4712 );
4713 return comp_mode
4714 + p1
4715 + p2
4716 + if is_altref {
4717 0.0
4718 } else {
4719 symbol_bits(
4720 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
4721 usize::from(ref_frame == ALTREF2_FRAME),
4722 )
4723 };
4724 }
4725 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4726 comp_mode
4727 + p1
4728 + symbol_bits(
4729 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4730 usize::from(far),
4731 )
4732 + if far {
4733 symbol_bits(
4734 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4735 usize::from(ref_frame == GOLDEN_FRAME),
4736 )
4737 } else {
4738 symbol_bits(
4739 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4740 usize::from(ref_frame == LAST2_FRAME),
4741 )
4742 }
4743}
4744
4745pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
4746 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
4747 let width = cdf[symbol] - low;
4748 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
4749 // 32769 prices a symbol can carry; the `log2` behind each is computed
4750 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
4751 // profile -- this function is called for every symbol of every candidate
4752 // the RD search prices). Each entry is exactly the expression this used
4753 // to evaluate, so every price is bit-identical.
4754 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
4755 PRICES.get_or_init(|| {
4756 (0..=32768u32)
4757 .map(|w| -(f64::from(w) / 32768.0).log2())
4758 .collect()
4759 })[usize::from(width)]
4760}
4761
4762/// What the tile writer spends to say a block is coded in each of the thirteen
4763/// modes, given the modes of the blocks above it and to its left: the luma mode
4764/// symbol against the CDF those two neighbours pick, the angle delta a
4765/// directional mode carries, and the chroma mode symbol, whose CDF the luma
4766/// mode itself indexes.
4767///
4768/// Without this the search is blind to what a mode costs to name, which is not
4769/// a rounding error: a directional mode on a picture that does not run that way
4770/// is a rate loss the squared error never sees.
4771/// Codes one square of the picture as a single block: searches the luma mode,
4772/// codes both chroma planes DC, and hands back the block and what it cost --
4773/// squared error plus lambda times the bits its symbols spend.
4774/// How many halvings of a `side`-square block's transform the `tx_depth`
4775/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
4776/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
4777fn max_tx_depth(side: usize) -> usize {
4778 match side {
4779 8 => 1,
4780 16 | 32 => 2,
4781 _ => 0,
4782 }
4783}
4784
4785/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
4786/// Priced at context row 0 -- the writer picks the real row from its
4787/// neighbours' transform sizes, which the search has no view of; the term is
4788/// the same for every depth of one block either way, so it only shifts the
4789/// depth-0-versus-split margin, never the ordering between two splits.
4790fn tx_depth_bits(side: usize, depth: usize) -> f64 {
4791 match side {
4792 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
4793 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
4794 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
4795 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
4796 }
4797}
4798
4799/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4800/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4801/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4802/// (the mode search's own weight); below 1 the split trial is charged less
4803/// for its bits and fires more often.
4804///
4805/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4806/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4807/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4808/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4809/// so what is mis-calibrated is the weight the split's rate is judged under,
4810/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4811pub(crate) fn split_lambda_mult() -> f64 {
4812 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4813 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4814 .ok()
4815 .and_then(|v| v.parse().ok())
4816 .unwrap_or(SPLIT_LAMBDA)
4817 });
4818 *M
4819}
4820
4821/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4822/// the sweep that chose it.
4823const SPLIT_LAMBDA: f64 = 1.0;
4824
4825/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4826/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
4827/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
4828/// trials offered, trials the split won, then the (rate, distortion) of the
4829/// split and flat arms summed apart for the split-won and flat-won trials --
4830/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
4831static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
4832 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
4833
4834/// Whether [`SPLIT_CENSUS`] is armed, read once.
4835pub(crate) fn split_census_on() -> bool {
4836 static ON: std::sync::LazyLock<bool> =
4837 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
4838 *ON
4839}
4840
4841/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
4842/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
4843fn split_census_base(site: usize, key: bool, side: usize) -> usize {
4844 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
4845 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
4846}
4847
4848/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
4849/// `(rate in bits, distortion as squared error)`.
4850fn split_census(
4851 site: usize,
4852 key: bool,
4853 side: usize,
4854 split_won: bool,
4855 split: (f64, f64),
4856 flat: (f64, f64),
4857) {
4858 use std::sync::atomic::Ordering::Relaxed;
4859 let base = split_census_base(site, key, side);
4860 let add = |i: usize, v: u64| {
4861 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
4862 };
4863 add(0, 1);
4864 let off = if split_won {
4865 add(1, 1);
4866 2
4867 } else {
4868 6
4869 };
4870 let (win, lose) = if split_won {
4871 (split, flat)
4872 } else {
4873 (flat, split)
4874 };
4875 add(off, (win.0 * 64.0).max(0.0) as u64);
4876 add(off + 1, win.1.max(0.0) as u64);
4877 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
4878 add(off + 3, lose.1.max(0.0) as u64);
4879}
4880
4881/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
4882/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
4883/// last table a run prints is the whole encode's total (there is no flush
4884/// hook the encoder API guarantees to reach).
4885pub(crate) fn dump_split_census() {
4886 use std::sync::atomic::Ordering::Relaxed;
4887 eprintln!(
4888 "SPLITCENSUS site frame side offered split share% \
4889 win_rate win_dist lose_rate lose_dist"
4890 );
4891 for site in 0..2 {
4892 for key in [true, false] {
4893 for side_idx in 0..4 {
4894 let base = split_census_base(site, key, 8 << side_idx);
4895 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
4896 if v[0] == 0 {
4897 continue;
4898 }
4899 let (n, s) = (v[0] as f64, v[1] as f64);
4900 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
4901 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
4902 // all `n` trials, not a mean of two means.
4903 eprintln!(
4904 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
4905 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
4906 if site == 0 { "intra" } else { "inter" },
4907 if key { "key " } else { "inter" },
4908 8 << side_idx,
4909 v[0],
4910 v[1],
4911 100.0 * s / n,
4912 (v[2] + v[6]) as f64 / n / 64.0,
4913 (v[3] + v[7]) as f64 / n,
4914 (v[4] + v[8]) as f64 / n / 64.0,
4915 (v[5] + v[9]) as f64 / n,
4916 );
4917 }
4918 }
4919 }
4920}
4921
4922/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
4923/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
4924/// its mode/reference syntax and not the search's own cost function
4925/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
4926/// control; below 1 a coded vector is charged less and `NEWMV` wins more
4927/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
4928pub(crate) fn mv_lambda_mult() -> f64 {
4929 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4930 crate::envflags::var("EC_AV1_MV_LAMBDA")
4931 .ok()
4932 .and_then(|v| v.parse().ok())
4933 .unwrap_or(MV_LAMBDA)
4934 });
4935 *M
4936}
4937
4938/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
4939const MV_LAMBDA: f64 = 1.0;
4940
4941/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
4942/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
4943/// which the RD cost multiplies by lambda). Zero at the default weight.
4944fn mv_rate_surcharge(mv_bits: f64) -> f64 {
4945 (mv_lambda_mult() - 1.0) * mv_bits
4946}
4947
4948/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
4949/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
4950/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
4951/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
4952/// cost it won by, 4 the summed cost it lost by, 5 the summed
4953/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
4954/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
4955/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
4956/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
4957/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
4958static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
4959 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
4960
4961/// Whether [`NEWMV_CENSUS`] is armed, read once.
4962pub(crate) fn newmv_census_on() -> bool {
4963 static ON: std::sync::LazyLock<bool> =
4964 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
4965 *ON
4966}
4967
4968/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
4969fn newmv_census_global(i: usize) {
4970 if newmv_census_on() {
4971 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4972 }
4973}
4974
4975/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
4976/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
4977/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
4978/// candidate's own; both `f64::INFINITY` is a block that offered neither.
4979fn newmv_census_block(
4980 side: usize,
4981 offered: bool,
4982 new_cost: f64,
4983 other_cost: f64,
4984 mv: (i32, i32),
4985 nearest: (i32, i32),
4986 mv_bits: f64,
4987) {
4988 if !newmv_census_on() {
4989 return;
4990 }
4991 use std::sync::atomic::Ordering::Relaxed;
4992 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
4993 let add = |i: usize, v: u64| {
4994 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
4995 };
4996 add(0, 1);
4997 if !offered {
4998 return;
4999 }
5000 add(1, 1);
5001 if new_cost < other_cost {
5002 add(2, 1);
5003 add(3, (other_cost - new_cost).max(0.0) as u64);
5004 } else {
5005 add(4, (new_cost - other_cost).max(0.0) as u64);
5006 }
5007 add(
5008 5,
5009 ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64,
5010 );
5011 if mv == nearest {
5012 add(6, 1);
5013 }
5014 add(7, (mv_bits * 64.0).max(0.0) as u64);
5015}
5016
5017/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
5018/// same guard [`dump_split_census`] rides (cumulative, so the last table a
5019/// run prints is the whole encode's).
5020pub(crate) fn dump_newmv_census() {
5021 use std::sync::atomic::Ordering::Relaxed;
5022 eprintln!(
5023 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
5024 mv_dist_q3 mv==nearest% mv_bits"
5025 );
5026 for side_idx in 0..4 {
5027 let base = side_idx * 8;
5028 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
5029 if v[0] == 0 {
5030 continue;
5031 }
5032 let off = v[1].max(1) as f64;
5033 eprintln!(
5034 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
5035 8 << side_idx,
5036 v[0],
5037 v[1],
5038 v[2],
5039 100.0 * v[2] as f64 / off,
5040 v[3] as f64 / v[2].max(1) as f64,
5041 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
5042 v[5] as f64 / off,
5043 100.0 * v[6] as f64 / off,
5044 v[7] as f64 / off / 64.0,
5045 );
5046 }
5047 // lane-hpmv: how many mv components this encode coded an eighth-pel bit
5048 // for, and how many of those named a vector no non-hp frame can code.
5049 let (hp_all, hp_eighth) = crate::tile::hp_symbols();
5050 eprintln!(
5051 "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)",
5052 100.0 * hp_eighth as f64 / hp_all.max(1) as f64,
5053 );
5054 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
5055 eprintln!(
5056 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
5057 leaf second reference {}/{} ({:.1}%)",
5058 g[1],
5059 g[0],
5060 100.0 * g[1] as f64 / g[0].max(1) as f64,
5061 g[3],
5062 g[2],
5063 100.0 * g[3] as f64 / g[2].max(1) as f64,
5064 );
5065 let [
5066 calls,
5067 evals,
5068 _subpel,
5069 rounds,
5070 near_pred,
5071 unmoved,
5072 widest,
5073 widest_moves,
5074 ] = crate::motion::take_census();
5075 let per = |n: u64| n as f64 / calls.max(1) as f64;
5076 eprintln!(
5077 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
5078 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
5079 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
5080 per(evals),
5081 per(rounds),
5082 100.0 * near_pred as f64 / calls.max(1) as f64,
5083 100.0 * unmoved as f64 / calls.max(1) as f64,
5084 100.0 * widest as f64 / calls.max(1) as f64,
5085 per(widest_moves),
5086 );
5087}
5088
5089/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
5090/// the intra witness's fire count stays its own.
5091pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
5092 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
5093
5094/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
5095/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
5096/// `0` compares types on reconstruction error alone, which is what separates
5097/// a rate-term calibration (class `rd-rate-term-calibration`) from a
5098/// distortion the trial mis-measures.
5099pub(crate) fn tx_type_lambda_mult() -> f64 {
5100 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
5101 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
5102 .ok()
5103 .and_then(|v| v.parse().ok())
5104 .unwrap_or(1.0)
5105 });
5106 *M
5107}
5108
5109/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
5110/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
5111/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
5112/// question needs: at weight 1 the five-type intra search spends 1.2% more
5113/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
5114/// of the type it picks.
5115pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
5116 if tx_type == TxType::DctDct {
5117 0.0
5118 } else {
5119 lambda * (tx_type_lambda_mult() - 1.0) * bits
5120 }
5121}
5122
5123/// lane-txrd instrument: over the FLAT inter luma decision, the summed
5124/// reconstruction error and priced bits of the type the search chose against
5125/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
5126/// integer counter. `EC_AV1_TXRD_CENSUS`.
5127pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
5128 std::sync::atomic::AtomicU64::new(0),
5129 std::sync::atomic::AtomicU64::new(0),
5130 std::sync::atomic::AtomicU64::new(0),
5131 std::sync::atomic::AtomicU64::new(0),
5132 std::sync::atomic::AtomicU64::new(0),
5133 std::sync::atomic::AtomicU64::new(0),
5134 std::sync::atomic::AtomicU64::new(0),
5135];
5136
5137/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
5138/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
5139#[cfg(test)]
5140pub(crate) fn take_txrd_stats() -> [u64; 7] {
5141 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5142}
5143
5144/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
5145#[cfg(test)]
5146pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
5147 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
5148}
5149
5150/// How many luma transform units resolved to each [`TxType`], indexed by the
5151/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
5152/// and the instrument that says which types the search actually reaches.
5153pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
5154 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
5155
5156/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
5157/// counts to its own encode.
5158#[cfg(test)]
5159pub(crate) fn take_tx_type_hits() -> [usize; 16] {
5160 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
5161}
5162
5163/// How many blocks resolved to each `tx_depth`, the fire count that says
5164/// whether the depth search below reaches its candidates at all.
5165static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
5166 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
5167
5168/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
5169/// to its own encode.
5170#[cfg(test)]
5171pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
5172 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5173}
5174
5175/// How many inter blocks resolved to each var-tx depth (0 = one transform
5176/// over the whole block, 1 = its four halves), the fire count a gate prints
5177/// to see the split search reach its candidates at all. Indexed
5178/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
5179/// says which of the four block classes the split reaches -- the 32x32 root
5180/// and the compound blocks are this lane's two new ones.
5181static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
5182 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5183
5184/// Whether a 32x32 inter winner searches its own var-tx depth (the four
5185/// 16x16 units against the flat transform) instead of coding depth 0 blind.
5186/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
5187///
5188/// Rejected three times on the bars rows of the native gate (flat to +0.3).
5189/// lane-av1resweep re-judged it on the two REAL film crops at
5190/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
5191/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
5192///
5193/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
5194/// |---|---|---|---|
5195/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
5196/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
5197/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
5198/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
5199/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
5200///
5201/// The bars rows are ~90% zero-intra-cost cells, so the split never had
5202/// residual to reach there -- the tool was being judged on content that
5203/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
5204fn tx32_depth_search() -> bool {
5205 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5206 crate::envflags::var("EC_AV1_TX32_DEPTH")
5207 .ok()
5208 .map(|v| !matches!(v.as_str(), "0" | "off"))
5209 });
5210 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
5211}
5212
5213/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
5214/// trial units have to be predicted from BOTH references
5215/// ([`mc_trial_compound`]) or the split would re-predict them by single-
5216/// reference translation, which is not what the decoder reconstructs.
5217/// ON by default (the table on [`tx32_depth_search`]: on real film it is
5218/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
5219/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
5220/// `EC_AV1_COMP_VARTX`.
5221fn compound_var_tx() -> bool {
5222 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5223 crate::envflags::var("EC_AV1_COMP_VARTX")
5224 .ok()
5225 .map(|v| !matches!(v.as_str(), "0" | "off"))
5226 });
5227 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
5228}
5229
5230/// How many 32x32-and-below inter blocks each reference frame won, indexed by
5231/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
5232/// fire count a gate prints to see an extra reference reach a block at all
5233/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
5234/// chosen is a pyramid that costs bytes and buys nothing).
5235static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
5236 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5237
5238/// Reads [`REF_FRAME_HITS`] and zeroes it.
5239#[cfg(test)]
5240pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
5241 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
5242}
5243
5244/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
5245#[cfg(test)]
5246pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
5247 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5248}
5249
5250/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
5251/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
5252/// is one flag, depth 1 is a split root plus one unsplit flag per child
5253/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
5254/// or a 4x4 sub-size).
5255fn txfm_split_bits(side: usize, depth: usize) -> f64 {
5256 let max_tx = side.min(64);
5257 let ctx = |tx: usize| {
5258 crate::decode::txfm_partition_ctx_rect(
5259 crate::decode::TXFM_CTX_INIT,
5260 crate::decode::TXFM_CTX_INIT,
5261 side,
5262 tx,
5263 tx,
5264 )
5265 };
5266 if depth == 0 {
5267 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
5268 }
5269 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
5270 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
5271}
5272
5273/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
5274/// type is never coded -- the decoder takes the LUMA type of the block's
5275/// chroma-reference position and reduces it to the set the chroma size allows
5276/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
5277/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
5278/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
5279/// basis they were never produced for: on the bars gate row the luma of the
5280/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
5281/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
5282/// collapse two lanes attributed to the type PRICE (class
5283/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
5284/// field the encoder never mirrored).
5285///
5286/// Re-codes the two chroma planes of a committed inter block at the type the
5287/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
5288/// the trials the caller already holds are right.
5289#[allow(clippy::too_many_arguments)]
5290fn recode_inter_chroma(
5291 chroma: &[Plane; 2],
5292 (x, y): (usize, usize),
5293 side: usize,
5294 mv: (i32, i32),
5295 refs: [(&[u16], usize, usize, usize); 2],
5296 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
5297 search: &Search,
5298 set: TxbSet,
5299 luma_tx_type: TxType,
5300 fctx: &crate::decode::FrameCtx,
5301) -> Option<[Trial; 2]> {
5302 let c = side / 2;
5303 let tx =
5304 crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
5305 if tx == TxType::DctDct {
5306 return None;
5307 }
5308 Some([0usize, 1].map(|p| match second {
5309 Some((mv1, r1)) => mc_trial_compound_typed(
5310 &chroma[p],
5311 x / 2,
5312 y / 2,
5313 c,
5314 (mv, mv1),
5315 false,
5316 refs[p],
5317 r1[p],
5318 search.base_q_idx,
5319 search.deadzone,
5320 set,
5321 tx,
5322 fctx,
5323 ),
5324 None => mc_trial_typed(
5325 &chroma[p],
5326 x / 2,
5327 y / 2,
5328 c,
5329 mv,
5330 false,
5331 refs[p].0,
5332 refs[p].1,
5333 refs[p].2,
5334 refs[p].3,
5335 false,
5336 search.base_q_idx,
5337 search.deadzone,
5338 set,
5339 tx,
5340 fctx,
5341 ),
5342 }))
5343}
5344
5345/// The inter block's own var-tx decision, once its motion vector is settled:
5346/// its residual as ONE transform over the whole block, or as the four
5347/// transforms of half the side the tree's first halving names. The prediction
5348/// is the same motion compensation either way, so the split trial
5349/// re-transforms the identical residual in four pieces -- it wins where four
5350/// small transforms carry a locally varying residual cheaper than one big
5351/// one. Commits the winner into `luma` and hands back its block-coordinate
5352/// levels, the depth the writer codes and the cost the winner adds to (or
5353/// takes off) the caller's already-computed flat cost.
5354///
5355/// Only for a block wholly inside the frame: past the true edge the reader's
5356/// var-tx recursion skips the units that fall outside
5357/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
5358/// leave the residual units this writes unpaired.
5359#[allow(clippy::too_many_arguments)]
5360fn commit_inter_luma(
5361 luma: &mut Plane,
5362 (x, y): (usize, usize),
5363 side: usize,
5364 mv: (i32, i32),
5365 reference: (&[u16], usize, usize, usize),
5366 search: &Search,
5367 flat: &Trial,
5368 skip: bool,
5369 // A COMPOUND winner's second half: the vector and reference planes the
5370 // trial units are blended from ([`mc_trial_compound`], the decoder's own
5371 // `comp_group_idx == 0` average). `None` is the single-reference block.
5372 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
5373 fctx: &crate::decode::FrameCtx,
5374) -> (Vec<i32>, u8, f64, Vec<TxType>) {
5375 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
5376 // type out of the two-type inter set the writer already codes a symbol
5377 // for, priced the same way the intra search is (sse + lambda * bits, the
5378 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
5379 // block codes no residual and the 64-point transform names no type.
5380 let mut flat_typed: Option<Trial> = None;
5381 let mut flat_type = TxType::DctDct;
5382 if !skip {
5383 // lane-intertx: on a `reduced_tx_set = 0` frame the search names the
5384 // Set1 alphabet the writer codes into ([`luma_set_for`], the shape
5385 // the intra search already takes), which is what makes the wider
5386 // seven-type candidate list below reachable -- and prices every
5387 // candidate, `IDTX` included, in the alphabet its symbol is really
5388 // coded into.
5389 if let Some(fset) = inter_luma_set(side).map(|set| luma_set_for(set, search.screen)) {
5390 let lambda = search.lambda * tx_type_lambda_mult();
5391 let cost = |t: &Trial| t.sse + lambda * t.bits;
5392 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
5393 if tx_type == TxType::DctDct {
5394 continue;
5395 }
5396 let candidate = match second {
5397 Some((mv1, ref1)) => mc_trial_compound_typed(
5398 luma,
5399 x,
5400 y,
5401 side,
5402 (mv, mv1),
5403 true,
5404 reference,
5405 ref1,
5406 search.base_q_idx,
5407 search.deadzone,
5408 fset,
5409 tx_type,
5410 fctx,
5411 ),
5412 None => mc_trial_typed(
5413 luma,
5414 x,
5415 y,
5416 side,
5417 mv,
5418 true,
5419 reference.0,
5420 reference.1,
5421 reference.2,
5422 reference.3,
5423 false,
5424 search.base_q_idx,
5425 search.deadzone,
5426 fset,
5427 tx_type,
5428 fctx,
5429 ),
5430 };
5431 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
5432 flat_type = tx_type;
5433 flat_typed = Some(candidate);
5434 }
5435 }
5436 }
5437 }
5438 // Counted at the return points, so the census names the types the block
5439 // really CODES -- a split unit's winner that the flat cost then beats was
5440 // never written (class `counter from refused stream`).
5441 let count = |types: &[TxType]| {
5442 for &t in types {
5443 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5444 }
5445 };
5446 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
5447 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
5448 use std::sync::atomic::Ordering::Relaxed;
5449 TXRD_STATS[0].fetch_add(1, Relaxed);
5450 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
5451 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
5452 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
5453 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
5454 // Is the `DCT_DCT` baseline the search compares against the trial
5455 // THIS function would build for the same block? A stale or
5456 // differently-predicted baseline is what would let a candidate win on
5457 // both terms at once (class `local-rd-on-references` vs a real
5458 // pricing defect); re-predicting it here is the only way to tell.
5459 if let Some(fset) = inter_luma_set(side) {
5460 let here = match second {
5461 Some((mv1, ref1)) => mc_trial_compound_typed(
5462 luma,
5463 x,
5464 y,
5465 side,
5466 (mv, mv1),
5467 true,
5468 reference,
5469 ref1,
5470 search.base_q_idx,
5471 search.deadzone,
5472 fset,
5473 TxType::DctDct,
5474 fctx,
5475 ),
5476 None => mc_trial_typed(
5477 luma,
5478 x,
5479 y,
5480 side,
5481 mv,
5482 true,
5483 reference.0,
5484 reference.1,
5485 reference.2,
5486 reference.3,
5487 false,
5488 search.base_q_idx,
5489 search.deadzone,
5490 fset,
5491 TxType::DctDct,
5492 fctx,
5493 ),
5494 };
5495 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
5496 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
5497 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
5498 let n = TXRD_STATS[0].load(Relaxed);
5499 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
5500 eprintln!(
5501 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
5502 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
5503 sse={:.0} bits={:.1}",
5504 second.is_some(),
5505 flat.sse,
5506 flat.bits,
5507 here.sse,
5508 here.bits,
5509 flat_ref.sse,
5510 flat_ref.bits,
5511 );
5512 }
5513 }
5514 }
5515 // What the caller's already-counted `flat` cost has to be corrected by
5516 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
5517 let flat_gain =
5518 (flat_ref.sse + search.lambda * flat_ref.bits) - (flat.sse + search.lambda * flat.bits);
5519 let eligible = tx_select()
5520 && tx_select_inter()
5521 && !skip
5522 && side >= 16
5523 && (second.is_none() || compound_var_tx())
5524 && (side != BLOCK || tx32_depth_search())
5525 && x + side <= luma.true_width
5526 && y + side <= luma.true_height;
5527 if !eligible {
5528 luma.commit(x, y, side, flat_ref);
5529 count(&[flat_type]);
5530 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
5531 }
5532 let tx = side / 2;
5533 let set = luma_set_for(
5534 if tx >= 32 {
5535 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
5536 TxbSet::Luma32Inter
5537 } else if tx >= 16 {
5538 TxbSet::Luma16Inter
5539 } else {
5540 TxbSet::Luma8Inter
5541 },
5542 search.screen,
5543 );
5544 let mut levels = vec![0i32; side * side];
5545 let (mut sse, mut bits) = (0.0, 0.0);
5546 let mut units = Vec::with_capacity(4);
5547 // The split units are smaller than their block, so their `txb_skip`
5548 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
5549 // each unit's own commit publishes what the next one reads, coding order.
5550 luma.ctx.tu_split = true;
5551 // One type per unit in the writer's own raster order (tile.rs
5552 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
5553 let mut split_types = vec![TxType::DctDct; 4];
5554 for tu_row in 0..2 {
5555 for tu_col in 0..2 {
5556 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
5557 let unit = |tx_type: TxType| match second {
5558 Some((mv1, ref1)) => mc_trial_compound_typed(
5559 luma,
5560 tu_x,
5561 tu_y,
5562 tx,
5563 (mv, mv1),
5564 true,
5565 reference,
5566 ref1,
5567 search.base_q_idx,
5568 search.deadzone,
5569 set,
5570 tx_type,
5571 fctx,
5572 ),
5573 None => mc_trial_typed(
5574 luma,
5575 tu_x,
5576 tu_y,
5577 tx,
5578 mv,
5579 true,
5580 reference.0,
5581 reference.1,
5582 reference.2,
5583 reference.3,
5584 false,
5585 search.base_q_idx,
5586 search.deadzone,
5587 set,
5588 tx_type,
5589 fctx,
5590 ),
5591 };
5592 let mut best: Option<(f64, TxType, Trial)> = None;
5593 for &tx_type in inter_tx_type_candidates(set, search.screen) {
5594 let candidate = unit(tx_type);
5595 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
5596 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
5597 best = Some((cost, tx_type, candidate));
5598 }
5599 }
5600 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
5601 split_types[tu_row * 2 + tu_col] = tx_type;
5602 sse += trial.sse;
5603 bits += trial.bits;
5604 for row in 0..tx {
5605 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
5606 .copy_from_slice(&trial.levels[row * tx..][..tx]);
5607 }
5608 units.push((tu_x, tu_y, trial));
5609 }
5610 }
5611 luma.ctx.tu_split = false;
5612 let split_rate = bits + txfm_split_bits(side, 1);
5613 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
5614 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
5615 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
5616 if split_census_on() {
5617 split_census(
5618 1,
5619 false,
5620 side,
5621 split_cost < flat_cost,
5622 (split_rate, sse),
5623 (flat_rate, flat_ref.sse),
5624 );
5625 }
5626 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
5627 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
5628 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
5629 // in the leaf row (class `gate-blind-to-feature`).
5630 let counted = side <= BLOCK;
5631 if split_cost < flat_cost {
5632 for (tu_x, tu_y, trial) in &units {
5633 luma.commit(*tu_x, *tu_y, tx, trial);
5634 }
5635 if counted {
5636 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5637 }
5638 count(&split_types);
5639 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
5640 }
5641 if counted {
5642 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5643 }
5644 luma.commit(x, y, side, flat_ref);
5645 count(&[flat_type]);
5646 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
5647}
5648
5649/// The largest distinct-colour count a block may hold and still be offered a
5650/// palette candidate at all: past it the k-means quantisation costs more
5651/// error than the map saves rate, and every trial is wasted wall.
5652///
5653/// Swept on the gate's own screen capture (lane-av1pal2, the
5654/// `unswept-decision-constants` class): 32 (the value this lane inherited)
5655/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
5656/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
5657/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
5658/// binds on nothing this content holds. 128 ships: best BD against both
5659/// references and no wall cost at all (6.1s, the same as at 32, because the
5660/// blocks it newly admits are ones the RD then keeps).
5661/// `EC_AV1_PAL_MAXCOLORS`.
5662fn palette_max_colors() -> usize {
5663 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5664 *N.get_or_init(|| {
5665 std::env::var("EC_AV1_PAL_MAXCOLORS")
5666 .ok()
5667 .and_then(|v| v.parse().ok())
5668 .unwrap_or(128)
5669 })
5670}
5671
5672/// The palettes worth trying for one block's luma, in the shape libaom's
5673/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
5674/// distinct colours takes them ALL (the prediction is then exact and the
5675/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
5676/// one-dimensional Lloyd iteration seeded evenly across its range -- both
5677/// offered, because which wins is an RD question the caller answers.
5678/// `block` is `side*side` source samples, row-major.
5679fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
5680 let mut histogram = [0u32; 256];
5681 for &v in block {
5682 histogram[usize::from(v)] += 1;
5683 }
5684 let present: Vec<u16> = (0..256u16)
5685 .filter(|&v| histogram[usize::from(v)] > 0)
5686 .collect();
5687 if present.len() < 2 {
5688 return Vec::new();
5689 }
5690 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
5691 let mut base = [0u16; 8];
5692 base[..colors.len()].copy_from_slice(colors);
5693 let map = block
5694 .iter()
5695 .map(|&v| {
5696 colors
5697 .iter()
5698 .enumerate()
5699 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
5700 .map(|(i, _)| i as u8)
5701 .expect("a palette holds at least two colours")
5702 })
5703 .collect();
5704 crate::tile::PaletteY {
5705 size: colors.len() as u8,
5706 colors: base,
5707 map,
5708 }
5709 };
5710 if present.len() <= 8 {
5711 return vec![exact(&present)];
5712 }
5713 if present.len() > palette_max_colors() {
5714 return Vec::new();
5715 }
5716 let (lo, hi) = (i32::from(present[0]), i32::from(present[present.len() - 1]));
5717 let mut out = Vec::with_capacity(2);
5718 for n in [8usize, 4] {
5719 // Even seeding across the block's own range, then four Lloyd passes
5720 // over the histogram (256 bins, not `side*side` pixels).
5721 let mut centres: Vec<f64> = (0..n)
5722 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
5723 .collect();
5724 for _ in 0..4 {
5725 let mut sums = vec![0f64; n];
5726 let mut counts = vec![0u32; n];
5727 for (v, &count) in histogram.iter().enumerate() {
5728 if count == 0 {
5729 continue;
5730 }
5731 let k = (0..n)
5732 .min_by(|&a, &b| {
5733 (centres[a] - v as f64)
5734 .abs()
5735 .total_cmp(&(centres[b] - v as f64).abs())
5736 })
5737 .expect("n >= 2");
5738 sums[k] += (v as u32 * count) as f64;
5739 counts[k] += count;
5740 }
5741 for k in 0..n {
5742 if counts[k] > 0 {
5743 centres[k] = sums[k] / f64::from(counts[k]);
5744 }
5745 }
5746 }
5747 let mut colors: Vec<u16> = centres
5748 .iter()
5749 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
5750 .collect();
5751 colors.sort_unstable();
5752 colors.dedup();
5753 if colors.len() >= 2 {
5754 out.push(exact(&colors));
5755 }
5756 }
5757 out
5758}
5759
5760#[allow(clippy::too_many_arguments)]
5761// ---------------------------------------------------------------------------
5762// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
5763// validity). A key frame that detected screen content and finds enough exact
5764// repeats in its own source sets `allow_intrabc`, which the spec forces every
5765// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
5766// its place when the copied blocks pay back the deblock/CDEF/LR the frame
5767// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
5768// ---------------------------------------------------------------------------
5769
5770/// Whether intra block copy is offered at all. **Off by default** --
5771/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
5772/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
5773/// but on the gate's real screen capture it MEASURED WORSE: setting
5774/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
5775/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
5776/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
5777/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
5778/// that detected no screen content.
5779fn intrabc_enabled() -> bool {
5780 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
5781 return forced;
5782 }
5783 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5784 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
5785}
5786
5787thread_local! {
5788 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
5789 /// probe runs both arms in one process, and the suite is one process, so
5790 /// an environment variable cannot separate them (same reason
5791 /// [`SCREEN_FORCE`] exists).
5792 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
5793}
5794
5795#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5796pub(crate) fn force_intrabc(value: Option<bool>) {
5797 INTRABC_FORCE.with(|c| c.set(value));
5798}
5799
5800/// How many of a screen frame's 16x16 blocks must have an exact repeat
5801/// somewhere else in the source before `allow_intrabc` is worth the in-loop
5802/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
5803/// constant class: `probe_intrabc_threshold` measures the arm at several
5804/// values.
5805fn intrabc_pct() -> usize {
5806 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5807 *N.get_or_init(|| {
5808 std::env::var("EC_AV1_INTRABC_PCT")
5809 .ok()
5810 .and_then(|v| v.parse().ok())
5811 .unwrap_or(10)
5812 })
5813}
5814
5815/// The pixel grid intrabc source positions are hashed on
5816/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
5817/// which keeps the block-hash table (and so the search) linear in the frame
5818/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
5819/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
5820/// bilinear interpolation decode.rs applies but this encoder does not.
5821fn intrabc_step() -> usize {
5822 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5823 *N.get_or_init(|| {
5824 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
5825 .ok()
5826 .and_then(|v| v.parse().ok())
5827 .unwrap_or(4);
5828 if n % 2 == 0 { n.max(2) } else { 4 }
5829 })
5830}
5831
5832/// The side of the luma square the block-hash table is keyed on.
5833const IBC_HASH: usize = 16;
5834
5835/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
5836/// the current one the source's bottom-right corner must already be. Under
5837/// 128 superblocks the same 256 pixels are two superblocks, which
5838/// [`Ibc::dv_valid`] derives from the size itself.
5839const INTRABC_DELAY_SB64: i32 = 4;
5840
5841/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
5842fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
5843 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
5844 for row in 0..IBC_HASH {
5845 let base = (y + row) * width + x;
5846 for &v in &plane[base..base + IBC_HASH] {
5847 h ^= u64::from(v);
5848 h = h.wrapping_mul(0x100_0000_01b3);
5849 }
5850 }
5851 h
5852}
5853
5854/// Every `intrabc_step()`-aligned position of `plane` inside
5855/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
5856fn ibc_index(
5857 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
5858 plane: &[u8],
5859 width: usize,
5860 (x0, y0): (usize, usize),
5861 (x1, y1): (usize, usize),
5862) {
5863 let step = intrabc_step();
5864 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
5865 return;
5866 }
5867 let mut y = y0.next_multiple_of(step);
5868 while y + IBC_HASH <= y1 {
5869 let mut x = x0.next_multiple_of(step);
5870 while x + IBC_HASH <= x1 {
5871 table
5872 .entry(ibc_hash(plane, width, x, y))
5873 .or_default()
5874 .push((x as u32, y as u32));
5875 x += step;
5876 }
5877 y += step;
5878 }
5879}
5880
5881/// Whether `screen`-detected source `y` repeats itself enough to be worth
5882/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
5883/// content appears at some other position, against [`intrabc_pct`]. Returns
5884/// the share as well, for the gate's own print.
5885fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
5886 if true_width < 4 * 64 || true_height < 2 * 64 {
5887 return (false, 0.0);
5888 }
5889 let mut table = std::collections::HashMap::new();
5890 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
5891 let (mut total, mut matched) = (0usize, 0usize);
5892 let mut by = 0;
5893 while by + IBC_HASH <= true_height {
5894 let mut bx = 0;
5895 while bx + IBC_HASH <= true_width {
5896 total += 1;
5897 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
5898 if hits
5899 .iter()
5900 .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by))
5901 {
5902 matched += 1;
5903 }
5904 }
5905 bx += IBC_HASH;
5906 }
5907 by += IBC_HASH;
5908 }
5909 let share = if total == 0 {
5910 0.0
5911 } else {
5912 matched as f64 / total as f64
5913 };
5914 (share * 100.0 >= intrabc_pct() as f64, share)
5915}
5916
5917/// One tile's intrabc search state: a block-hash table over the part of the
5918/// tile's own reconstruction that is already final (whole superblock rows --
5919/// the in-loop filters are off on this frame, so a coded superblock row never
5920/// changes again), plus the last DV chosen, which the RD price uses as its
5921/// predictor estimate.
5922struct Ibc {
5923 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
5924 /// source repeats exactly where a lossily coded reconstruction only
5925 /// nearly does, so an exact-match table over the reconstruction finds
5926 /// almost nothing. The candidate is then SCORED against the
5927 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
5928 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
5929 /// The tile's own luma rect, in samples.
5930 tile: (usize, usize, usize, usize),
5931 /// The DV the previous intrabc block of this tile took -- the *estimate*
5932 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
5933 /// against. The writer computes the true predictor off its own mi grid
5934 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
5935 /// a slightly mispriced candidate, never a wrong bitstream.
5936 last_dv: Option<(i32, i32)>,
5937 /// How many blocks took intrabc, and how many hash lookups found at least
5938 /// one valid candidate -- the gate's own fire counts.
5939 hits: usize,
5940 lookups: usize,
5941 found: usize,
5942}
5943
5944impl Ibc {
5945 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
5946 let mut table = std::collections::HashMap::new();
5947 ibc_index(
5948 &mut table,
5949 source,
5950 width,
5951 (tile.0, tile.1),
5952 (tile.2, tile.3),
5953 );
5954 Self {
5955 table,
5956 tile,
5957 last_dv: None,
5958 hits: 0,
5959 lookups: 0,
5960 found: 0,
5961 }
5962 }
5963
5964 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
5965 /// (1/8 pel), with this lane's own extra restriction on top: the source
5966 /// must lie entirely in a COMPLETED superblock row, which is exactly the
5967 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
5968 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
5969 /// wavefront's own diagonal) are legal and not searched; the upgrade path
5970 /// is to index the current row's finished superblocks too.
5971 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
5972 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
5973 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
5974 return false;
5975 }
5976 let (tx0, ty0, tx1, ty1) = (
5977 self.tile.0 as i32,
5978 self.tile.1 as i32,
5979 self.tile.2 as i32,
5980 self.tile.3 as i32,
5981 );
5982 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
5983 let (w, h) = (w as i32, h as i32);
5984 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
5985 return false;
5986 }
5987 // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
5988 // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
5989 // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
5990 // Counting 64s under a 128 superblock let the search take a source
5991 // from a 64 row the 128 visit order had not reconstructed yet.
5992 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
5993 let delay: i32 = if sb_log2 == 7 {
5994 INTRABC_DELAY_SB64 / 2
5995 } else {
5996 INTRABC_DELAY_SB64
5997 };
5998 let active_sb_row = (y as i32 - ty0) >> sb_log2;
5999 let active_sb_col = (x as i32 - tx0) >> sb_log2;
6000 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
6001 let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
6002 // This lane's own restriction (see the doc comment).
6003 if src_sb_row >= active_sb_row {
6004 return false;
6005 }
6006 let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
6007 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
6008 return false;
6009 }
6010 // libaom's wavefront: only the top-left cone of the frame is legal.
6011 let wf = (1 + delay) * (active_sb_row - src_sb_row);
6012 src_sb_col < active_sb_col - delay + wf
6013 }
6014}
6015
6016/// How many block searches ran, how many found at least one VALID candidate,
6017/// and how many won on rate-distortion -- the hash hit rate a gate prints
6018/// (class `gate-blind-to-feature`: "the search ran" and "the search found
6019/// something" and "the block took it" are three different claims).
6020static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
6021 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
6022
6023impl Drop for Ibc {
6024 fn drop(&mut self) {
6025 for (slot, n) in [self.lookups, self.found, self.hits]
6026 .into_iter()
6027 .enumerate()
6028 {
6029 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
6030 }
6031 }
6032}
6033
6034/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
6035/// its own encode.
6036#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6037pub(crate) fn take_intrabc_search() -> [usize; 3] {
6038 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
6039}
6040
6041/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
6042/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
6043/// infers rather than codes.
6044fn dv_component_bits(diff: i32) -> f64 {
6045 let z = diff.unsigned_abs() as i32 - 1;
6046 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
6047 let class = mv_class_of(z);
6048 bits += symbol_bits(&cdf::MV_CLASS, class);
6049 let local = z - mv_class_base(class);
6050 if class == 0 {
6051 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
6052 } else {
6053 let d = local >> 3;
6054 for i in 0..class {
6055 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
6056 }
6057 }
6058 bits
6059}
6060
6061/// What one block vector costs against `pred`, plus the `skip` and
6062/// `use_intrabc` flags the block carries and the ordinary intra block does
6063/// not pay in this currency.
6064fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
6065 let diff = (dv.0 - pred.0, dv.1 - pred.1);
6066 let joint = match (diff.0 != 0, diff.1 != 0) {
6067 (false, false) => 0,
6068 (false, true) => 1,
6069 (true, false) => 2,
6070 (true, true) => 3,
6071 };
6072 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
6073 if diff.0 != 0 {
6074 bits += dv_component_bits(diff.0);
6075 }
6076 if diff.1 != 0 {
6077 bits += dv_component_bits(diff.1);
6078 }
6079 bits
6080}
6081
6082/// The squared error of copying the `side`-square block at `(sx, sy)` of each
6083/// plane's reconstruction onto the source block at `(x, y)`, luma and both
6084/// chroma planes together -- what an intrabc block's whole (residual-free)
6085/// distortion is.
6086fn ibc_sse(
6087 luma: &Plane,
6088 chroma: &[Plane; 2],
6089 (x, y): (usize, usize),
6090 (sx, sy): (usize, usize),
6091 side: usize,
6092) -> f64 {
6093 // Inside the true frame only, for the reason [`Plane::block_sse`] is
6094 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
6095 // how well it copies the padding.
6096 let mut sse = 0.0f64;
6097 let clip = |whole: usize, inside: usize| match edge_sse() {
6098 true => whole.min(inside),
6099 false => whole,
6100 };
6101 let rows = clip(side, luma.true_height.saturating_sub(y));
6102 let cols = clip(side, luma.true_width.saturating_sub(x));
6103 for row in 0..rows {
6104 let src = &luma.source[(y + row) * luma.width + x..][..cols];
6105 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
6106 for (&s, &r) in src.iter().zip(rec) {
6107 let d = f64::from(i32::from(s) - i32::from(r));
6108 sse += d * d;
6109 }
6110 }
6111 let half = side / 2;
6112 for plane in chroma {
6113 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
6114 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
6115 for row in 0..rows {
6116 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
6117 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
6118 for (&s, &r) in src.iter().zip(rec) {
6119 let d = f64::from(i32::from(s) - i32::from(r));
6120 sse += d * d;
6121 }
6122 }
6123 }
6124 sse
6125}
6126
6127/// Copies the `side`-square block at `(sx, sy)` of each plane's
6128/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
6129/// since it carries no residual (`skip`). Full-pel in both planes by
6130/// construction ([`intrabc_step`] keeps every DV even), which is what makes
6131/// this a plain copy where decode.rs runs the bilinear kernel over the same
6132/// samples.
6133fn ibc_commit(
6134 luma: &mut Plane,
6135 chroma: &mut [Plane; 2],
6136 (x, y): (usize, usize),
6137 (sx, sy): (usize, usize),
6138 side: usize,
6139) {
6140 for row in 0..side {
6141 let from = (sy + row) * luma.width + sx;
6142 let to = (y + row) * luma.width + x;
6143 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
6144 luma.reconstruction[to..to + side].copy_from_slice(&copied);
6145 }
6146 let half = side / 2;
6147 for plane in chroma {
6148 for row in 0..half {
6149 let from = (sy / 2 + row) * plane.width + sx / 2;
6150 let to = (y / 2 + row) * plane.width + x / 2;
6151 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
6152 plane.reconstruction[to..to + half].copy_from_slice(&copied);
6153 }
6154 plane.commit_ctx_zero(x / 2, y / 2, half);
6155 }
6156 luma.commit_ctx_zero(x, y, side);
6157}
6158
6159/// Searches this block's own DV: every hash-table position whose 16x16 luma
6160/// square equals the block's source square, plus the previous block's DV as a
6161/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
6162/// the winning `(dv, cost)`, or `None` when nothing valid was found.
6163fn ibc_search(
6164 ibc: &mut Ibc,
6165 luma: &Plane,
6166 chroma: &[Plane; 2],
6167 (x, y): (usize, usize),
6168 side: usize,
6169 lambda: f64,
6170) -> Option<((i32, i32), f64, (usize, usize))> {
6171 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
6172 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
6173 let consider =
6174 |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
6175 let dv = ((sy as i32 - y as i32) * 8, (sx as i32 - x as i32) * 8);
6176 if !ibc.dv_valid(x, y, side, side, dv) {
6177 return;
6178 }
6179 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
6180 if best.as_ref().is_none_or(|b| cost < b.1) {
6181 *best = Some((dv, cost, (sx, sy)));
6182 }
6183 };
6184 ibc.lookups += 1;
6185 let key = ibc_hash(luma.source, luma.width, x, y);
6186 // The table is filled in raster order, so the entries BEFORE this block's
6187 // own position are exactly the already-coded ones -- and the nearest of
6188 // them costs the fewest DV bits. Walking backwards from the block's own
6189 // slot is what makes the search look up-and-left; taking the newest
6190 // entries outright only ever finds candidates below and to the right,
6191 // every one of which `dv_valid` rejects.
6192 let hits: Vec<(u32, u32)> = ibc
6193 .table
6194 .get(&key)
6195 .map(|h| {
6196 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
6197 h[..end].iter().rev().take(32).copied().collect()
6198 })
6199 .unwrap_or_default();
6200 for (hx, hy) in hits {
6201 consider(&*ibc, hx as usize, hy as usize, &mut best);
6202 }
6203 if let Some(dv) = ibc.last_dv {
6204 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
6205 if sx >= 0 && sy >= 0 {
6206 consider(&*ibc, sx as usize, sy as usize, &mut best);
6207 }
6208 }
6209 if best.is_some() {
6210 ibc.found += 1;
6211 }
6212 best
6213}
6214
6215fn code_square(
6216 luma: &mut Plane,
6217 chroma: &mut [Plane; 2],
6218 (x, y): (usize, usize),
6219 side: usize,
6220 search: &Search,
6221 mode_bits: &[f64; 13],
6222 // The frame header's `tx_mode == TxMode::Select`: the block then searches
6223 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
6224 // transform over its whole side.
6225 tx_select: bool,
6226 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
6227 // header did not set `allow_intrabc`.
6228 ibc: Option<&mut Ibc>,
6229 // Whether this is a KEY frame's block, read only by the split census
6230 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
6231 // which is this lane's whole finding.
6232 census_key: bool,
6233 fctx: &crate::decode::FrameCtx,
6234) -> (BlockCoeffs, f64) {
6235 let (luma_set, chroma_set) = if side == SUPERBLOCK {
6236 // A whole superblock coded as ONE intra block (lane-i64): one
6237 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
6238 // `code_from_prediction` hands back, and one TX_32X32 per chroma
6239 // plane -- the same three sets the key frame writer's
6240 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
6241 // uses (`search_skip_64`).
6242 (TxbSet::Luma64, TxbSet::Chroma32)
6243 } else if side == BLOCK {
6244 (TxbSet::Luma32, TxbSet::Chroma16)
6245 } else if side == 8 {
6246 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
6247 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
6248 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
6249 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
6250 // (this branch is still unreached), so leaving `Chroma8` here would
6251 // silently wire the wrong table the moment one does; `Chroma4` is
6252 // what a real caller needs.
6253 (TxbSet::Luma8, TxbSet::Chroma4)
6254 } else {
6255 (TxbSet::Luma16, TxbSet::Chroma8)
6256 };
6257 let at = At {
6258 x,
6259 y,
6260 side,
6261 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
6262 set: luma_set_for(luma_set, search.screen),
6263 };
6264 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
6265 luma.search_block(at, search, mode_bits, fctx);
6266 let mut luma_tx_types = vec![tx_type];
6267 // The depth search runs on the mode the whole-block transform picked --
6268 // libaom's own ordering, and the reason it costs one extra pass per depth
6269 // rather than one per (mode, depth) pair.
6270 let mut tx_depth = 0u8;
6271 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
6272 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
6273 // pays that zero exactly as a 32x32's depth search makes it pay
6274 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
6275 // below hands the root a symbol for free.
6276 if tx_select && side == SUPERBLOCK {
6277 cost += search.lambda * tx_depth_bits(side, 0);
6278 }
6279 if tx_select && max_tx_depth(side) > 0 {
6280 let mut best = (
6281 cost + search.lambda * tx_depth_bits(side, 0),
6282 0usize,
6283 luma.snapshot(x, y, side),
6284 luma_coeffs,
6285 );
6286 let mut best_types = std::mem::take(&mut luma_tx_types);
6287 // The census wants the flat arm's own (rate, distortion), which
6288 // `search_block` only hands back folded into one cost -- so under the
6289 // env flag alone it is re-coded at depth 0 and the plane restored.
6290 let census_flat = split_census_on().then(|| {
6291 let kept = luma.snapshot(x, y, side);
6292 let (_, sse, bits, _) =
6293 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
6294 luma.restore(x, y, side, &kept);
6295 (bits + tx_depth_bits(side, 0), sse)
6296 });
6297 let mut census_split: Option<(f64, f64)> = None;
6298 for depth in 1..=max_tx_depth(side) {
6299 let (levels, sse, bits, types) =
6300 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
6301 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
6302 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
6303 if census_flat.is_some() {
6304 let c = (bits + tx_depth_bits(side, depth), sse);
6305 if census_split
6306 .is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
6307 {
6308 census_split = Some(c);
6309 }
6310 }
6311 if cost_d < best.0 {
6312 best = (
6313 cost_d,
6314 depth,
6315 luma.snapshot(x, y, side),
6316 coeffs(&levels, side),
6317 );
6318 best_types = types;
6319 }
6320 }
6321 if let (Some(flat), Some(split)) = (census_flat, census_split) {
6322 split_census(0, census_key, side, best.1 > 0, split, flat);
6323 }
6324 luma_tx_types = best_types;
6325 luma.restore(x, y, side, &best.2);
6326 cost = best.0;
6327 tx_depth = best.1 as u8;
6328 luma_coeffs = best.3;
6329 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6330 }
6331 // The palette candidate is priced against the mode the luma search (and
6332 // its transform-depth search) already settled on, so a block only takes
6333 // one when it beats the best ordinary intra coding of the same pixels.
6334 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
6335 // prediction is the colour map, not the DC of its neighbours.
6336 let mut mode = mode;
6337 let mut angle_delta = angle_delta;
6338 let mut palette = None;
6339 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6340 let source: Vec<u8> = (y..y + side)
6341 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
6342 .collect();
6343 let kept = luma.snapshot(x, y, side);
6344 // spec 5.11.50: a block cut by the frame's right/bottom edge codes
6345 // its map over the ON-SCREEN corner only and the decoder replicates
6346 // that outward, so the searched map is folded the same way here --
6347 // the prediction priced, the reconstruction committed and the symbols
6348 // `write_color_index_map` writes are then one and the same map
6349 // (lane-palw).
6350 let on = (
6351 side.min(luma.true_width.saturating_sub(x)),
6352 side.min(luma.true_height.saturating_sub(y)),
6353 );
6354 for mut pal in palette_candidates(&source) {
6355 let n = usize::from(pal.size);
6356 crate::decode::palette_replicate(&mut pal.map, side, side, on);
6357 let prediction: Vec<u8> = pal
6358 .map
6359 .iter()
6360 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
6361 .collect();
6362 let trial = luma.code_from_prediction(
6363 x,
6364 y,
6365 side,
6366 &prediction,
6367 false,
6368 search.base_q_idx,
6369 search.deadzone,
6370 luma_set,
6371 );
6372 let cost_p = trial.sse
6373 + search.lambda
6374 * (trial.bits
6375 + mode_bits[DC_PRED as usize]
6376 + crate::tile::palette_bits(&pal, side, on)
6377 + if tx_select {
6378 tx_depth_bits(side, 0)
6379 } else {
6380 0.0
6381 });
6382 if cost_p < cost {
6383 cost = cost_p;
6384 mode = DC_PRED as u8;
6385 angle_delta = 0;
6386 tx_depth = 0;
6387 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
6388 luma.commit(x, y, side, &trial);
6389 palette = Some(pal);
6390 }
6391 }
6392 if palette.is_none() {
6393 luma.restore(x, y, side, &kept);
6394 }
6395 }
6396
6397 // The five recursive filter-intra modes (spec 5.11.14), priced against
6398 // whatever the mode, transform-depth and palette searches settled on --
6399 // the same "one candidate loop after the incumbent is known" shape the
6400 // palette above uses. A block that takes one is `DC_PRED` with no palette
6401 // by construction (`av1_filter_intra_allowed`), and its luma transform
6402 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
6403 //
6404 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
6405 // depth the ordinary intra search runs, each unit predicting recursively
6406 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
6407 // arm), so a block whose ordinary winner wanted a split transform is
6408 // compared against a filter arm that may split too.
6409 //
6410 // Measured (native BD table, lane-fitu): searching the depths on EVERY
6411 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
6412 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
6413 // locally cheaper reconstruction that the film rows go on to predict from
6414 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
6415 // content is where it pays, and a non-screen frame keeps the depth-0-only
6416 // arm, byte for byte.
6417 let mut filter_intra: Option<u8> = None;
6418 if filter_intra_on()
6419 && palette.is_none()
6420 && let Some(class) = crate::decode::filter_intra_size_class(side)
6421 {
6422 let row = &cdf::FILTER_INTRA[class];
6423 // With the sequence bit on, EVERY `DC_PRED` block without a luma
6424 // palette carries the flag, so the incumbent pays its zero before the
6425 // comparison -- otherwise the candidate is charged a bit the block
6426 // spends either way (class `price-the-narrowing-not-the-table`).
6427 if mode == DC_PRED {
6428 cost += search.lambda * symbol_bits(row, 0);
6429 }
6430 let one_bits = symbol_bits(row, 1);
6431 let kept = luma.snapshot(x, y, side);
6432 let max_depth = if tx_select && search.screen {
6433 max_tx_depth(side)
6434 } else {
6435 0
6436 };
6437 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
6438 for fi in 0..5u8 {
6439 for depth in 0..=max_depth {
6440 // A filter-intra block's units are coded through
6441 // `code_from_prediction`, which is `DCT_DCT` throughout, so
6442 // this arm keeps the empty (all-`DCT_DCT`) type list.
6443 let (levels, sse, bits, _) =
6444 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
6445 let cost_f = sse
6446 + search.lambda
6447 * (bits
6448 + mode_bits[DC_PRED as usize]
6449 + one_bits
6450 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
6451 + if tx_select {
6452 tx_depth_bits(side, depth)
6453 } else {
6454 0.0
6455 });
6456 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
6457 best = Some((
6458 cost_f,
6459 fi,
6460 depth,
6461 luma.snapshot(x, y, side),
6462 coeffs(&levels, side),
6463 ));
6464 }
6465 }
6466 }
6467 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
6468 cost = cost_f;
6469 mode = DC_PRED;
6470 angle_delta = 0;
6471 tx_depth = depth as u8;
6472 luma_coeffs = levels;
6473 luma.restore(x, y, side, &snapshot);
6474 filter_intra = Some(fi);
6475 } else {
6476 luma.restore(x, y, side, &kept);
6477 }
6478 }
6479
6480 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
6481 // planes; what it costs still counts towards the partition decision.
6482 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
6483 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
6484 cost += chroma_cost;
6485
6486 // The intrabc arm is priced against the WHOLE block -- luma and both
6487 // chroma planes, residual-free -- so it is compared after the chroma
6488 // search has added its own cost, not against the luma decision alone.
6489 if let Some(ibc) = ibc {
6490 if let Some((dv, cost_ibc, src)) =
6491 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
6492 {
6493 if cost_ibc < cost {
6494 ibc_commit(luma, chroma, (x, y), src, side);
6495 ibc.last_dv = Some(dv);
6496 ibc.hits += 1;
6497 return (
6498 BlockCoeffs {
6499 skip: true,
6500 dv: Some(dv),
6501 ..BlockCoeffs::default()
6502 },
6503 cost_ibc,
6504 );
6505 }
6506 }
6507 }
6508 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
6509 // (its levels came from `code_from_prediction`), so the searched types
6510 // belong to a block this one no longer is.
6511 if palette.is_some() || filter_intra.is_some() {
6512 luma_tx_types = Vec::new();
6513 }
6514 (
6515 BlockCoeffs {
6516 u,
6517 v,
6518 luma: luma_coeffs,
6519 mode,
6520 uv_mode,
6521 tx_depth,
6522 palette,
6523 palette_uv,
6524 filter_intra,
6525 cfl_alphas,
6526 angle_delta_y: angle_delta as i8,
6527 luma_tx_types,
6528 ..BlockCoeffs::default()
6529 },
6530 cost,
6531 )
6532}
6533
6534/// The chroma modes the search offers, and the only ones it may offer: each
6535/// predicts from the row directly above and the column directly to the left
6536/// and nothing further, so none of them needs the above-right/below-left
6537/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
6538/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
6539/// reconstruction and its own alpha syntax; both are left out here.
6540const CHROMA_MODES: [u8; 7] = [
6541 DC_PRED,
6542 V_PRED,
6543 H_PRED,
6544 SMOOTH_PRED,
6545 SMOOTH_V_PRED,
6546 SMOOTH_H_PRED,
6547 PAETH_PRED,
6548];
6549
6550/// The thirteen intra mode names, for the chroma fire count's print.
6551#[cfg(test)]
6552const UV_MODE_NAMES: [&str; 14] = [
6553 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", "SMOOTH_H",
6554 "PAETH", "CFL",
6555];
6556
6557/// How many blocks each chroma mode has won, indexed by the mode itself --
6558/// the fire count that says whether the search below reaches its candidates
6559/// at all (the `gate-blind-to-feature` class), printed once per gate run.
6560static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
6561 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
6562
6563/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
6564/// won, summed over both chroma planes -- the alpha histogram the gate prints
6565/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
6566/// magnitude only is a search that never left its first candidate).
6567static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
6568 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
6569
6570/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
6571/// zero on a CfL block", `1..=16` the magnitudes.
6572#[cfg(test)]
6573pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
6574 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6575}
6576
6577/// How many directional luma blocks won at each `angle_delta_y`, indexed
6578/// `delta + 3` -- the histogram that says whether the refinement below ever
6579/// leaves zero (`gate-blind-to-feature`).
6580static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
6581 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
6582
6583/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
6584#[cfg(test)]
6585pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
6586 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
6587}
6588
6589/// Whether the luma search refines a directional winner's `angle_delta_y`
6590/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
6591fn angle_delta_on() -> bool {
6592 static ENV: std::sync::LazyLock<Option<bool>> =
6593 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0"));
6594 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
6595}
6596
6597/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
6598/// switches it off, which is how the lane measured its own on/off pair).
6599fn cfl_on() -> bool {
6600 static ENV: std::sync::LazyLock<Option<bool>> =
6601 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0"));
6602 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
6603}
6604
6605/// Whether the intra search offers the five recursive filter-intra modes at
6606/// all, and with them whether the sequence header sets `enable_filter_intra`
6607/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
6608/// its own on/off pair -- and how every byte pin written before it still
6609/// reproduces). It is also a speed lever: on at preset 0, off above it.
6610// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
6611// it off for the whole process (a sequence-header field, so it cannot change
6612// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
6613// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
6614// this workspace.
6615
6616/// Whether a sequence codes 128x128 superblocks when the environment says
6617/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
6618/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
6619/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
6620/// 128x128 block in it every row of the native BD gate is down or flat on
6621/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
6622///
6623/// | row | 64 superblocks | 128 + the 128 root |
6624/// |---|---|---|
6625/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
6626/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
6627/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
6628/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
6629/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
6630///
6631/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
6632/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
6633///
6634/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
6635/// off (the delta_q unit at the 128 superblock, the superblock size travelling
6636/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
6637/// predictor and wavefront, and seven test harnesses that handed the encoder a
6638/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
6639pub(crate) const SB128_DEFAULT: bool = true;
6640
6641/// Whether this process's sequences code 128x128 superblocks. An ENCODER
6642/// knob (like `speed::SPEED`), never read by a decode: read through a
6643/// process-global (not a thread-local) because the tile writers run on
6644/// worker threads; `2` is "the environment has not been read yet".
6645static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
6646
6647/// Whether this process's sequences code 128x128 superblocks.
6648pub(crate) fn sb128_on() -> bool {
6649 use std::sync::atomic::Ordering::Relaxed;
6650 match ENC_SB128.load(Relaxed) {
6651 2 => {
6652 let on = crate::envflags::var("EC_AV1_SB128")
6653 .ok()
6654 .map_or(SB128_DEFAULT, |v| v != "0");
6655 ENC_SB128.store(u8::from(on), Relaxed);
6656 on
6657 }
6658 v => v == 1,
6659 }
6660}
6661
6662/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
6663/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
6664/// exactly like the speed-preset gates.
6665#[cfg(test)]
6666pub(crate) fn force_sb128(on: bool) {
6667 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
6668}
6669
6670/// The luma loop-restoration unit size this sequence codes: a 128 superblock
6671/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
6672/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
6673/// 128), which is the one filter parameter the superblock size moves.
6674pub(crate) fn lr_unit() -> u32 {
6675 if sb128_on() { 128 } else { 64 }
6676}
6677
6678pub(crate) fn filter_intra_on() -> bool {
6679 #[cfg(test)]
6680 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
6681 return forced;
6682 }
6683 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6684 crate::envflags::var("EC_AV1_FILTER_INTRA")
6685 .ok()
6686 .map(|v| v != "0")
6687 });
6688 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
6689}
6690
6691/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
6692/// to its own encode.
6693#[cfg(test)]
6694pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
6695 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6696}
6697
6698/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
6699/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
6700/// Returns each plane's levels, the mode, and what the pair cost (squared
6701/// error plus lambda times bits, the same currency the luma search speaks).
6702///
6703/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
6704/// which is what the luma mode decision was taken against, so what a
6705/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
6706/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
6707/// writer then has to code.
6708#[allow(clippy::too_many_arguments)]
6709/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
6710/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
6711/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
6712/// trials all seven, as before this lever.
6713///
6714/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
6715/// the search's largest trial population by far -- seven modes times two
6716/// planes for every intra block, against 3.7 luma trials -- and the RD
6717/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
6718/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
6719fn chroma_top_k() -> Option<usize> {
6720 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
6721 crate::envflags::var("EC_AV1_CHROMA_K")
6722 .ok()
6723 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
6724 });
6725 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
6726}
6727
6728/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
6729/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
6730/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
6731/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
6732/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
6733/// BD swings by about a point in either direction as near-tie chroma modes
6734/// flip, which is the measurement's own sensitivity, not a trend: nothing
6735/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
6736/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
6737/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
6738/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
6739pub(crate) const CHROMA_TOP_K: Option<usize> = None;
6740
6741fn search_chroma(
6742 chroma: &mut [Plane; 2],
6743 // The luma plane's RECONSTRUCTION under this block, already committed by
6744 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
6745 luma: &Plane,
6746 (x, y): (usize, usize),
6747 side: usize,
6748 set: TxbSet,
6749 search: &Search,
6750 luma_mode: u8,
6751 fctx: &crate::decode::FrameCtx,
6752) -> (
6753 [Vec<Coeff>; 2],
6754 u8,
6755 f64,
6756 Option<crate::tile::PaletteUv>,
6757 Option<(i32, i32)>,
6758) {
6759 let at = At {
6760 x: x / 2,
6761 y: y / 2,
6762 side: side / 2,
6763 reach: Reach::none(),
6764 set,
6765 };
6766 // The census's cheap proxy for a chroma mode: the SAD of its prediction
6767 // summed over both planes, ranked by the same rule the luma histogram
6768 // uses. Only built under `EC_AV1_CENSUS`.
6769 // The SAD of each mode's prediction, summed over both planes -- the
6770 // census's ranking rule, and what [`chroma_top_k`] prunes by.
6771 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
6772 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6773 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6774 u.iter()
6775 .zip(v.iter())
6776 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
6777 .collect()
6778 };
6779 let modes: Vec<u8> = match chroma_top_k() {
6780 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
6781 _ => CHROMA_MODES.to_vec(),
6782 };
6783 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
6784 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
6785 let ranking: Vec<(f64, u8)> = if census_on() {
6786 sad_scores(chroma)
6787 } else {
6788 Vec::new()
6789 };
6790 census_add(2, 1);
6791 census_add(3, modes.len());
6792 let mut best: Option<(f64, u8, Trial, Trial)> = None;
6793 for mode in modes {
6794 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
6795 if (V_PRED..=D67_PRED).contains(&mode) {
6796 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
6797 }
6798 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
6799 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
6800 // chroma of a 64x64 block is `DCT_DCT` whatever
6801 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
6802 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
6803 // points.
6804 let tx_type = if at.side >= 32 {
6805 TxType::DctDct
6806 } else {
6807 crate::decode::default_intra_tx_type(mode)
6808 };
6809 let u = chroma[0].trial_typed(
6810 at,
6811 mode,
6812 0,
6813 search.base_q_idx,
6814 search.deadzone,
6815 tx_type,
6816 fctx,
6817 );
6818 let v = chroma[1].trial_typed(
6819 at,
6820 mode,
6821 0,
6822 search.base_q_idx,
6823 search.deadzone,
6824 tx_type,
6825 fctx,
6826 );
6827 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
6828 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
6829 best = Some((cost, mode, u, v));
6830 }
6831 }
6832 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
6833 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
6834 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
6835 // what keeps `u_colors` ascending and distinct the way
6836 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
6837 // each cluster's own mean, since the colour-index map is SHARED by the
6838 // two planes. Priced against the best ordinary chroma mode above, so a
6839 // block only takes one when it beats it; a palette block's chroma mode is
6840 // `UV_DC_PRED` by construction.
6841 let mut palette_uv = None;
6842 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6843 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
6844 let plane_source = |p: &Plane| -> Vec<u8> {
6845 (at.y..at.y + at.side)
6846 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
6847 .collect()
6848 };
6849 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
6850 // The luma on-screen extent carried into this plane exactly as the
6851 // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
6852 let on_uv = crate::decode::palette_onscreen_uv(
6853 (side, side),
6854 (
6855 side.min(luma.true_width.saturating_sub(x)),
6856 side.min(luma.true_height.saturating_sub(y)),
6857 ),
6858 (at.side, at.side),
6859 // The encoder writes 4:2:0 only (`palette_uv_side` above).
6860 (1, 1),
6861 );
6862 for mut pal in palette_candidates(&u_source) {
6863 let n = usize::from(pal.size);
6864 crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
6865 // V's base colour per cluster: the mean of the samples the shared
6866 // map assigns to it (an empty cluster cannot happen -- every
6867 // colour `palette_candidates` returns is some pixel's nearest).
6868 let mut sums = [0u32; 8];
6869 let mut counts = [0u32; 8];
6870 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
6871 let k = usize::from(i).min(n - 1);
6872 sums[k] += u32::from(sample);
6873 counts[k] += 1;
6874 }
6875 let mut v_colors = [0u16; 8];
6876 for k in 0..n {
6877 v_colors[k] = if counts[k] > 0 {
6878 ((sums[k] + counts[k] / 2) / counts[k]) as u16
6879 } else {
6880 0
6881 };
6882 }
6883 let candidate = crate::tile::PaletteUv {
6884 size: pal.size,
6885 u_colors: pal.colors,
6886 v_colors,
6887 map: pal.map,
6888 };
6889 let predict = |colors: &[u16; 8]| -> Vec<u8> {
6890 candidate
6891 .map
6892 .iter()
6893 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
6894 .collect()
6895 };
6896 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
6897 let u_trial = chroma[0].code_from_prediction(
6898 at.x,
6899 at.y,
6900 at.side,
6901 &pu,
6902 false,
6903 search.base_q_idx,
6904 search.deadzone,
6905 set,
6906 );
6907 let v_trial = chroma[1].code_from_prediction(
6908 at.x,
6909 at.y,
6910 at.side,
6911 &pv,
6912 false,
6913 search.base_q_idx,
6914 search.deadzone,
6915 set,
6916 );
6917 let cost_p = u_trial.sse
6918 + v_trial.sse
6919 + search.lambda
6920 * (u_trial.bits
6921 + v_trial.bits
6922 + crate::tile::palette_uv_bits(&candidate, side, on_uv));
6923 if cost_p < cost {
6924 cost = cost_p;
6925 mode = DC_PRED;
6926 u = u_trial;
6927 v = v_trial;
6928 palette_uv = Some(candidate);
6929 }
6930 }
6931 }
6932 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
6933 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
6934 // nudges every sample by `alpha_q3` times the block's subsampled,
6935 // average-subtracted luma reconstruction. Offered only where
6936 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
6937 // and priced against the best ordinary chroma mode above, palette
6938 // included, so a block only takes it when it beats both.
6939 let mut cfl_alphas = None;
6940 if side <= 32 && cfl_on() {
6941 // The AC signal, through the decoder's own
6942 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
6943 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
6944 i32::from(luma.reconstruction[ly * luma.width + lx])
6945 });
6946 let dc_prediction = |plane: &Plane| -> Vec<u8> {
6947 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
6948 let (above, left, corner) =
6949 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
6950 let mut prediction = vec![0u8; at.side * at.side];
6951 intra_predict_u8(
6952 DC_PRED,
6953 0,
6954 above,
6955 left,
6956 corner,
6957 at.side,
6958 at.side,
6959 false,
6960 false,
6961 &mut prediction,
6962 fctx,
6963 );
6964 prediction
6965 };
6966 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
6967 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
6968 // add the residual -- which is what [`Plane::code_from_prediction`]
6969 // does with what this returns.
6970 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
6971 base.iter()
6972 .zip(ac.iter())
6973 .map(|(&b, &a)| {
6974 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
6975 })
6976 .collect()
6977 };
6978 // The least-squares alpha, then its two neighbours: minimising
6979 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
6980 // dot-product ratio, and the quantised optimum is one of the two
6981 // integers around it (the clamp and the Q6 rounding are what the SSE
6982 // check below re-decides). libaom sweeps all sixteen magnitudes under
6983 // full RD; three predictions per plane buy nearly the same alpha for a
6984 // thirtieth of the search.
6985 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
6986 let (mut num, mut den) = (0.0f64, 0.0f64);
6987 for row in 0..at.side {
6988 for col in 0..at.side {
6989 let i = row * at.side + col;
6990 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
6991 - f64::from(base[i]);
6992 num += d * f64::from(ac[i]);
6993 den += f64::from(ac[i]) * f64::from(ac[i]);
6994 }
6995 }
6996 if den == 0.0 {
6997 return 0;
6998 }
6999 let ideal = 64.0 * num / den;
7000 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
7001 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
7002 let alpha = alpha.clamp(-16, 16) as i32;
7003 if alpha == 0 {
7004 continue;
7005 }
7006 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
7007 if sse < best.0 {
7008 best = (sse, alpha);
7009 }
7010 }
7011 best.1
7012 };
7013 let picked = [
7014 pick_alpha(&chroma[0], &bases[0]),
7015 pick_alpha(&chroma[1], &bases[1]),
7016 ];
7017 if picked != [0, 0] {
7018 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
7019 let trial = |plane_idx: usize, alpha: i32| -> Trial {
7020 let prediction = if alpha == 0 {
7021 bases[plane_idx].clone()
7022 } else {
7023 apply(&bases[plane_idx], alpha)
7024 };
7025 chroma[plane_idx].code_from_prediction(
7026 at.x,
7027 at.y,
7028 at.side,
7029 &prediction,
7030 false,
7031 search.base_q_idx,
7032 search.deadzone,
7033 set,
7034 )
7035 };
7036 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
7037 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
7038 let combos: [(i32, i32); 3] = [(picked[0], picked[1]), (picked[0], 0), (0, picked[1])];
7039 for &(alpha_u, alpha_v) in &combos {
7040 if (alpha_u, alpha_v) == (0, 0) {
7041 continue;
7042 }
7043 let cu = trial(0, alpha_u);
7044 let cv = trial(1, alpha_v);
7045 let bits =
7046 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
7047 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
7048 if cost_cfl < cost {
7049 cost = cost_cfl;
7050 mode = crate::tile::UV_CFL_PRED as u8;
7051 u = cu;
7052 v = cv;
7053 palette_uv = None;
7054 cfl_alphas = Some((alpha_u, alpha_v));
7055 }
7056 }
7057 }
7058 }
7059 if let Some((alpha_u, alpha_v)) = cfl_alphas {
7060 for alpha in [alpha_u, alpha_v] {
7061 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
7062 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7063 }
7064 }
7065 if census_on() {
7066 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
7067 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7068 }
7069 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7070 chroma[0].commit(at.x, at.y, at.side, &u);
7071 chroma[1].commit(at.x, at.y, at.side, &v);
7072 (
7073 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
7074 mode,
7075 cost,
7076 palette_uv,
7077 cfl_alphas,
7078 )
7079}
7080
7081/// Codes one leaf of a straddling quadrant as whichever costs least of intra
7082/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
7083/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
7084/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
7085/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
7086/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
7087/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
7088/// attempted here: these leaves only ever fill the sliver of real content a
7089/// true edge lands in the middle of a larger block, not a leaf worth a full
7090/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
7091/// (see `write_inter_frame_leaf`'s doc comment).
7092#[allow(clippy::too_many_arguments)]
7093/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
7094/// as [`code_square_inter`] wants them: empty on a frame that codes no
7095/// `reference_select`, or when the leaf compound candidates are switched off.
7096/// One helper because THREE leaf call sites need it -- the split quadrants
7097/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
7098/// `&[]` and so coded no compound block anywhere along the frame's true edge.
7099#[allow(clippy::too_many_arguments)]
7100fn leaf_compound_stacks<'a>(
7101 grid: &MiGrid,
7102 mi_row: usize,
7103 mi_col: usize,
7104 bw4: usize,
7105 bh4: usize,
7106 mi_cols: usize,
7107 mi_rows: usize,
7108 reference_select: bool,
7109 golden: Option<&'a Picture>,
7110 altref: Option<&'a Picture>,
7111) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
7112 if !(reference_select && leaf_compound()) {
7113 return Vec::new();
7114 }
7115 [
7116 (crate::mvstack::GOLDEN_FRAME, golden),
7117 (crate::mvstack::ALTREF_FRAME, altref),
7118 ]
7119 .into_iter()
7120 .filter_map(|(r, pic)| {
7121 pic.map(|p| {
7122 (
7123 r,
7124 p,
7125 crate::mvstack::find_mv_stack_compound(
7126 grid,
7127 mi_row,
7128 mi_col,
7129 bw4,
7130 bh4,
7131 (crate::mvstack::LAST_FRAME, r),
7132 mi_cols,
7133 mi_rows,
7134 grid.sign_bias_table(),
7135 &[(0, 0); 7],
7136 None,
7137 ),
7138 )
7139 })
7140 })
7141 .collect()
7142}
7143
7144/// The OBMC prediction of one square single-reference block: this block's own
7145/// translation prediction (`mc::predict`) with every bordering above/left
7146/// neighbour blended into the overlap strips by the DECODER's own plan and
7147/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
7148/// the search prices is what a decoder reconstructs -- never a second
7149/// implementation of the blend. `None` when the block has no overlappable
7150/// neighbour at all (the writer would then code no `motion_mode` symbol) or
7151/// when the plan cannot be built (a neighbour naming a reference this encode
7152/// does not hold).
7153#[allow(clippy::too_many_arguments)]
7154fn obmc_prediction(
7155 grid: &MiGrid,
7156 (mi_row, mi_col): (usize, usize),
7157 (mi_rows, mi_cols): (usize, usize),
7158 (x, y): (usize, usize),
7159 side: usize,
7160 mv: (i32, i32),
7161 refs: &[Option<&Picture>; 8],
7162 // This block's OWN reference planes, luma then both chroma, each as
7163 // (samples, stride, true width, true height).
7164 ref_planes: [(&[u16], usize, usize, usize); 3],
7165 frame_width: usize,
7166 fctx: &crate::decode::FrameCtx,
7167) -> Option<[Vec<u8>; 3]> {
7168 let n4 = side / 4;
7169 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
7170 return None;
7171 }
7172 let refpix = crate::decode::RefPix::ready(*refs);
7173 let plan = crate::decode::obmc_plan(
7174 grid,
7175 &[],
7176 &[],
7177 mi_row,
7178 mi_col,
7179 n4,
7180 n4,
7181 mi_rows,
7182 mi_cols,
7183 side,
7184 side,
7185 side,
7186 crate::decode::ss_x(fctx),
7187 crate::decode::ss_y(fctx),
7188 side / 2,
7189 x,
7190 y,
7191 x / 2,
7192 y / 2,
7193 &refpix,
7194 Some(fctx.interp_filter.get()),
7195 frame_width,
7196 )
7197 .ok()?;
7198 let mut pred = [
7199 vec![0u16; side * side],
7200 vec![0u16; side * side / 4],
7201 vec![0u16; side * side / 4],
7202 ];
7203 for (i, r) in ref_planes.into_iter().enumerate() {
7204 let luma_plane = i == 0;
7205 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
7206 let s = if luma_plane { side } else { side / 2 };
7207 mc::predict(
7208 r.0,
7209 r.1,
7210 r.2,
7211 r.3,
7212 mv_to_q4(px, mv.1, luma_plane),
7213 mv_to_q4(py, mv.0, luma_plane),
7214 s,
7215 s,
7216 &mut pred[i],
7217 fctx,
7218 );
7219 }
7220 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
7221 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
7222 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
7223 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
7224}
7225
7226fn code_square_inter(
7227 luma: &mut Plane,
7228 chroma: &mut [Plane; 2],
7229 (x, y): (usize, usize),
7230 side: usize,
7231 search: &Search,
7232 mode_bits: &[f64; 13],
7233 reference: &Picture,
7234 stack: &MvStack,
7235 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
7236 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
7237 // `reference_select`, and at the straddling call sites).
7238 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
7239 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
7240 // (`record_mi`, in the writer's own coding order) and this leaf's place in
7241 // it -- what the OBMC candidate's eligibility walk and neighbour plan
7242 // read, the same state the tile writer reads when it codes the leaf's
7243 // `motion_mode` symbol.
7244 grid: &MiGrid,
7245 (mi_row, mi_col): (usize, usize),
7246 (mi_rows, mi_cols): (usize, usize),
7247 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
7248 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
7249 refs: &[Option<&Picture>; 8],
7250 fctx: &crate::decode::FrameCtx,
7251) -> (BlockCoeffs, f64) {
7252 // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra
7253 // candidate at all -- `intra_cost` stays at infinity, so every
7254 // comparison below takes an inter candidate and the fallback arm at the
7255 // tail is unreachable. The planes hold what the caller snapshotted until
7256 // the winner commits: the intra trial used to commit here and be
7257 // overwritten by the inter commit, so skipping it changes no committed
7258 // sample, only work.
7259 let (intra_block, intra_cost) = if search.arf_leaf_intra {
7260 code_square(
7261 luma,
7262 chroma,
7263 (x, y),
7264 side,
7265 search,
7266 mode_bits,
7267 tx_select() && tx_select_inter(),
7268 None,
7269 false,
7270 fctx,
7271 )
7272 } else {
7273 arfmode_hit(0);
7274 (BlockCoeffs::default(), f64::INFINITY)
7275 };
7276 let luma_set = if side == 8 {
7277 TxbSet::Luma8Inter
7278 } else {
7279 TxbSet::Luma16Inter
7280 };
7281 let chroma_set = if side == 8 {
7282 TxbSet::Chroma4
7283 } else {
7284 TxbSet::Chroma8
7285 };
7286
7287 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
7288 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
7289 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
7290 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
7291 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
7292 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
7293
7294 let mv = stack.nearest_mv;
7295 let ref_luma = (
7296 &reference.y,
7297 reference.width,
7298 luma.true_width,
7299 luma.true_height,
7300 );
7301 let ref_u = (
7302 &reference.u,
7303 reference.width / 2,
7304 chroma[0].true_width,
7305 chroma[0].true_height,
7306 );
7307 let ref_v = (
7308 &reference.v,
7309 reference.width / 2,
7310 chroma[1].true_width,
7311 chroma[1].true_height,
7312 );
7313 let luma_trial = mc_trial(
7314 luma,
7315 x,
7316 y,
7317 side,
7318 mv,
7319 true,
7320 ref_luma.0,
7321 ref_luma.1,
7322 ref_luma.2,
7323 ref_luma.3,
7324 false,
7325 search.base_q_idx,
7326 search.deadzone,
7327 luma_set,
7328 fctx,
7329 );
7330 let u = mc_trial(
7331 &chroma[0],
7332 x / 2,
7333 y / 2,
7334 side / 2,
7335 mv,
7336 false,
7337 ref_u.0,
7338 ref_u.1,
7339 ref_u.2,
7340 ref_u.3,
7341 false,
7342 search.base_q_idx,
7343 search.deadzone,
7344 chroma_set,
7345 fctx,
7346 );
7347 let v = mc_trial(
7348 &chroma[1],
7349 x / 2,
7350 y / 2,
7351 side / 2,
7352 mv,
7353 false,
7354 ref_v.0,
7355 ref_v.1,
7356 ref_v.2,
7357 ref_v.3,
7358 false,
7359 search.base_q_idx,
7360 search.deadzone,
7361 chroma_set,
7362 fctx,
7363 );
7364 let skip = luma_trial.levels.iter().all(|&l| l == 0)
7365 && u.levels.iter().all(|&l| l == 0)
7366 && v.levels.iter().all(|&l| l == 0);
7367 let inter_cost = luma_trial.sse
7368 + u.sse
7369 + v.sse
7370 + search.lambda
7371 * (skip_bits(skip)
7372 + intra_inter_bits(true)
7373 + single_ref_bits
7374 + mode_bits_inter
7375 + if skip {
7376 0.0
7377 } else {
7378 luma_trial.bits + u.bits + v.bits
7379 });
7380
7381 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
7382 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
7383 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
7384 // scan's own coverage already reached as far) but a real gap at 4-mi
7385 // leaf geometry. r3 ported the extended scan and, while proving it a
7386 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
7387 // `mvstack.rs`), found and fixed a second bug the extended scan's
7388 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
7389 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
7390 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
7391 // regardless of whether it also casts a ref-frame-matching vote) --
7392 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
7393 // branches), which is what made 8-mi geometry a true no-op instead of
7394 // one that only held when every neighbour happened to be inter.
7395 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
7396 // only ever took the stack's NEARESTMV candidate or went intra, so a
7397 // 32x32 block splitting because its four quarters MOVE differently could
7398 // not code the movement it split for. Same candidate `search_inter_block`
7399 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
7400 // a vector the residual syntax can name -- at this leaf's own side.
7401 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
7402 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
7403 // re-price below can hand it back as the winner's own mode info.
7404 let nearest_info = InterInfo {
7405 ref1: None,
7406 mv1: (0, 0),
7407 ref_frame: crate::mvstack::LAST_FRAME,
7408 mode: InterMode::NearestMv,
7409 mv,
7410 ref_mv_idx: 0,
7411 };
7412 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
7413 // syntax, apart from its residual: the OBMC candidate re-prices the same
7414 // syntax against a different prediction, so both sides of that comparison
7415 // carry it.
7416 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
7417 // This leaf's own `NEWMV` vector, kept whether or not it won the
7418 // single-reference comparison: it seeds the compound half-new candidate
7419 // below, exactly as `search_inter_block` seeds its own from the searches
7420 // it already ran.
7421 let mut searched_new: Option<(i32, i32)> = None;
7422 // What that search cost, kept for the second reference's own early-out
7423 // below (`None` when this leaf ran no search at all).
7424 let mut searched_new_cost: Option<f64> = None;
7425 let source_block = luma.source_block(x, y, side);
7426 if leaf_new_mv() {
7427 let (seeds, seed_n) = mv_seeds(stack);
7428 let found = motion::search(
7429 ref_luma.0,
7430 ref_luma.1,
7431 ref_luma.2,
7432 ref_luma.3,
7433 &source_block,
7434 x,
7435 y,
7436 side,
7437 side,
7438 stack.pred_mv,
7439 &seeds[..seed_n],
7440 search.lambda,
7441 fctx,
7442 1,
7443 );
7444 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
7445 searched_new_cost = Some(found.cost);
7446 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
7447 if mv_residual.is_none() {
7448 // lane-newmv: a vector the writer cannot name never reaches RD.
7449 newmv_census_block(
7450 side,
7451 false,
7452 f64::INFINITY,
7453 best.0,
7454 new_mv,
7455 stack.nearest_mv,
7456 0.0,
7457 );
7458 }
7459 if let Some(mv_bits) = mv_residual {
7460 searched_new = Some(new_mv);
7461 // Same reuse as `search_inter_block`: a NEWMV equal to the
7462 // stack's NEARESTMV is the same three trials, already run above.
7463 let (luma_new, u_new, v_new) = if new_mv == mv {
7464 (luma_trial.clone(), u.clone(), v.clone())
7465 } else {
7466 (
7467 mc_trial(
7468 luma,
7469 x,
7470 y,
7471 side,
7472 new_mv,
7473 true,
7474 ref_luma.0,
7475 ref_luma.1,
7476 ref_luma.2,
7477 ref_luma.3,
7478 false,
7479 search.base_q_idx,
7480 search.deadzone,
7481 luma_set,
7482 fctx,
7483 ),
7484 mc_trial(
7485 &chroma[0],
7486 x / 2,
7487 y / 2,
7488 side / 2,
7489 new_mv,
7490 false,
7491 ref_u.0,
7492 ref_u.1,
7493 ref_u.2,
7494 ref_u.3,
7495 false,
7496 search.base_q_idx,
7497 search.deadzone,
7498 chroma_set,
7499 fctx,
7500 ),
7501 mc_trial(
7502 &chroma[1],
7503 x / 2,
7504 y / 2,
7505 side / 2,
7506 new_mv,
7507 false,
7508 ref_v.0,
7509 ref_v.1,
7510 ref_v.2,
7511 ref_v.3,
7512 false,
7513 search.base_q_idx,
7514 search.deadzone,
7515 chroma_set,
7516 fctx,
7517 ),
7518 )
7519 };
7520 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
7521 && u_new.levels.iter().all(|&l| l == 0)
7522 && v_new.levels.iter().all(|&l| l == 0);
7523 let drl_bits = if stack.entries.len() > 1 {
7524 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
7525 } else {
7526 0.0
7527 };
7528 let cost_new = luma_new.sse
7529 + u_new.sse
7530 + v_new.sse
7531 + search.lambda
7532 * (skip_bits(skip_new)
7533 + intra_inter_bits(true)
7534 + single_ref_bits
7535 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7536 + drl_bits
7537 + mv_bits
7538 + mv_rate_surcharge(mv_bits)
7539 + if skip_new {
7540 0.0
7541 } else {
7542 luma_new.bits + u_new.bits + v_new.bits
7543 });
7544 newmv_census_block(
7545 side,
7546 true,
7547 cost_new,
7548 best.0,
7549 new_mv,
7550 stack.nearest_mv,
7551 mv_bits,
7552 );
7553 if cost_new < best.0 {
7554 single_syntax = intra_inter_bits(true)
7555 + single_ref_bits
7556 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7557 + drl_bits
7558 + mv_bits;
7559 best = (
7560 cost_new,
7561 Some((
7562 luma_new,
7563 u_new,
7564 v_new,
7565 skip_new,
7566 InterInfo {
7567 ref1: None,
7568 mv1: (0, 0),
7569 ref_frame: crate::mvstack::LAST_FRAME,
7570 mode: InterMode::NewMv,
7571 mv: new_mv,
7572 ref_mv_idx: 0,
7573 },
7574 )),
7575 );
7576 }
7577 }
7578 }
7579
7580 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
7581 // `search_inter_block` prices for a whole 32x32 block:
7582 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
7583 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
7584 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
7585 // too. Priced with the same static-CDF approximation, plus the
7586 // compound-only syntax the writer emits.
7587 if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() {
7588 // lane-arfmode: arm 4 drops this leaf's compound set (counted once
7589 // per leaf, not once per pair); the single-reference candidates
7590 // above stay.
7591 arfmode_hit(2);
7592 }
7593 for (ref1, g, cstack) in compound
7594 .iter()
7595 .filter(|_| leaf_compound() && search.arf_leaf_compound)
7596 {
7597 let (ref1, g) = (*ref1, *g);
7598 // The whole `comp_mode` + reference-pair tree at the writer's own
7599 // contexts, for THIS pair (lane-ctx).
7600 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
7601 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7602 let mode_bits_of =
7603 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7604 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7605 (
7606 cstack.nearest_mv,
7607 mode_bits_of(0),
7608 InterInfo {
7609 ref_frame: crate::mvstack::LAST_FRAME,
7610 mode: InterMode::NearestNearestMv,
7611 mv: cstack.nearest_mv.0,
7612 mv1: cstack.nearest_mv.1,
7613 ref1: Some(ref1),
7614 ref_mv_idx: 0,
7615 },
7616 ),
7617 (
7618 ((0, 0), (0, 0)),
7619 mode_bits_of(6),
7620 InterInfo {
7621 ref_frame: crate::mvstack::LAST_FRAME,
7622 mode: InterMode::GlobalGlobalMv,
7623 mv: (0, 0),
7624 mv1: (0, 0),
7625 ref1: Some(ref1),
7626 ref_mv_idx: 0,
7627 },
7628 ),
7629 ];
7630 // Every compound MV residual here is priced against compound stack
7631 // entry 0, which is what `assign_compound_mv` predicts from at
7632 // `ref_mv_idx = 0` -- so it is also what the second-reference search
7633 // below seeds from and rounds to, and no candidate it finds can then
7634 // fail `mv_residual_bits`.
7635 let cbase = cstack
7636 .entries
7637 .first()
7638 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
7639 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
7640 // it a leaf could only name a stack vector for the second half, and
7641 // screen capture showed the consequence: every leaf compound block
7642 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
7643 // extra-reference `NEWMV`, when this reference's own
7644 // `NEAREST_NEARESTMV` vector already prices `margin` times better
7645 // than the `LAST` search of this same leaf did -- one candidate
7646 // evaluation standing in for a whole search.
7647 let margin = leaf_second_new_margin();
7648 let mut second_new: Option<(i32, i32)> = None;
7649 if leaf_second_new_mv() {
7650 newmv_census_global(2);
7651 let skip = margin > 0.0
7652 && searched_new_cost.is_some_and(|last| {
7653 motion::cost_at(
7654 &g.y,
7655 g.width,
7656 luma.true_width,
7657 luma.true_height,
7658 &source_block,
7659 x,
7660 y,
7661 side,
7662 side,
7663 cstack.nearest_mv.1,
7664 cbase.1,
7665 search.lambda,
7666 fctx,
7667 ) * margin
7668 <= last
7669 });
7670 if skip {
7671 newmv_census_global(3);
7672 }
7673 if !skip {
7674 let mut seeds = [(0, 0); 4];
7675 let mut seed_n = 1;
7676 for e in cstack.entries.iter().take(3) {
7677 seeds[seed_n] = e.mv1;
7678 seed_n += 1;
7679 }
7680 let found = motion::search(
7681 &g.y,
7682 g.width,
7683 luma.true_width,
7684 luma.true_height,
7685 &source_block,
7686 x,
7687 y,
7688 side,
7689 side,
7690 cbase.1,
7691 &seeds[..seed_n],
7692 search.lambda,
7693 fctx,
7694 ref_distance(ref1),
7695 );
7696 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
7697 }
7698 }
7699 if let Some(new_mv) = searched_new {
7700 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
7701 ccands.push((
7702 (new_mv, cstack.nearest_mv.1),
7703 mode_bits_of(3) + b0,
7704 InterInfo {
7705 ref_frame: crate::mvstack::LAST_FRAME,
7706 mode: InterMode::NewNearestMv,
7707 mv: new_mv,
7708 mv1: cstack.nearest_mv.1,
7709 ref1: Some(ref1),
7710 ref_mv_idx: 0,
7711 },
7712 ));
7713 }
7714 }
7715 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
7716 // searches this leaf ran, each residual priced against `cbase`.
7717 if let Some(mv1) = second_new {
7718 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
7719 ccands.push((
7720 (cstack.nearest_mv.0, mv1),
7721 mode_bits_of(2) + b1,
7722 InterInfo {
7723 ref_frame: crate::mvstack::LAST_FRAME,
7724 mode: InterMode::NearestNewMv,
7725 mv: cstack.nearest_mv.0,
7726 mv1,
7727 ref1: Some(ref1),
7728 ref_mv_idx: 0,
7729 },
7730 ));
7731 if let Some((new_mv, b0)) =
7732 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
7733 {
7734 ccands.push((
7735 (new_mv, mv1),
7736 mode_bits_of(7) + b0 + b1,
7737 InterInfo {
7738 ref_frame: crate::mvstack::LAST_FRAME,
7739 mode: InterMode::NewNewMv,
7740 mv: new_mv,
7741 mv1,
7742 ref1: Some(ref1),
7743 ref_mv_idx: 0,
7744 },
7745 ));
7746 }
7747 }
7748 }
7749 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
7750 ccands.dedup_by_key(|c| c.0);
7751 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
7752 let g_u = (
7753 g.u.as_slice(),
7754 g.width / 2,
7755 chroma[0].true_width,
7756 chroma[0].true_height,
7757 );
7758 let g_v = (
7759 g.v.as_slice(),
7760 g.width / 2,
7761 chroma[1].true_width,
7762 chroma[1].true_height,
7763 );
7764 for (mvs, bits, info) in ccands {
7765 let luma_c = mc_trial_compound(
7766 luma,
7767 x,
7768 y,
7769 side,
7770 mvs,
7771 true,
7772 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7773 g_luma,
7774 search.base_q_idx,
7775 search.deadzone,
7776 luma_set,
7777 fctx,
7778 );
7779 let u_c = mc_trial_compound(
7780 &chroma[0],
7781 x / 2,
7782 y / 2,
7783 side / 2,
7784 mvs,
7785 false,
7786 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7787 g_u,
7788 search.base_q_idx,
7789 search.deadzone,
7790 chroma_set,
7791 fctx,
7792 );
7793 let v_c = mc_trial_compound(
7794 &chroma[1],
7795 x / 2,
7796 y / 2,
7797 side / 2,
7798 mvs,
7799 false,
7800 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7801 g_v,
7802 search.base_q_idx,
7803 search.deadzone,
7804 chroma_set,
7805 fctx,
7806 );
7807 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
7808 && u_c.levels.iter().all(|&l| l == 0)
7809 && v_c.levels.iter().all(|&l| l == 0);
7810 let cost_c = luma_c.sse
7811 + u_c.sse
7812 + v_c.sse
7813 + search.lambda
7814 * (skip_bits(skip_c)
7815 + intra_inter_bits(true)
7816 + bits
7817 + if skip_c {
7818 0.0
7819 } else {
7820 luma_c.bits + u_c.bits + v_c.bits
7821 });
7822 if cost_c < best.0 {
7823 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
7824 }
7825 }
7826 }
7827
7828 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
7829 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
7830 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
7831 // the writer codes no symbol for one. The prediction is the decoder's own
7832 // plan and blend over the neighbours this leaf's `grid` already carries
7833 // (published by `record_mi` in the writer's coding order), so the
7834 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
7835 // offered this only at 32x32, which is not where libaom cashes its OBMC
7836 // gain.
7837 let mut motion_won = 0u8;
7838 let single = match &best.1 {
7839 None => Some(nearest_info),
7840 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
7841 Some(_) => None,
7842 };
7843 if let Some(info) = single.filter(|i| {
7844 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
7845 && i.ref_frame == crate::mvstack::LAST_FRAME
7846 }) {
7847 let planes = [
7848 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7849 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7850 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7851 ];
7852 // Which alphabet this block's writer will code the symbol against
7853 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
7854 // 3-symbol one only under `allow_warped_motion` and at least one warp
7855 // sample. Mirrored here so the candidates are priced against the
7856 // table the tile really narrows.
7857 let warp_alphabet = warp_on()
7858 && crate::decode::num_proj_ref(
7859 grid,
7860 mi_row,
7861 mi_col,
7862 side / 4,
7863 side / 4,
7864 mi_cols,
7865 mi_rows,
7866 info.ref_frame,
7867 fctx,
7868 ) >= 1;
7869 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
7870 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
7871 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
7872 if let Some(pred) = obmc_prediction(
7873 grid,
7874 (mi_row, mi_col),
7875 (mi_rows, mi_cols),
7876 (x, y),
7877 side,
7878 info.mv,
7879 refs,
7880 planes,
7881 reference.width,
7882 fctx,
7883 ) {
7884 candidates.push((1, pred));
7885 }
7886 }
7887 if warp_alphabet {
7888 if let Some(pred) = warp_prediction(
7889 grid,
7890 (mi_row, mi_col),
7891 (mi_rows, mi_cols),
7892 (x, y),
7893 side,
7894 info.mv,
7895 info.ref_frame,
7896 planes,
7897 fctx,
7898 ) {
7899 candidates.push((2, pred));
7900 }
7901 }
7902 for (motion, pred) in candidates {
7903 let luma_o = luma.code_from_prediction(
7904 x,
7905 y,
7906 side,
7907 &pred[0],
7908 false,
7909 search.base_q_idx,
7910 search.deadzone,
7911 luma_set,
7912 );
7913 let u_o = chroma[0].code_from_prediction(
7914 x / 2,
7915 y / 2,
7916 side / 2,
7917 &pred[1],
7918 false,
7919 search.base_q_idx,
7920 search.deadzone,
7921 chroma_set,
7922 );
7923 let v_o = chroma[1].code_from_prediction(
7924 x / 2,
7925 y / 2,
7926 side / 2,
7927 &pred[2],
7928 false,
7929 search.base_q_idx,
7930 search.deadzone,
7931 chroma_set,
7932 );
7933 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
7934 && u_o.levels.iter().all(|&l| l == 0)
7935 && v_o.levels.iter().all(|&l| l == 0);
7936 let cost_o = luma_o.sse
7937 + u_o.sse
7938 + v_o.sse
7939 + search.lambda
7940 * (skip_bits(skip_o)
7941 + single_syntax
7942 + mm(motion)
7943 + if skip_o {
7944 0.0
7945 } else {
7946 luma_o.bits + u_o.bits + v_o.bits
7947 });
7948 // The incumbent pays the motion_mode symbol IT would code, so
7949 // both sides of the comparison carry that syntax.
7950 if cost_o < best.0 + search.lambda * mm(motion_won) {
7951 motion_won = motion;
7952 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
7953 }
7954 }
7955 }
7956
7957 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
7958 if cost < intra_cost {
7959 // A compound winner commits the flat trial it was priced from:
7960 // `commit_inter_luma`'s var-tx trial set is single-reference
7961 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
7962 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
7963 // predicting each half-side trial from BOTH references, verified
7964 // byte-identical to this when its split is disabled) and MEASURED
7965 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
7966 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
7967 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
7968 // compound block's residual is small enough that the four extra
7969 // per-unit txb_skip/eob symbols cost more ladder bytes than this
7970 // encoder's static-CDF estimate prices them at, so the local RD
7971 // win does not convert. lane-av1txbits REBUILT it on top of a
7972 // search that prices against the tables the frame is really
7973 // written with (`tile::arm_pricing_cdfs`, the estimate error on
7974 // these very blocks measured down from +31% to +3%) and measured
7975 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
7976 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
7977 // same build without it. The static-CDF estimate was NOT what
7978 // held the compound var-tx trial back. The flat trial stays.
7979 // An OBMC winner commits the flat trial too: `commit_inter_luma`
7980 // re-predicts each var-tx unit by plain translation, which is not
7981 // the prediction this candidate was priced from.
7982 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
7983 // 0.05 (both rejections above were measured at 0.1, the weight
7984 // the lambda lane showed was 2x too heavy): a compound winner is
7985 // offered the same var-tx split, its units predicted from BOTH
7986 // references (`mc_trial_compound`). RE-MEASURED native: film
7987 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
7988 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
7989 // one row 0.2 down, two flat, short of the two-down-one-flat keep
7990 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
7991 // rather than change the default on a single 0.2 row. It fires:
7992 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
7993 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
7994 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
7995 // 1.3/1.2 down there, which is where the upgrade path is if this
7996 // is picked up again.
7997 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7998 refs[r as usize].map(|g| {
7999 (
8000 info.mv1,
8001 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
8002 )
8003 })
8004 });
8005 let (levels, tx_depth, dcost, luma_tx_types) =
8006 if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {
8007 luma.commit(x, y, side, &luma_new);
8008 (luma_new.levels.clone(), 0, 0.0, Vec::new())
8009 } else {
8010 commit_inter_luma(
8011 luma,
8012 (x, y),
8013 side,
8014 info.mv,
8015 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8016 search,
8017 &luma_new,
8018 skip_new,
8019 second,
8020 fctx,
8021 )
8022 };
8023 // lane-txrd: chroma follows the luma type the search just chose.
8024 let [u_new, v_new] = match luma_tx_types.first().copied() {
8025 Some(t) => recode_inter_chroma(
8026 chroma,
8027 (x, y),
8028 side,
8029 info.mv,
8030 [
8031 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
8032 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
8033 ],
8034 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
8035 refs[r as usize].map(|g| {
8036 (
8037 info.mv1,
8038 [
8039 (
8040 g.u.as_slice(),
8041 g.width / 2,
8042 chroma[0].true_width,
8043 chroma[0].true_height,
8044 ),
8045 (
8046 g.v.as_slice(),
8047 g.width / 2,
8048 chroma[1].true_width,
8049 chroma[1].true_height,
8050 ),
8051 ],
8052 )
8053 })
8054 }),
8055 search,
8056 chroma_set,
8057 t,
8058 fctx,
8059 )
8060 .unwrap_or([u_new, v_new]),
8061 None => [u_new, v_new],
8062 };
8063 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
8064 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
8065 return (
8066 BlockCoeffs {
8067 angle_delta_y: 0,
8068 cfl_alphas: None,
8069 filter_intra: None,
8070 luma: coeffs(&levels, side),
8071 u: coeffs(&u_new.levels, side / 2),
8072 v: coeffs(&v_new.levels, side / 2),
8073 mode: DC_PRED as u8,
8074 uv_mode: DC_PRED,
8075 skip: skip_new,
8076 eight: None,
8077 dv: None,
8078 palette: None,
8079 palette_uv: None,
8080 tx_depth,
8081 luma_tx_types,
8082 inter: Some(info),
8083 motion_mode: motion_won,
8084 },
8085 cost + dcost,
8086 );
8087 }
8088 }
8089
8090 census_add(8, 1);
8091 if skip {
8092 census_add(10, 1);
8093 }
8094 if inter_cost >= intra_cost {
8095 census_add(9, 1);
8096 }
8097 if inter_cost < intra_cost {
8098 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
8099 luma,
8100 (x, y),
8101 side,
8102 mv,
8103 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8104 search,
8105 &luma_trial,
8106 skip,
8107 None,
8108 fctx,
8109 );
8110 // lane-txrd: chroma follows the luma type (this tail's block is
8111 // single-reference `NEARESTMV`, so no compound second half).
8112 let [u, v] = match luma_tx_types.first().copied() {
8113 Some(t) => recode_inter_chroma(
8114 chroma,
8115 (x, y),
8116 side,
8117 mv,
8118 [
8119 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
8120 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
8121 ],
8122 None,
8123 search,
8124 chroma_set,
8125 t,
8126 fctx,
8127 )
8128 .unwrap_or([u, v]),
8129 None => [u, v],
8130 };
8131 chroma[0].commit(x / 2, y / 2, side / 2, &u);
8132 chroma[1].commit(x / 2, y / 2, side / 2, &v);
8133 (
8134 BlockCoeffs {
8135 luma_tx_types,
8136 angle_delta_y: 0,
8137 cfl_alphas: None,
8138 filter_intra: None,
8139 luma: coeffs(&levels, side),
8140 u: coeffs(&u.levels, side / 2),
8141 v: coeffs(&v.levels, side / 2),
8142 mode: DC_PRED as u8,
8143 uv_mode: DC_PRED,
8144 skip,
8145 eight: None,
8146 dv: None,
8147 palette: None,
8148 palette_uv: None,
8149 tx_depth,
8150 motion_mode: 0,
8151 inter: Some(InterInfo {
8152 ref1: None,
8153 mv1: (0, 0),
8154 ref_frame: crate::mvstack::LAST_FRAME,
8155 mode: InterMode::NearestMv,
8156 mv,
8157 ref_mv_idx: 0,
8158 }),
8159 },
8160 inter_cost + dcost,
8161 )
8162 } else {
8163 (intra_block, intra_cost)
8164 }
8165}
8166
8167/// Publishes one coded inter-frame block into the `mi` grid the next block's
8168/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
8169/// block casts no vote but is still a coded cell (see `code_square_inter`'s
8170/// note on `processed_rows`/`processed_cols`).
8171fn record_mi(
8172 grid: &mut MiGrid,
8173 mi_row: usize,
8174 mi_col: usize,
8175 size: u8,
8176 inter: Option<InterInfo>,
8177 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
8178 // the RD pricer the two cells the writer's `skip_ctx` sums.
8179 skip: bool,
8180) {
8181 let info = match inter {
8182 Some(info) => MiInfo {
8183 is_inter: true,
8184 ref_frame: info.ref_frame,
8185 // A COMPOUND block votes with BOTH of its references and both of
8186 // its vectors, exactly as the tile writer publishes it: recording
8187 // a compound block as a single-reference one here left the
8188 // encoder's own grid disagreeing with the writer's from the first
8189 // compound block on, so every later stack it searched against was
8190 // not the stack the decoder derives.
8191 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8192 mv1: mv16(info.mv1),
8193 mv: mv16(info.mv),
8194 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
8195 // side, compound modes 2/3/7 on the other.
8196 is_new_mv: matches!(
8197 info.mode,
8198 InterMode::NewMv
8199 | InterMode::NewNewMv
8200 | InterMode::NearestNewMv
8201 | InterMode::NewNearestMv
8202 ),
8203 size,
8204 size_h: size,
8205 is_global_mv0: false,
8206 is_global_mv1: false,
8207 },
8208 None => MiInfo {
8209 is_inter: false,
8210 ref_frame: -1,
8211 ref_frame1: NO_REF1,
8212 mv1: (0, 0),
8213 mv: (0, 0),
8214 is_new_mv: false,
8215 size,
8216 size_h: size,
8217 is_global_mv0: false,
8218 is_global_mv1: false,
8219 },
8220 };
8221 for dr in 0..usize::from(size) {
8222 for dc in 0..usize::from(size) {
8223 grid.set(mi_row + dr, mi_col + dc, info);
8224 grid.set_skip(mi_row + dr, mi_col + dc, skip);
8225 }
8226 }
8227}
8228
8229/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
8230/// writer's own `write_inter_block_128_rect` makes, so the second half of a
8231/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
8232fn record_mi_rect(
8233 grid: &mut MiGrid,
8234 mi_row: usize,
8235 mi_col: usize,
8236 (w_mi, h_mi): (usize, usize),
8237 inter: Option<InterInfo>,
8238 skip: bool,
8239) {
8240 record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
8241 // `record_mi` stamped the square corner; widen it to the true footprint,
8242 // with the block's own (rect) size fields.
8243 let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
8244 info.size = w_mi as u8;
8245 info.size_h = h_mi as u8;
8246 for dr in 0..h_mi {
8247 for dc in 0..w_mi {
8248 grid.set(mi_row + dr, mi_col + dc, info);
8249 grid.set_skip(mi_row + dr, mi_col + dc, skip);
8250 }
8251 }
8252}
8253
8254/// The reconstructed samples one 32x32 square covers in all three planes, so
8255/// that a partition trial can be undone.
8256/// One square of a plane, row-major, the inverse of [`Plane::restore`].
8257///
8258/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
8259/// which allocated and freed a `Vec` per row of every block it copied --
8260/// `Plane::snapshot` runs once per partition trial.
8261fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
8262 let mut out = vec![0u8; side * side];
8263 for row in 0..side {
8264 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
8265 }
8266 out
8267}
8268
8269fn snapshot(
8270 luma: &Plane,
8271 chroma: &[Plane; 2],
8272 (x, y): (usize, usize),
8273 side: usize,
8274) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
8275 [
8276 luma.snapshot(x, y, side),
8277 chroma[0].snapshot(x / 2, y / 2, side / 2),
8278 chroma[1].snapshot(x / 2, y / 2, side / 2),
8279 ]
8280}
8281
8282/// Puts such a snapshot back.
8283fn restore(
8284 luma: &mut Plane,
8285 chroma: &mut [Plane; 2],
8286 (x, y): (usize, usize),
8287 side: usize,
8288 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
8289) {
8290 luma.restore(x, y, side, &saved[0]);
8291 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
8292 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
8293}
8294
8295/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
8296/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
8297/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
8298/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
8299/// rule shared with the key-frame path, not a second one that could diverge.
8300fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
8301 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
8302 let dc_entry = dc_pos.map(|i| scored.remove(i));
8303 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
8304 scored.truncate(if dc_entry.is_some() {
8305 top_k.saturating_sub(1)
8306 } else {
8307 top_k
8308 });
8309 if let Some(dc_entry) = dc_entry {
8310 scored.push(dc_entry);
8311 }
8312 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
8313 modes.iter().copied().filter(|m| keep.contains(m)).collect()
8314}
8315
8316fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
8317 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
8318 [INTRA_MODE_CTX[usize::from(left_mode)]];
8319 std::array::from_fn(|mode| {
8320 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
8321 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
8322 } else {
8323 0.0
8324 };
8325 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
8326 })
8327}
8328
8329/// What the luma mode search picks between, and under what terms.
8330#[derive(Clone, Copy)]
8331struct Search<'a> {
8332 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
8333 /// luma search then offers a palette candidate beside the intra modes.
8334 screen: bool,
8335 base_q_idx: u8,
8336 deadzone: f64,
8337 lambda: f64,
8338 modes: &'a [u8],
8339 /// How many of `modes` the full RD trial (forward transform, quantize,
8340 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
8341 /// pre-pass on the prediction residual alone plus DC (always kept, since
8342 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
8343 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
8344 /// mode through full RD, unchanged from before this lever.
8345 top_k: Option<usize>,
8346 /// lane-arfmode: the top ARF's offer set ([`crate::speed::ARFMODE`])
8347 /// -- `false` cuts the named candidate group from the whole-32 search
8348 /// ([`search_inter_block`]), the 16x16/8x8 leaf search
8349 /// ([`code_square_inter`]) and the 8x8 split offer, at the top ARF
8350 /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is
8351 /// the pre-lane behaviour: the mid and quarter hidden frames, the shown
8352 /// leaves and the flat path keep intra and compound, and the
8353 /// straddling-edge 8x8s are only mode-gated, never partition-gated.
8354 /// The probe's correction: with the leaf gate ALONE the film A stream
8355 /// was byte-identical to the control -- the ARF's intra area lives at
8356 /// the whole-32 level, so the intra arm must cut it there too.
8357 arf_leaf_intra: bool,
8358 arf_leaf8: bool,
8359 arf_leaf_compound: bool,
8360}
8361
8362/// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what
8363/// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the
8364/// shipped table -- 0, bit-exact with the pre-lane encoder).
8365fn arfmode() -> u8 {
8366 match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
8367 u8::MAX => {}
8368 n => return n,
8369 }
8370 static ENV: std::sync::LazyLock<Option<u8>> = std::sync::LazyLock::new(|| {
8371 crate::envflags::var("EC_AV1_ARFMODE")
8372 .ok()
8373 .and_then(|v| v.parse().ok())
8374 });
8375 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE))
8376}
8377
8378/// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.
8379static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
8380
8381/// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
8382/// process constant ([`crate::envflags`]), so an in-process witness needs
8383/// this to arm the lever.
8384#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
8385pub(crate) fn set_arfmode(n: Option<u8>) {
8386 ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed);
8387}
8388
8389/// How often each armed [`crate::speed::ARFMODE`] arm actually fired since
8390/// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded
8391/// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8
8392/// split the search would have offered and the arm refused, 2 = a top-ARF
8393/// leaf whose compound set was dropped. A green gate over counts of zero
8394/// proves nothing about the lever.
8395static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [
8396 std::sync::atomic::AtomicUsize::new(0),
8397 std::sync::atomic::AtomicUsize::new(0),
8398 std::sync::atomic::AtomicUsize::new(0),
8399];
8400
8401/// Records one such hit.
8402fn arfmode_hit(which: usize) {
8403 ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8404}
8405
8406/// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer
8407/// condition, so the counter only runs when every other prune let the split
8408/// through and the arm alone refuses it.
8409fn arfmode_hit_and_no() -> bool {
8410 arfmode_hit(1);
8411 false
8412}
8413
8414/// Takes (and clears) the counts. `pub` for `examples/enc_probe`, so a
8415/// probe point can print a non-zero engagement count under the env knob
8416/// itself -- the counter the gate BD numbers are read against.
8417pub fn take_arfmode_hits() -> [usize; 3] {
8418 [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
8419}
8420
8421fn prune_top_k() -> Option<usize> {
8422 #[cfg(test)]
8423 {
8424 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
8425 return k;
8426 }
8427 }
8428 let swept = std::env::var("EC_AV1_PRUNE_K")
8429 .ok()
8430 .and_then(|v| v.parse::<usize>().ok());
8431 match swept {
8432 Some(k) if cfg!(test) => Some(k),
8433 _ => crate::speed::at(&crate::speed::PRUNE_K),
8434 }
8435}
8436
8437// A per-thread override [`prune_top_k`] checks first, so one test can sweep
8438// `top_k` in-process without mutating the environment (forbidden here --
8439// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
8440#[cfg(test)]
8441thread_local! {
8442 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
8443 const { std::cell::Cell::new(None) };
8444}
8445
8446#[cfg(test)]
8447fn set_test_top_k_override(value: Option<usize>) {
8448 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
8449}
8450
8451/// The default: unpruned, thirteen full trials per block, same as before this
8452/// lever. Set from the sweep in the lane report if the quality gate clears it.
8453pub(crate) const PRUNE_TOP_K: Option<usize> = None;
8454
8455/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
8456/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
8457/// quality gates were measured separately and may land on different
8458/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
8459/// [`EC_AV1_PRUNE_K`] or the key-frame path.
8460fn prune_top_k_inter() -> Option<usize> {
8461 #[cfg(test)]
8462 {
8463 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
8464 return k;
8465 }
8466 }
8467 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
8468 .ok()
8469 .and_then(|v| v.parse::<usize>().ok());
8470 match swept {
8471 Some(k) if cfg!(test) => Some(k),
8472 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
8473 }
8474}
8475
8476// A per-thread override [`prune_top_k_inter`] checks first, same reason as
8477// [`TEST_TOP_K_OVERRIDE`].
8478#[cfg(test)]
8479thread_local! {
8480 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
8481 const { std::cell::Cell::new(None) };
8482}
8483
8484#[cfg(test)]
8485fn set_test_top_k_override_inter(value: Option<usize>) {
8486 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
8487}
8488
8489/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
8490/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
8491/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
8492/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
8493/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
8494/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
8495/// pruning them costs less quality here.
8496pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
8497
8498// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
8499// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
8500// inter frame's cost can be attributed to a bucket without changing what
8501// the search actually does. Index: 0 = whole-call time inside
8502// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
8503// [`crate::mc::predict`] (every call, from the motion search's own
8504// candidates and from a committed inter block's final prediction alike),
8505// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
8506#[cfg(test)]
8507thread_local! {
8508 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
8509 std::cell::Cell::new(0),
8510 std::cell::Cell::new(0),
8511 std::cell::Cell::new(0),
8512 std::cell::Cell::new(0),
8513 ];
8514}
8515
8516/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
8517/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
8518/// per transform trial and per `mc::predict` call whether or not anyone was
8519/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
8520/// The clock is now read only when [`crate::par::stage_times`] is on, which
8521/// is what prints the breakdown in the first place.
8522#[cfg(test)]
8523pub(crate) fn stage_start() -> Option<std::time::Instant> {
8524 crate::par::stage_times().then(std::time::Instant::now)
8525}
8526
8527#[cfg(test)]
8528pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
8529 if let Some(t) = t {
8530 stage_add(bucket, t.elapsed());
8531 }
8532}
8533
8534#[cfg(test)]
8535pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
8536 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
8537}
8538
8539#[cfg(test)]
8540fn stage_reset() {
8541 crate::par::set_stage_times(true);
8542 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
8543}
8544
8545#[cfg(test)]
8546fn stage_read() -> [std::time::Duration; 4] {
8547 crate::par::set_stage_times(false);
8548 STAGE_NS.with(|c| {
8549 c.each_ref()
8550 .map(|cell| std::time::Duration::from_nanos(cell.get()))
8551 })
8552}
8553
8554/// One mode's coding of one block, before it is committed.
8555#[derive(Clone)]
8556struct Trial {
8557 levels: Vec<i32>,
8558 reconstruction: Vec<u8>,
8559 sse: f64,
8560 bits: f64,
8561}
8562
8563/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
8564/// of a 64-point transform that is actually coded (everything outside it is
8565/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
8566fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
8567 let mut out = vec![0i32; to * to];
8568 for row in 0..to {
8569 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
8570 }
8571 out
8572}
8573
8574/// The non-zero levels of a block, as the tile writer takes them.
8575fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
8576 levels
8577 .iter()
8578 .enumerate()
8579 .filter(|&(_, &level)| level != 0)
8580 .map(|(i, &level)| Coeff {
8581 row: (i / side) as u8,
8582 col: (i % side) as u8,
8583 level,
8584 })
8585 .collect()
8586}
8587
8588thread_local! {
8589 /// The tile grid the next frame is coded with, as `(TileColsLog2,
8590 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
8591 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
8592 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
8593 /// one tile per frame, what every caller that never arms anything gets
8594 /// and what every stream this crate wrote before tiles existed carries.
8595 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
8596}
8597
8598/// Arms this thread's next frame encodes with a tile grid (log2 counts).
8599pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
8600 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
8601}
8602
8603fn armed_tiles() -> (u32, u32) {
8604 let armed = TILE_LOG2.with(std::cell::Cell::get);
8605 if armed != (0, 0) {
8606 return armed;
8607 }
8608 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
8609 // (which codes through `encode_sequence`, not the facade) can measure what
8610 // a tile grid costs without a knob of its own -- same shape as
8611 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
8612 match std::env::var("EC_AV1_TILES").ok() {
8613 Some(v) if cfg!(test) => {
8614 let mut f = v.split(':');
8615 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
8616 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
8617 (cols, rows)
8618 }
8619 _ => armed,
8620 }
8621}
8622
8623/// Codes a frame's `tiles` tiles, each entirely on its own (see
8624/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
8625/// the crate's own pool, and hands back their payloads in tile order plus
8626/// whatever `code` returned for tile `store` -- the CDF state
8627/// `context_update_tile_id` names. The result cannot depend on the thread
8628/// count: each job writes one tile from the frame's own starting tables into
8629/// its own slot.
8630fn write_tiles<F>(
8631 tiles: usize,
8632 store: usize,
8633 code: F,
8634) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
8635where
8636 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
8637{
8638 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
8639 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
8640 let threads = crate::par::tile_threads().min(tiles);
8641 let mut slots: Vec<Slot> = Vec::new();
8642 if threads <= 1 {
8643 for index in 0..tiles {
8644 slots.push(Some(code(index)));
8645 }
8646 } else {
8647 let done: std::sync::Mutex<Vec<Slot>> =
8648 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8649 {
8650 let batch = crate::par::Batch::new("ec-av1-tile");
8651 for (from, to) in crate::par::bands(tiles, threads) {
8652 let done = &done;
8653 let code = &code;
8654 batch.submit(move || {
8655 for index in from..to {
8656 let coded = code(index);
8657 done.lock().expect("tile slots")[index] = Some(coded);
8658 }
8659 });
8660 }
8661 }
8662 slots = done.into_inner().expect("tile slots");
8663 }
8664 let mut out = Vec::with_capacity(tiles);
8665 let mut stored = None;
8666 for (index, slot) in slots.into_iter().enumerate() {
8667 let (bytes, cdfs) = slot.expect("every tile was coded")?;
8668 if index == store {
8669 stored = cdfs;
8670 }
8671 out.push(bytes);
8672 }
8673 Ok((out, stored))
8674}
8675
8676/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
8677/// workers, and returns the results in tile order. The counterpart of
8678/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
8679/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
8680/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
8681/// availability is already tile-relative (`clip_planes_to_tile`,
8682/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
8683/// other tiles have run -- gated by
8684/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
8685/// covers the search as well as the write.
8686///
8687/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
8688/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
8689/// does it for the decoder's filter bands.
8690fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
8691where
8692 T: Send,
8693 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
8694{
8695 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
8696 let threads = crate::par::tile_threads().min(tiles);
8697 if threads <= 1 {
8698 return (0..tiles).map(|index| job(index, fctx)).collect();
8699 }
8700 type Slot<T> = Option<Result<T>>;
8701 let done: std::sync::Mutex<Vec<Slot<T>>> =
8702 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8703 {
8704 let batch = crate::par::Batch::new("ec-av1-tile-search");
8705 for (from, to) in crate::par::bands(tiles, threads) {
8706 let done = &done;
8707 let job = &job;
8708 let ctx = crate::decode::filter_ctx_copy(fctx);
8709 batch.submit(move || {
8710 for index in from..to {
8711 let searched = job(index, &ctx);
8712 done.lock().expect("tile slots")[index] = Some(searched);
8713 }
8714 });
8715 }
8716 }
8717 done.into_inner()
8718 .expect("tile slots")
8719 .into_iter()
8720 .map(|slot| slot.expect("every tile was searched"))
8721 .collect()
8722}
8723
8724/// One tile job's own copy of a plane: the frame's source, a blank
8725/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
8726/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
8727/// of the frame's reconstruction because a tile's prediction never reads a
8728/// sample outside its own rectangle, and every sample inside it is written
8729/// before it is read.
8730fn fresh_plane(
8731 source: &[u8],
8732 width: usize,
8733 height: usize,
8734 true_width: usize,
8735 true_height: usize,
8736) -> Plane<'_> {
8737 Plane {
8738 source,
8739 reconstruction: vec![128; source.len()],
8740 width,
8741 height,
8742 true_width,
8743 true_height,
8744 tile_x0: 0,
8745 tile_y0: 0,
8746 tile_x1: width,
8747 tile_y1: height,
8748 ctx: CoefCtxMap::default(),
8749 }
8750}
8751
8752/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
8753/// the frame's plane, through the [`crate::par::Shared`] every job holds.
8754///
8755/// corner-cut: the disjointness that makes the aliasing sound is the caller's
8756/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
8757/// rectangles partition it -- checked end-to-end by
8758/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
8759/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
8760/// row-range `split_at_mut` plumbing through `Plane`, which would have to
8761/// thread an origin offset through every prediction and transform call site
8762/// for the same bytes.
8763#[allow(unsafe_code)]
8764fn copy_rect(
8765 dst: crate::par::Shared<'_, Vec<u8>>,
8766 src: &[u8],
8767 stride: usize,
8768 x0: usize,
8769 y0: usize,
8770 x1: usize,
8771 y1: usize,
8772) {
8773 // SAFETY: this job touches only its own tile rectangle (see above).
8774 let dst = unsafe { dst.get() };
8775 for y in y0..y1 {
8776 let (a, b) = (y * stride + x0, y * stride + x1);
8777 dst[a..b].copy_from_slice(&src[a..b]);
8778 }
8779}
8780
8781/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
8782/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
8783/// tables the frame stores (spec 7.20), which is what
8784/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
8785/// below publish.
8786fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
8787 ec_av1_syntax::TileInfo {
8788 uniform_spacing: true,
8789 cols: layout.cols(),
8790 rows: layout.rows(),
8791 cols_log2: layout.cols_log2,
8792 rows_log2: layout.rows_log2,
8793 mi_col_starts: layout.mi_col_starts(),
8794 mi_row_starts: layout.mi_row_starts(),
8795 context_update_tile_id: layout.largest_tile() as u32,
8796 tile_size_bytes,
8797 }
8798}
8799
8800/// Clips the three planes' intra edge reads to `rect`, the tile the
8801/// superblock about to be searched belongs to (the encoder side of the
8802/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
8803/// raster order -- which is a linear extension of every tile's own coding
8804/// order, so a block still only ever predicts from samples already
8805/// reconstructed -- and only availability is tile-relative.
8806fn clip_planes_to_tile(
8807 luma: &mut Plane<'_>,
8808 chroma: &mut [Plane<'_>; 2],
8809 rect: crate::tile::TileRect,
8810) {
8811 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8812 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8813 luma.set_tile(x0, y0, x1, y1);
8814 for plane in chroma.iter_mut() {
8815 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
8816 }
8817}
8818
8819/// Encodes one picture as a key frame.
8820///
8821/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
8822/// picks its coefficient CDFs from one of four q contexts by that index.
8823/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
8824/// smaller values trade fidelity for rate.
8825///
8826/// The picture may be any even width and height: the encoder pads it by edge
8827/// replication to a whole number of 32x32 blocks internally, and the frame it
8828/// writes crops back to the picture's own size (`render_width`/
8829/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
8830/// own size, never the padded one.
8831///
8832/// # Errors
8833/// Returns an error when the picture's width or height is zero or odd, or
8834/// when its planes are not 4:2:0 of that size.
8835/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
8836/// stream. The per-frame decode state this needs lives for exactly this call.
8837///
8838/// # Errors
8839/// Returns an error under the same conditions
8840/// [`encode_key_frame_with_modes`] does.
8841pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
8842 encode_key_frame_with_ctx(
8843 picture,
8844 base_q_idx,
8845 deadzone,
8846 &crate::decode::FrameCtx::for_encoder(),
8847 )
8848}
8849
8850/// [`encode_key_frame`] with the per-block intra modes given rather than
8851/// searched.
8852///
8853/// # Errors
8854/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
8855/// is empty, or when a block's coefficients do not fit the coded frame.
8856pub fn encode_key_frame_with_modes(
8857 picture: &Picture,
8858 base_q_idx: u8,
8859 deadzone: f64,
8860 modes: &[u8],
8861) -> Result<Encoded> {
8862 encode_key_frame_with_modes_with_ctx(
8863 picture,
8864 base_q_idx,
8865 deadzone,
8866 modes,
8867 &crate::decode::FrameCtx::for_encoder(),
8868 )
8869}
8870
8871/// Codes `pictures` as one key frame followed by inter frames.
8872///
8873/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
8874/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
8875/// `show_existing_frame` header, so `stream` is in CODING order while
8876/// `frames` stays in display order (`EncodedSequence::coding_order` is the
8877/// map). Screen content codes flat, decided once per sequence by the same
8878/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
8879/// puts every stream back on the flat path for an A/B.
8880///
8881/// # Errors
8882/// Returns an error under the same conditions [`encode_key_frame`] and the
8883/// inter frame path do.
8884pub fn encode_sequence(
8885 pictures: &[Picture],
8886 base_q_idx: u8,
8887 deadzone: f64,
8888) -> Result<EncodedSequence> {
8889 encode_sequence_with_ctx(
8890 pictures,
8891 base_q_idx,
8892 deadzone,
8893 &crate::decode::FrameCtx::for_encoder(),
8894 )
8895}
8896
8897pub(crate) fn encode_key_frame_with_ctx(
8898 picture: &Picture,
8899 base_q_idx: u8,
8900 deadzone: f64,
8901 fctx: &crate::decode::FrameCtx,
8902) -> Result<Encoded> {
8903 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
8904}
8905
8906/// Encodes one picture as a key frame, choosing each block's luma mode from
8907/// `modes` alone.
8908///
8909/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
8910/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
8911/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
8912/// uses.
8913///
8914/// # Errors
8915/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
8916/// names a mode [`crate::intra::predict`] does not predict.
8917pub(crate) fn encode_key_frame_with_modes_with_ctx(
8918 picture: &Picture,
8919 base_q_idx: u8,
8920 deadzone: f64,
8921 modes: &[u8],
8922 fctx: &crate::decode::FrameCtx,
8923) -> Result<Encoded> {
8924 picture.check_even()?;
8925 let padded = picture.padded_to(BLOCK);
8926 let encoded = encode_key_frame_inner(
8927 &padded,
8928 base_q_idx,
8929 deadzone,
8930 modes,
8931 split_blocks(),
8932 (picture.width, picture.height),
8933 unspecified_color_config(),
8934 fctx,
8935 )?;
8936 Ok(crop_encoded(&encoded, picture.width, picture.height))
8937}
8938
8939/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
8940/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
8941/// already padded to a whole number of 32x32 blocks; `render` is the real
8942/// (pre-pad) size the frame header tells a decoder to crop back to.
8943pub(crate) fn encode_key_frame_inner(
8944 picture: &Picture,
8945 base_q_idx: u8,
8946 deadzone: f64,
8947 modes: &[u8],
8948 split_blocks: bool,
8949 render: (usize, usize),
8950 color_config: ColorConfig,
8951 fctx: &crate::decode::FrameCtx,
8952) -> Result<Encoded> {
8953 // lane-refs: an intra frame runs no motion compensation, and the
8954 // context is shared across the sequence -- put the kernel back to the
8955 // default so nothing reads the previous inter frame's.
8956 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
8957 picture.check()?;
8958 if modes.is_empty() {
8959 return Err(Error::unsupported(
8960 "AV1 encode",
8961 "a mode search needs at least one mode to choose from",
8962 ));
8963 }
8964 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
8965 return Err(Error::unsupported(
8966 "AV1 encode",
8967 format!("intra mode {bad} is not one the encoder predicts"),
8968 ));
8969 }
8970 // The header carries the frame's true (unpadded) size as `frame_width`/
8971 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
8972 // `mi_rows` derived from that same true size (spec `compute_image_size`).
8973 // `render_width`/`render_height` come out equal to it too, so
8974 // `render_and_frame_size_different` is false and no render_size bits are
8975 // written, mirroring libaom/rav1e: the padded `picture` below is only the
8976 // internal coding surface, never what the header names.
8977 // Screen-content detection runs on the SOURCE luma, before any header is
8978 // built: it decides this sequence's `seq_force_screen_content_tools` (and
8979 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
8980 // this frame's own `allow_screen_content_tools`.
8981 let screen = screen_content(
8982 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8983 picture.width,
8984 (picture.width).min(render.0),
8985 (picture.height).min(render.1),
8986 );
8987 arm_seq_screen(screen);
8988 // A key frame's writer really does start from the defaults, and a search
8989 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
8990 // disarm, or a key frame's bits would depend on which thread searched it.
8991 crate::tile::arm_pricing_cdfs(None, false);
8992 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
8993 // forces deblocking, CDEF and loop restoration OFF for this frame
8994 // (frame.rs:194/210/252/272), so it is only set when the source repeats
8995 // itself enough for the copied blocks to pay that back
8996 // ([`intrabc_worth_it`]).
8997 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
8998 // grid across every tile while this writer builds one per tile, so a
8999 // multi-tile allow_intrabc frame would predict its DVs off a different
9000 // grid than the decoder does. corner-cut, ceiling named: the upgrade
9001 // path is a frame-scoped grid shared by the tile writers.
9002 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
9003 intrabc_worth_it(
9004 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
9005 picture.width,
9006 picture.width.min(render.0),
9007 picture.height.min(render.1),
9008 )
9009 } else {
9010 (false, 0.0)
9011 };
9012 IBC_SHARE.with(|c| c.set(ibc_share));
9013 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
9014 header.allow_screen_content_tools = screen;
9015 // lane-txi: the wider `tx_type` alphabets, gated by the same content
9016 // rule the type search itself stands behind ([`wide_tx_set`]).
9017 header.reduced_tx_set = !wide_tx_set(screen);
9018 header.allow_intrabc = allow_intrabc;
9019 header.render_width = render.0 as u32;
9020 header.render_height = render.1 as u32;
9021 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
9022 // its luma transform below its own side (`crate::tile::write_luma_select`).
9023 // Set here rather than in `key_frame_headers_colour` so the header
9024 // builders' other callers -- the hand-built tile writers, which code no
9025 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
9026 let tx_select = tx_select();
9027 if tx_select {
9028 header.tx_mode = TxMode::Select;
9029 }
9030 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
9031
9032 // Prediction reads no further than this, in each plane's own units --
9033 // see `Plane::true_width`/`true_height`.
9034 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
9035 // lane-palw: the encoder's own in-process reconstruct reads its palette
9036 // colour-index maps back through `decode::palette_onscreen`, which takes
9037 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
9038 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
9039 // them here so the reconstruct clamps a block cut by the frame edge
9040 // exactly as the writer now does.
9041 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
9042 fctx.seg_mi_dims.set(frame_mi_dims);
9043 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
9044 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
9045 // design (see `intra_predict_u8`'s doc comment), so narrow the source
9046 // once here.
9047 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
9048 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
9049 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
9050 let mut luma = Plane {
9051 source: &picture_y8,
9052 reconstruction: vec![128; picture_y8.len()],
9053 width: picture.width,
9054 height: picture.height,
9055 true_width,
9056 true_height,
9057 tile_x0: 0,
9058 tile_y0: 0,
9059 tile_x1: picture.width,
9060 tile_y1: picture.height,
9061 ctx: CoefCtxMap::default(),
9062 };
9063 let mut chroma = [
9064 Plane {
9065 source: &picture_u8,
9066 reconstruction: vec![128; picture_u8.len()],
9067 width: picture.width / 2,
9068 height: picture.height / 2,
9069 true_width: true_width / 2,
9070 true_height: true_height / 2,
9071 tile_x0: 0,
9072 tile_y0: 0,
9073 tile_x1: picture.width / 2,
9074 tile_y1: picture.height / 2,
9075 ctx: CoefCtxMap::default(),
9076 },
9077 Plane {
9078 source: &picture_v8,
9079 reconstruction: vec![128; picture_v8.len()],
9080 width: picture.width / 2,
9081 height: picture.height / 2,
9082 true_width: true_width / 2,
9083 true_height: true_height / 2,
9084 tile_x0: 0,
9085 tile_y0: 0,
9086 tile_x1: picture.width / 2,
9087 tile_y1: picture.height / 2,
9088 ctx: CoefCtxMap::default(),
9089 },
9090 ];
9091
9092 // The search trades a bit for the squared error it saves, in the units the
9093 // reconstruction is measured in: one step of the quantizer, squared.
9094 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
9095 let search = Search {
9096 base_q_idx,
9097 deadzone,
9098 lambda: lambda_scale() * key_lambda_factor() * step * step,
9099 modes,
9100 top_k: prune_top_k(),
9101 screen,
9102 arf_leaf_intra: true,
9103 arf_leaf8: true,
9104 arf_leaf_compound: true,
9105 };
9106
9107 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
9108 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
9109 // which may be fewer columns/rows than the padded picture has room for
9110 // -- a block whose origin sits past the true bound is not coded at all,
9111 // matching what a decoder derives from `frame_width`/`frame_height` and
9112 // so never visits either.
9113 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9114 let (cols, rows) = (cols as usize, rows as usize);
9115 // The luma mode of the block above and of the block to the left, which is
9116 // what picks the CDF the next block's mode is coded against -- the same
9117 // bookkeeping the tile writer keeps, so that the search is costing the
9118 // symbol the writer will actually write.
9119 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
9120 // because a 32x32 block may be split into four 16x16 ones.
9121 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9122 // This frame's tile grid (one tile unless the facade armed more).
9123 let layout = crate::tile::TileLayout::new(
9124 header.mi_cols,
9125 header.mi_rows,
9126 tile_cols_log2,
9127 tile_rows_log2,
9128 );
9129 header.tile_info = tile_info_of(&layout, 1);
9130 // The filter search re-decodes this frame's tiles; the decoder derives
9131 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
9132 // `mi_row_starts`), which is what makes the writer's rects and the
9133 // reader's the same rects.
9134 let header_tile_info = header.tile_info.clone();
9135 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
9136 // once over the whole frame. Each tile job builds its own reconstruction
9137 // planes and its own `above_mode`/`left_mode` bands, which is also what
9138 // the tile writer reads -- a tile resets its neighbour contexts (spec
9139 // 5.11.1), so a block at a tile's left edge must cost its mode against
9140 // the default context, not against whatever the tile to its west left in
9141 // that row. At one tile the bands are the frame's, exactly as before.
9142 let (frame_width, frame_height) = (picture.width, picture.height);
9143 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
9144 let [cb, cr] = &mut chroma;
9145 let chroma_out = [
9146 crate::par::Shared::new(&mut cb.reconstruction),
9147 crate::par::Shared::new(&mut cr.reconstruction),
9148 ];
9149 let search_tile = |index: usize,
9150 fctx: &crate::decode::FrameCtx|
9151 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
9152 crate::tile::arm_pricing_cdfs(None, false);
9153 let rect = layout.rect(index);
9154 let mut luma = fresh_plane(
9155 &picture_y8,
9156 frame_width,
9157 frame_height,
9158 true_width,
9159 true_height,
9160 );
9161 let mut chroma = [
9162 fresh_plane(
9163 &picture_u8,
9164 frame_width / 2,
9165 frame_height / 2,
9166 true_width / 2,
9167 true_height / 2,
9168 ),
9169 fresh_plane(
9170 &picture_v8,
9171 frame_width / 2,
9172 frame_height / 2,
9173 true_width / 2,
9174 true_height / 2,
9175 ),
9176 ];
9177 clip_planes_to_tile(&mut luma, &mut chroma, rect);
9178 let mut above_mode = vec![DC_PRED; cols * 2];
9179 let mut left_mode = vec![DC_PRED; rows * 2];
9180 let mut ibc = allow_intrabc.then(|| {
9181 Ibc::new(
9182 (
9183 rect.mi_col0 as usize * 4,
9184 rect.mi_row0 as usize * 4,
9185 (rect.mi_col1 as usize * 4).min(true_width),
9186 (rect.mi_row1 as usize * 4).min(true_height),
9187 ),
9188 &picture_y8,
9189 frame_width,
9190 )
9191 });
9192 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
9193 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
9194 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
9195 let mut modes = Vec::with_capacity(4);
9196 // The quadrants of a superblock are coded in the order the decoder
9197 // walks them, which for a 64x64 split into 32x32 blocks is raster
9198 // order among the quadrants that are inside the frame.
9199 let mut blocks = Vec::with_capacity(4);
9200 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
9201 // BEFORE its quadrants (so both start from the same
9202 // reconstruction) and compared against the four of them below --
9203 // the shape the inter frame's own 64 root takes
9204 // (`search_skip_64`). A frame that allows intrabc is refused
9205 // outright ([`I64_ROOT`]) because the quadrant searches below
9206 // carry DV state a discarded trial would desync.
9207 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
9208 // lane-corner LIFTED the two guards this root shipped with: the
9209 // frame no longer has to be a whole number of superblocks, and
9210 // the superblock no longer has to be wholly inside the frame.
9211 // The desync the guards were written for (a 248x152 corner's
9212 // chroma disagreeing three ways) does NOT reproduce at this
9213 // revision -- see
9214 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
9215 // which pins all three planes of the encoder's reconstruction,
9216 // our decoder and ffmpeg on four straddling sizes, three of them
9217 // cut on BOTH axes, with the edge fire count asserted. What the
9218 // guards cost was every key-frame root on an arbitrary export
9219 // size (the `aligned` line switched the whole feature off on, for
9220 // instance, a 1920x792 frame).
9221 let whole_inside =
9222 x64 + SUPERBLOCK <= luma.true_width && y64 + SUPERBLOCK <= luma.true_height;
9223 // lane-corner: and the superblock the true frame edge CUTS
9224 // THROUGH with more than half of each axis still inside, which is
9225 // all AV1 asks of a `PARTITION_NONE` root (spec
9226 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
9227 // key writer's `Superblock::Whole` arm checks) -- the shape the
9228 // inter root already takes ([`b64_edge`]).
9229 let edge_inside = edge_root_enabled()
9230 && crate::tile::has_half(
9231 sb_col as u32 * crate::tile::SB_MI,
9232 crate::tile::SB_MI,
9233 header.mi_cols,
9234 )
9235 && crate::tile::has_half(
9236 sb_row as u32 * crate::tile::SB_MI,
9237 crate::tile::SB_MI,
9238 header.mi_rows,
9239 );
9240 let sb64_legal = i64_root()
9241 && ibc.is_none()
9242 && sb_row * 2 + 1 < rows
9243 && sb_col * 2 + 1 < cols
9244 && (whole_inside || edge_inside);
9245 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
9246 if sb64_legal {
9247 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9248 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
9249 let (c64, r64) = (sb_col * 4, sb_row * 4);
9250 let (block, cost) = code_square(
9251 &mut luma,
9252 &mut chroma,
9253 (x64, y64),
9254 SUPERBLOCK,
9255 &search,
9256 &mode_bits(above_mode[c64], left_mode[r64]),
9257 tx_select,
9258 None,
9259 true,
9260 fctx,
9261 );
9262 let cost =
9263 cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
9264 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
9265 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
9266 sb64 = Some((cost, block, after));
9267 }
9268 // A superblock whose 64x64 trial already codes almost nothing per
9269 // pixel is taken outright and its quadrants are never searched --
9270 // `split_rd_breakout` one size up, at the threshold the inter
9271 // root clamps to ([`b64_breakout_threshold`]), where this lever
9272 // BUYS wall instead of spending it.
9273 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
9274 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
9275 });
9276 // What the four quadrants cost together, including the split
9277 // partition symbol at the superblock level, so the two arms are
9278 // one comparable number.
9279 let mut sb_cost = match sb64 {
9280 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
9281 None => 0.0,
9282 };
9283 for quadrant in 0..if early64 { 0 } else { 4 } {
9284 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
9285 if col >= cols || row >= rows {
9286 continue;
9287 }
9288 let (x, y) = (col * BLOCK, row * BLOCK);
9289 let (c0, r0) = (col * 2, row * 2);
9290 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
9291
9292 // spec `decode_partition`'s hasRows/hasCols recomputed at this
9293 // 32x32 block's own half (see `crate::tile::has_half`): the
9294 // true frame edge can fall inside a quadrant a superblock-level
9295 // check already let through. A quadrant that fails either may
9296 // not be left whole; a 16x16 sub-block that fails either (once
9297 // split) is a leaf this writer has no rectangular transform
9298 // for, so the search must not pick a split that would need one.
9299 let (has_cols32, has_rows32) = (
9300 crate::tile::has_half(
9301 col as u32 * crate::tile::BLOCK_MI,
9302 crate::tile::BLOCK_MI,
9303 header.mi_cols,
9304 ),
9305 crate::tile::has_half(
9306 row as u32 * crate::tile::BLOCK_MI,
9307 crate::tile::BLOCK_MI,
9308 header.mi_rows,
9309 ),
9310 );
9311 let whole_legal = has_cols32 && has_rows32;
9312 // A 16x16 sub-block's own hasCols/hasRows (spec
9313 // `decode_partition`, recomputed at this leaf's own half):
9314 // either axis false is a straddling leaf this writer codes as
9315 // the 8x8 leaves that are inside it
9316 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
9317 // false is the same split with the partition symbol inferred
9318 // rather than coded -- no rectangular transform is needed
9319 // (lane-av1rect).
9320 let sub_half = |sr: usize, sc: usize| {
9321 (
9322 crate::tile::has_half(
9323 sc as u32 * crate::tile::SUB_MI,
9324 crate::tile::SUB_MI,
9325 header.mi_cols,
9326 ),
9327 crate::tile::has_half(
9328 sr as u32 * crate::tile::SUB_MI,
9329 crate::tile::SUB_MI,
9330 header.mi_rows,
9331 ),
9332 )
9333 };
9334 // What the whole 32x32 costs, including the partition symbol
9335 // that says it is not split.
9336 let (whole, mut cost_whole) = code_square(
9337 &mut luma,
9338 &mut chroma,
9339 (x, y),
9340 BLOCK,
9341 &search,
9342 &mode_bits(above_mode[c0], left_mode[r0]),
9343 tx_select,
9344 ibc.as_mut(),
9345 true,
9346 fctx,
9347 );
9348 cost_whole += search.lambda * partition_bits(BLOCK, false);
9349 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
9350
9351 // What four 16x16 blocks cost instead, each searched against
9352 // the reconstruction the ones before it left.
9353 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
9354 let mut split = Vec::with_capacity(4);
9355 let mut cost_split = search.lambda
9356 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
9357 let mut split_modes = Vec::with_capacity(4);
9358 for sub in 0..4 {
9359 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
9360 // Same filter as the writer's `sub_positions` (spec
9361 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
9362 // return): a sub-block whose own origin sits past the
9363 // true frame is never coded, so it must not be searched
9364 // or pushed onto `split` either, or the writer's block
9365 // count will not match what it is prepared to name.
9366 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
9367 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
9368 {
9369 continue;
9370 }
9371 let (has_cols16, has_rows16) = sub_half(sr, sc);
9372 if has_cols16 && has_rows16 {
9373 let (block, cost) = code_square(
9374 &mut luma,
9375 &mut chroma,
9376 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
9377 SUB,
9378 &search,
9379 &mode_bits(above_mode[sc], left_mode[sr]),
9380 tx_select,
9381 ibc.as_mut(),
9382 true,
9383 fctx,
9384 );
9385 cost_split += cost;
9386 split_modes.push(block.mode);
9387 above_mode[sc] = block.mode;
9388 left_mode[sr] = block.mode;
9389 split.push(block);
9390 } else {
9391 // A straddling 16x16: two (or, at a true corner, one)
9392 // 8x8 leaves, in the raster order `write_leaf8`'s
9393 // caller expects. Both leaves cost against the SAME
9394 // enclosing-slot mode context (see
9395 // `crate::tile::write_leaf8`'s doc), and neither
9396 // updates `above_mode`/`left_mode` at this SUB slot --
9397 // the writer never does either, so the search must
9398 // not diverge from what it will actually read next.
9399 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
9400 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
9401 let mut leaves = Vec::with_capacity(2);
9402 for i in 0..4 {
9403 let leaf_x = x_sub + (i % 2) * 8;
9404 let leaf_y = y_sub + (i / 2) * 8;
9405 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
9406 continue;
9407 }
9408 let (leaf, cost) = code_square(
9409 &mut luma,
9410 &mut chroma,
9411 (leaf_x, leaf_y),
9412 8,
9413 &search,
9414 &leaf_mode_bits,
9415 tx_select,
9416 None,
9417 true,
9418 fctx,
9419 );
9420 cost_split += cost;
9421 split_modes.push(leaf.mode);
9422 leaves.push(leaf);
9423 }
9424 split.push(BlockCoeffs {
9425 eight: Some(leaves),
9426 ..BlockCoeffs::default()
9427 });
9428 }
9429 }
9430
9431 // A split whose subs are all whole 16x16 is a real quality
9432 // alternative to `whole`, exactly as before. Through r14, a
9433 // split carrying an 8x8-leaf sub was only ever forced
9434 // (`!whole_legal`), never chosen on cost, because the leaf
9435 // path was not yet proven against a real decoder; r15 proved
9436 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
9437 // the read path (`decode_leaf8`), so leaf8 can now win on
9438 // cost anywhere, same as any other split.
9439 if !whole_legal || (split_blocks && cost_split < cost_whole) {
9440 sb_cost += cost_split;
9441 modes.extend_from_slice(&split_modes);
9442 blocks.push(Quadrant::Split(split));
9443 } else {
9444 sb_cost += cost_whole;
9445 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
9446 for cell in 0..2 {
9447 above_mode[c0 + cell] = whole.mode;
9448 left_mode[r0 + cell] = whole.mode;
9449 }
9450 modes.push(whole.mode);
9451 blocks.push(Quadrant::Whole(whole));
9452 }
9453 }
9454 let index = sb_row * sb_cols + sb_col;
9455 match sb64 {
9456 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
9457 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
9458 for cell in 0..4 {
9459 above_mode[sb_col * 4 + cell] = block.mode;
9460 left_mode[sb_row * 4 + cell] = block.mode;
9461 }
9462 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9463 if !whole_inside {
9464 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9465 }
9466 let mode = block.mode;
9467 coded.push((index, Superblock::Whole(block), vec![mode]));
9468 }
9469 _ => coded.push((index, Superblock::Split(blocks), modes)),
9470 }
9471 }
9472 }
9473 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
9474 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
9475 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
9476 for (&out, tile) in chroma_out.iter().zip(&chroma) {
9477 copy_rect(
9478 out,
9479 &tile.reconstruction,
9480 frame_width / 2,
9481 x0 / 2,
9482 y0 / 2,
9483 x1.div_ceil(2),
9484 y1.div_ceil(2),
9485 );
9486 }
9487 Ok(coded)
9488 };
9489 let searched = search_tiles(layout.count(), fctx, search_tile)?;
9490 // Back into frame raster order: the tile writer indexes `superblocks` by
9491 // the frame's own superblock index, and `modes` is the coding order the
9492 // ablation drivers read.
9493 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> =
9494 (0..sb_cols * sb_rows).map(|_| None).collect();
9495 for (at, superblock, block_modes) in searched.into_iter().flatten() {
9496 in_order[at] = Some((superblock, block_modes));
9497 }
9498 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
9499 let mut modes = Vec::with_capacity(cols * rows);
9500 for slot in in_order {
9501 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
9502 superblocks.push(superblock);
9503 modes.extend_from_slice(&block_modes);
9504 }
9505
9506 #[cfg(test)]
9507 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(
9508 &superblocks,
9509 base_q_idx,
9510 ));
9511 // A key frame always starts from the defaults (`primary_ref_frame` is
9512 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
9513 // set, so what it stores into the slots it refreshes is exactly those
9514 // defaults again (spec 7.20's `started_from` arm) -- the first inter
9515 // frame after it therefore starts from the defaults too.
9516 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
9517 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
9518 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
9519 // from -- `Cdfs::txb` widens every luma set under it.
9520 cdfs.reduced_tx_set = header.reduced_tx_set;
9521 let start_cdfs = CdfSnapshot(cdfs);
9522 // The luma restoration-unit grid this frame's `lr_params` implies
9523 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
9524 // swallowed by the one before it), for the tile writer's own per-unit
9525 // walk.
9526 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
9527 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
9528 // Every tile is coded from this frame's OWN starting tables and leaves
9529 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
9530 // loop-restoration reference and its neighbour contexts), so the tiles
9531 // are independent of each other and of the order they are written in.
9532 let code_tiles = |bits: u8,
9533 sb_cols: usize,
9534 grid: &[u8],
9535 units: &[Option<crate::restoration::WienerInfo>]|
9536 -> Result<Vec<Vec<u8>>> {
9537 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
9538 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
9539 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
9540 crate::tile::arm_sb128(sb128_on());
9541 let mut cdfs = start_cdfs.0.clone();
9542 crate::tile::arm_screen(screen);
9543 crate::tile::arm_frame_mi_dims(frame_mi_dims);
9544 crate::tile::arm_filter_intra(filter_intra_on());
9545 crate::tile::arm_intrabc(allow_intrabc);
9546 crate::tile::arm_pricing_cdfs(None, false);
9547 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
9548 mi_cols,
9549 mi_rows,
9550 base_q_idx,
9551 &superblocks,
9552 tx_select,
9553 &mut cdfs,
9554 layout.rect(index),
9555 )?;
9556 Ok((bytes, None))
9557 })?;
9558 Ok(out)
9559 };
9560 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
9561 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
9562 // the tile just coded back to the decoder under each candidate (see
9563 // `crate::filter_search`), and keep the filtered picture that wins as
9564 // the reconstruction -- what a decoder outputs, and what the next
9565 // frame predicts from.
9566 pick_and_apply_filters(
9567 &mut header,
9568 &mut luma,
9569 &mut chroma,
9570 [&picture_y8, &picture_u8, &picture_v8],
9571 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
9572 // and loop restoration off and codes none of their parameters
9573 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
9574 // the encoder's reconstruction is already what a decoder produces.
9575 !allow_intrabc,
9576 &mut tiles,
9577 search.lambda,
9578 fctx,
9579 // A key frame codes no 128x128 root block (the writer has no intra
9580 // path at that size), so every unit carries its own literal.
9581 &[],
9582 // Every re-code starts from this frame's OWN starting tables, never
9583 // from where the first write left them: the second tile is the same
9584 // symbol sequence plus new ones, so it must adapt from the same
9585 // point the decoder will.
9586 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
9587 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
9588 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
9589 crate::decode::decode_key_frame_tiles_lr(
9590 &payloads,
9591 &header_tile_info,
9592 h.mi_cols,
9593 h.mi_rows,
9594 base_q_idx,
9595 h.frame_width,
9596 h.frame_height,
9597 seq.enable_filter_intra,
9598 cdef,
9599 lf,
9600 tx_select,
9601 h.reduced_tx_set,
9602 h.allow_screen_content_tools,
9603 h.allow_intrabc,
9604 lr,
9605 fctx,
9606 )
9607 },
9608 )?;
9609 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
9610 header.tile_info.tile_size_bytes = tile_size_bytes;
9611 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
9612 let mut stream = temporal_delimiter();
9613 stream.extend_from_slice(&sequence_header_obu(&seq)?);
9614 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
9615
9616 let [u, v] = chroma;
9617 Ok(Encoded {
9618 stream,
9619 modes,
9620 inter_block_share: 0.0,
9621 reconstruction: Picture {
9622 width: luma.width,
9623 height: luma.height,
9624 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9625 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9626 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9627 },
9628 tile,
9629 mi_cols: header.mi_cols,
9630 mi_rows: header.mi_rows,
9631 base_q_idx,
9632 tx_select,
9633 // A key frame codes no inter block, so no motion_mode symbol.
9634 switchable_motion_mode: false,
9635 screen,
9636 reduced_tx_set: header.reduced_tx_set,
9637 next_cdfs: start_cdfs.clone(),
9638 start_cdfs,
9639 loop_filter: header.loop_filter,
9640 cdef: header.cdef,
9641 loop_restoration: header.loop_restoration,
9642 allow_intrabc,
9643 delta: header.delta.clone(),
9644 })
9645}
9646
9647/// Chooses this frame's deblocking levels and CDEF strengths, writes them
9648/// into `header` and
9649/// replaces the frame's own region of the encoder's reconstruction with the
9650/// filtered picture the decoder produced under them
9651/// ([`crate::filter_search::pick_deblock`]).
9652///
9653/// `search == false` leaves the header at level 0 (deblocking off) and the
9654/// reconstruction untouched: the caller's stream is one this crate's own
9655/// decoder cannot read back, so there is nothing to search against.
9656///
9657/// # Errors
9658/// The decoder's own error, when it refuses the tile the encoder just wrote
9659/// -- that is an encoder defect, not a filter one, so it is propagated
9660/// rather than swallowed into "no deblocking".
9661fn pick_and_apply_filters(
9662 header: &mut FrameHeader,
9663 luma: &mut Plane<'_>,
9664 chroma: &mut [Plane<'_>; 2],
9665 source: [&[u8]; 3],
9666 search: bool,
9667 // The coded tiles, one payload per tile of the frame's grid, replaced in
9668 // place when the search chooses a per-64x64 `cdef_idx` list
9669 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
9670 // tile is written a second time under `recode` and the winner
9671 // re-decoded from them.
9672 tiles: &mut Vec<Vec<u8>>,
9673 lambda: f64,
9674 fctx: &crate::decode::FrameCtx,
9675 // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles
9676 // carry -- empty (the identity map) for a frame whose every block covers
9677 // one 64x64 CDEF unit.
9678 cdef_owner: &[u32],
9679 recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<Vec<u8>>>,
9680 decode: impl Fn(
9681 &LoopFilterParams,
9682 &CdefParams,
9683 &FrameHeader,
9684 &[Vec<u8>],
9685 &LoopRestorationParams,
9686 ) -> Result<Picture>,
9687) -> Result<()> {
9688 if !search {
9689 return Ok(());
9690 }
9691 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
9692 let hdr = header.clone();
9693 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
9694 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
9695 let damping = 3 + (header.quantization.base_q_idx >> 6);
9696 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9697 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
9698 let none_lr = LoopRestorationParams::default();
9699 // Every candidate scores the same coded tile: decode it once and re-run
9700 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
9701 // the encoder's profile before this). The per-64x64 error the CDEF
9702 // preset search reads comes off the REPLAYED picture, which is the same
9703 // picture a decode produces -- that is what the replay is pinned on.
9704 crate::decode::clear_filter_replay();
9705 // lane-av1fpar: the per-tile search is over, so every core is idle from
9706 // here to the end of the frame -- band each candidate's deblock/CDEF
9707 // replay, the capture decode's own filter chain and the loop-restoration
9708 // passes across the same workers the search used.
9709 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
9710 let ft = crate::par::timer(crate::par::S_FILTER);
9711 let search_result = crate::filter_search::pick_filters(
9712 |lf, cdef| {
9713 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
9714 return Ok(picture);
9715 }
9716 crate::decode::arm_filter_replay();
9717 let _t = crate::par::timer(crate::par::S_FIRST);
9718 decode(lf, cdef, &hdr, tiles, &none_lr)
9719 },
9720 source,
9721 luma.width,
9722 (fw, fh),
9723 damping,
9724 (sb_cols, sb_rows),
9725 lambda,
9726 cdef_owner,
9727 );
9728 drop(ft);
9729 let (lf, cdef, idx_grid, picture) = search_result?;
9730 header.loop_filter = lf;
9731 header.cdef = cdef;
9732 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
9733 // in the frame header, so a re-decode under candidate parameters cannot
9734 // search them the way deblocking and CDEF are searched above. What the
9735 // decoder hands back instead is its own filter chain's intermediates
9736 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
9737 // those, through the decoder's own Wiener kernel.
9738 //
9739 // The capture rides the decode this stage was already going to do: the
9740 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
9741 // decode of the tile as it stands. That decode's header still says
9742 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
9743 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
9744 // an approximation inside the SEARCH only; the reconstruction this
9745 // function ends up splicing is always a real decode of the real tile.
9746 let lr_on = restoration_enabled();
9747 // The `cdef_idx` literals live in the tile payload, so a frame that
9748 // chose a per-64x64 preset list codes its tiles a second time.
9749 if !idx_grid.is_empty() {
9750 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
9751 }
9752 // lane-av1cap: that re-coded tile used to be DECODED here as well --
9753 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
9754 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
9755 // and the picture this function splices. Both come out of ONE more
9756 // replay of the winning parameters on the same captured pre-filter
9757 // planes every candidate was scored on: the same two filter kernels, on
9758 // the same input, in the same order, so the same bytes. Re-coding the
9759 // tile does not move the reconstruction the replay holds -- `cdef_idx`
9760 // is an equiprobable literal, so it adapts no CDF and changes no
9761 // residual.
9762 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
9763 #[cfg(test)]
9764 let replay_was_used = replayed.is_some();
9765 let (mut filtered, mut stages) = match replayed {
9766 Some((picture, stages)) => (picture, stages),
9767 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
9768 // refuses): every candidate was a full decode, so the winner's own
9769 // picture stands, and the stages still need a capturing decode.
9770 None => {
9771 fctx.capture_stages.set(lr_on);
9772 let picture = if idx_grid.is_empty() && !lr_on {
9773 picture
9774 } else {
9775 let _t = crate::par::timer(crate::par::S_CAPTURE);
9776 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
9777 };
9778 fctx.capture_stages.set(false);
9779 (picture, crate::decode::take_filter_stages(fctx))
9780 }
9781 };
9782 #[cfg(test)]
9783 if crate::decode::verify_final_replay() && replay_was_used {
9784 fctx.capture_stages.set(lr_on);
9785 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
9786 fctx.capture_stages.set(false);
9787 let want_stages = crate::decode::take_filter_stages(fctx);
9788 assert!(
9789 (want.width, want.height) == (filtered.width, filtered.height)
9790 && want.y == filtered.y
9791 && want.u == filtered.u
9792 && want.v == filtered.v,
9793 "the final filter replay is not the capture decode it stands in for",
9794 );
9795 // Only the frame's own cropped region: the plane is padded to the
9796 // superblock grid and the columns past the mi extent are written by
9797 // nothing (the decoder's plane pool leaves whatever the last frame
9798 // put there), while the restoration search reads strictly inside
9799 // `fw x fh` -- `restoration::lr_sample` clamps its column to
9800 // `plane_w - 1` and its row to the frame's, and
9801 // `filter_search::pick_restoration`'s own SSE walk never leaves the
9802 // crop either.
9803 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
9804 for row in 0..h {
9805 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
9806 assert!(
9807 x == y,
9808 "{what}: the replayed filter stages are not the ones the capture \
9809 decode returns (row {row} of {h}, width {w}, stride {stride})",
9810 );
9811 }
9812 };
9813 match (&want_stages, &stages) {
9814 (Some(a), Some(b)) => {
9815 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
9816 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9817 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
9818 region(
9819 &a.deblocked[i],
9820 &b.deblocked[i],
9821 a.stride[i],
9822 w,
9823 h,
9824 "deblocked",
9825 );
9826 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
9827 }
9828 }
9829 (None, None) => {}
9830 _ => panic!("one path captured filter stages and the other did not"),
9831 }
9832 }
9833 // lane-av1cap2: the capture stays live past the restoration search --
9834 // `crate::decode::replay_restoration` filters the same post-CDEF plane
9835 // rather than decoding the re-coded tile. Cleared at the end instead.
9836 let mut lr = LoopRestorationParams::default();
9837 if lr_on {
9838 let unit = lr_unit();
9839 let mut want = LoopRestorationParams {
9840 loop_restoration_size: [unit, unit, unit],
9841 uses_lr: true,
9842 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
9843 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
9844 lr_unit_shift: u8::from(unit == 128),
9845 ..LoopRestorationParams::default()
9846 };
9847 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
9848 let lrt = crate::par::timer(crate::par::S_LR);
9849 let units = match stages.take() {
9850 Some(stages) => crate::filter_search::pick_restoration(
9851 &stages,
9852 source[0],
9853 luma.width,
9854 (fw, fh),
9855 &want,
9856 lambda,
9857 fctx,
9858 ),
9859 None => Vec::new(),
9860 };
9861 // A frame no unit restores keeps `RESTORE_NONE` on every plane
9862 // rather than paying ~1 bit per 64x64 for a tile full of
9863 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
9864 // clip whose units never take a filter).
9865 drop(lrt);
9866 if units.iter().any(Option::is_some) {
9867 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
9868 let _t = crate::par::timer(crate::par::S_CAPTURE);
9869 // lane-av1cap2: that re-coded tile used to be DECODED here to
9870 // reach the restored reference frame -- 5.6% of a 4K frame,
9871 // for a filter that reads nothing of the tile but the per-unit
9872 // Wiener filters this stage just chose. Run the decoder's own
9873 // restoration kernel on the replay's post-CDEF plane instead
9874 // (`crate::decode::replay_restoration`), with the real
9875 // post-deblock stripe borders.
9876 match crate::decode::replay_restoration(&want, &units, fctx) {
9877 Some(y) => {
9878 #[cfg(test)]
9879 let margin = fctx
9880 .last_frame_wide_margin
9881 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
9882 #[cfg(test)]
9883 if crate::decode::verify_final_replay() {
9884 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
9885 assert!(
9886 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
9887 && want_pic.u == filtered.u
9888 && want_pic.v == filtered.v,
9889 "the restoration replay moved a chroma plane or the picture size",
9890 );
9891 assert!(
9892 want_pic.y == y,
9893 "the restoration replay is not the decode of the re-coded tile",
9894 );
9895 assert!(
9896 fctx.last_frame_wide_margin
9897 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
9898 == margin,
9899 "the restoration replay's wide-margin luma is not the decode's",
9900 );
9901 }
9902 filtered.y = y;
9903 }
9904 // Nothing captured: the winner came out of a full decode,
9905 // so this one does too.
9906 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
9907 }
9908 *tiles = coded;
9909 lr = want;
9910 }
9911 }
9912 crate::decode::clear_filter_replay();
9913 header.loop_restoration = lr;
9914 let dec_cw = filtered.width.div_ceil(2);
9915 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9916 crate::filter_search::splice(
9917 &mut luma.reconstruction,
9918 luma.width,
9919 &filtered.y,
9920 filtered.width,
9921 fw,
9922 fh,
9923 );
9924 crate::filter_search::splice(
9925 &mut chroma[0].reconstruction,
9926 chroma[0].width,
9927 &filtered.u,
9928 dec_cw,
9929 cw,
9930 ch,
9931 );
9932 crate::filter_search::splice(
9933 &mut chroma[1].reconstruction,
9934 chroma[1].width,
9935 &filtered.v,
9936 dec_cw,
9937 cw,
9938 ch,
9939 );
9940 Ok(())
9941}
9942
9943/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
9944/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
9945/// since every block this crate's inter tile writer codes is 32x32.
9946const SIZE_GROUP_32: usize = 3;
9947
9948/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
9949/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
9950/// stack this encoder builds is ever asked to predict against.
9951const LAST_FRAME: i8 = 1;
9952
9953/// What an inter frame's intra branch spends to name each of the thirteen
9954/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
9955/// context, since an inter frame's intra blocks do not read their
9956/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
9957/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
9958/// state, so it is built once per frame.
9959fn inter_mode_bits() -> [f64; 13] {
9960 std::array::from_fn(|mode| {
9961 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
9962 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
9963 } else {
9964 0.0
9965 };
9966 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
9967 + angle
9968 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
9969 })
9970}
9971
9972/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
9973/// [`mc::predict`] takes, in the units of the plane it predicts into.
9974///
9975/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
9976/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
9977/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
9978/// domain. `luma` picks which.
9979fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
9980 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
9981}
9982
9983/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
9984/// that module): the magnitude an `MV_CLASS_n` component's own bits start
9985/// counting from.
9986fn mv_class_base(class: usize) -> i32 {
9987 if class == 0 { 0 } else { 2i32 << (class + 2) }
9988}
9989
9990/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
9991/// `tile::mv_class_of`.
9992fn mv_class_of(z: i32) -> usize {
9993 let mut class = 0;
9994 while class < 10 && mv_class_base(class + 1) <= z {
9995 class += 1;
9996 }
9997 class
9998}
9999
10000/// What [`crate::tile::write_mv_component`] (private to that module) would
10001/// spend coding one non-zero motion vector component, against the same
10002/// static default CDFs the writer starts a frame from — the same
10003/// static-table approximation [`mode_bits`] costs the luma mode symbol
10004/// through, not the tile writer's own adapting state, which this encoder has
10005/// no way to read without duplicating it block for block.
10006///
10007/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
10008/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
10009/// exists to avoid ever happening.
10010fn mv_component_bits(diff: i32) -> Option<f64> {
10011 let hp_frame = crate::tile::high_precision_mv();
10012 let mag = diff.unsigned_abs() as i32;
10013 let z = mag - 1;
10014 if !hp_frame && z & 1 == 0 {
10015 return None;
10016 }
10017 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
10018 let class = mv_class_of(z);
10019 bits += symbol_bits(&cdf::MV_CLASS, class);
10020 let local = z - mv_class_base(class);
10021 let hp = (local & 1) as usize;
10022 if class == 0 {
10023 let bit = (local >> 3) & 1;
10024 let fr = (local >> 1) & 3;
10025 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
10026 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
10027 // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
10028 // frame, so the pricer charges for it there and only there.
10029 if hp_frame {
10030 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
10031 }
10032 } else {
10033 let d = local >> 3;
10034 let fr = (local >> 1) & 3;
10035 for i in 0..class {
10036 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
10037 }
10038 bits += symbol_bits(&cdf::MV_FR, fr as usize);
10039 if hp_frame {
10040 bits += symbol_bits(&cdf::MV_HP, hp);
10041 }
10042 }
10043 Some(bits)
10044}
10045
10046/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
10047/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
10048/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
10049/// value without the second motion search's wall.
10050fn last2_new_mv() -> bool {
10051 match std::env::var("EC_AV1_LAST2_NEW").ok() {
10052 Some(v) => v != "0",
10053 None => true,
10054 }
10055}
10056
10057/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
10058/// own -- a second motion search per block against that reference's picture,
10059/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
10060/// off in a test build (what the lane measured both arms with).
10061fn extra_ref_new_mv() -> bool {
10062 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
10063 Some(v) if cfg!(test) => v != "0",
10064 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
10065 }
10066}
10067
10068/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
10069/// flat slot plan (`inter_frame_headers_slots`): every reference but
10070/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
10071/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
10072/// frame two back when there is one (otherwise it, too, names the key frame's
10073/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
10074pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
10075 let last = order_hint.wrapping_sub(1) & 0x7f;
10076 let alt = if has_altref {
10077 order_hint.wrapping_sub(2) & 0x7f
10078 } else {
10079 key_hint
10080 };
10081 [last, last, last, key_hint, last, last, alt]
10082}
10083
10084/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
10085/// header bit that lets each block choose between a single and a compound
10086/// reference. Off by default until compound prediction is measured to pay;
10087/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
10088/// runs as), and every block still codes SINGLE, so the only cost is one
10089/// `comp_mode` symbol per inter block.
10090pub(crate) const REFERENCE_SELECT: bool = true;
10091
10092/// [`REFERENCE_SELECT`], with the test-build environment override.
10093pub(crate) fn reference_select() -> bool {
10094 match std::env::var("EC_AV1_COMPOUND").ok() {
10095 Some(v) if cfg!(test) => v != "0",
10096 _ => crate::speed::at(&crate::speed::COMPOUND),
10097 }
10098}
10099
10100/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
10101/// per entry past `start`, `1` to advance and `0` to stop, at most two.
10102fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
10103 let mut bits = 0.0;
10104 let mut idx = start;
10105 while idx < start + 2 && stack.entries.len() > idx + 1 {
10106 let advance = idx < target;
10107 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
10108 if !advance {
10109 break;
10110 }
10111 idx += 1;
10112 }
10113 bits
10114}
10115
10116/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
10117/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
10118/// `assign_mv`), so the same vector costs a different residual from each.
10119fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
10120 let mut best: Option<(f64, u8)> = None;
10121 for idx in 0..3usize {
10122 if idx > 0 && stack.entries.len() <= idx {
10123 break;
10124 }
10125 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
10126 if let Some(b) = mv_residual_bits(mv, base) {
10127 let total = b + drl_bits_for(stack, 0, idx);
10128 if best.is_none_or(|(t, _)| total < t) {
10129 best = Some((total, idx as u8));
10130 }
10131 }
10132 }
10133 best
10134}
10135
10136/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
10137/// zero vector and the stack's own candidates. A neighbour block's vector is
10138/// where this block's motion most often already is, which is what pays for
10139/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
10140/// vs libaom for 0.2 s off a 6 s ladder).
10141fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
10142 let mut seeds = [(0, 0); 4];
10143 let mut n = 1;
10144 for e in stack.entries.iter().take(3) {
10145 seeds[n] = e.mv;
10146 n += 1;
10147 }
10148 (seeds, n)
10149}
10150
10151/// What [`crate::tile::write_mv`] (private to that module) would spend
10152/// coding `mv` as a residual against `pred`: the joint symbol naming which
10153/// components differ, then each differing component. `None` under the same
10154/// condition [`mv_component_bits`] returns `None`.
10155/// How many frames back `ref_frame` sits from the frame being coded, off the
10156/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
10157/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
10158/// what [`crate::motion::search`] scales its starting step by.
10159fn ref_distance(ref_frame: i8) -> u32 {
10160 let (bits, order_hint, hints) = crate::tile::order_hints();
10161 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
10162 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
10163 .unsigned_abs()
10164 .max(1);
10165 if crate::envflags::env_flag!("EC_TRACE_DIST") {
10166 eprintln!(
10167 "EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}",
10168 hints[i]
10169 );
10170 }
10171 d
10172}
10173
10174fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
10175 let diff = (mv.0 - pred.0, mv.1 - pred.1);
10176 let joint = match (diff.0 != 0, diff.1 != 0) {
10177 (false, false) => 0,
10178 (false, true) => 1,
10179 (true, false) => 2,
10180 (true, true) => 3,
10181 };
10182 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
10183 for d in [diff.0, diff.1] {
10184 if d != 0 {
10185 bits += mv_component_bits(d)?;
10186 }
10187 }
10188 Some(bits)
10189}
10190
10191/// Rounds `mv` so that its residual against `pred` is one
10192/// [`crate::tile::write_mv_component`] can actually code: each component's
10193/// difference is either zero or has an even magnitude (the eighth-pel bit
10194/// `allow_high_precision_mv` off always infers as one forces the coded
10195/// magnitude odd one step further in, which comes out even here since this
10196/// crate's motion search works in whole units of that same step). Rounding
10197/// down keeps every coded MV — and so every `nearest_mv` a later block's
10198/// stack votes with — built from an even displacement from `(0, 0)`, so the
10199/// invariant holds without this function seeing the whole stack.
10200/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
10201/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
10202/// always), the shape [`set_frame_interp`] has: the witness that has to see
10203/// `mv_hp` symbols coded turns it on through this while holding
10204/// [`crate::speed::knob_write`].
10205static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
10206
10207/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
10208#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
10209pub(crate) fn set_high_precision_mv(on: Option<bool>) {
10210 HP_MV_OVERRIDE.store(
10211 on.map_or(u8::MAX, u8::from),
10212 std::sync::atomic::Ordering::Relaxed,
10213 );
10214}
10215
10216/// The qindex below which an inter frame codes `allow_high_precision_mv`
10217/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
10218/// crate's shipped value, i.e. high-precision motion vectors off in every
10219/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
10220pub(crate) const HP_MV_QTHRESH: u8 = 0;
10221
10222/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
10223/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
10224/// always, any number as the threshold) so the BD gate can sweep the policy
10225/// without a rebuild.
10226pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
10227 match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
10228 0 => return false,
10229 1 => return true,
10230 _ => {}
10231 }
10232 static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
10233 let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
10234 Some("all" | "always") => 256,
10235 Some("0" | "off") => 0,
10236 Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
10237 None => u16::from(HP_MV_QTHRESH),
10238 });
10239 u16::from(base_q_idx) < threshold
10240}
10241
10242fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
10243 // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
10244 // residual is codable and there is nothing to round away.
10245 if crate::tile::high_precision_mv() {
10246 return mv;
10247 }
10248 let round = |m: i32, p: i32| {
10249 let diff = m - p;
10250 let mag = diff.unsigned_abs() as i32;
10251 let even = mag - mag % 2;
10252 if even == 0 {
10253 p
10254 } else {
10255 p + even * diff.signum()
10256 }
10257 };
10258 (round(mv.0, pred.0), round(mv.1, pred.1))
10259}
10260
10261/// Predicts one `side`-square block by motion compensation from `reference`
10262/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
10263#[allow(clippy::too_many_arguments)]
10264fn mc_trial(
10265 plane: &Plane,
10266 x: usize,
10267 y: usize,
10268 side: usize,
10269 mv: (i32, i32),
10270 luma: bool,
10271 reference: &[u16],
10272 stride: usize,
10273 ref_width: usize,
10274 ref_height: usize,
10275 skip: bool,
10276 base_q_idx: u8,
10277 deadzone: f64,
10278 set: TxbSet,
10279 fctx: &crate::decode::FrameCtx,
10280) -> Trial {
10281 mc_trial_typed(
10282 plane,
10283 x,
10284 y,
10285 side,
10286 mv,
10287 luma,
10288 reference,
10289 stride,
10290 ref_width,
10291 ref_height,
10292 skip,
10293 base_q_idx,
10294 deadzone,
10295 set,
10296 TxType::DctDct,
10297 fctx,
10298 )
10299}
10300
10301/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
10302#[allow(clippy::too_many_arguments)]
10303fn mc_trial_typed(
10304 plane: &Plane,
10305 x: usize,
10306 y: usize,
10307 side: usize,
10308 mv: (i32, i32),
10309 luma: bool,
10310 reference: &[u16],
10311 stride: usize,
10312 ref_width: usize,
10313 ref_height: usize,
10314 skip: bool,
10315 base_q_idx: u8,
10316 deadzone: f64,
10317 set: TxbSet,
10318 tx_type: TxType,
10319 fctx: &crate::decode::FrameCtx,
10320) -> Trial {
10321 let x_q4 = mv_to_q4(x, mv.1, luma);
10322 let y_q4 = mv_to_q4(y, mv.0, luma);
10323 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
10324 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
10325 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
10326 // lane-av1speed: both buffers are per-candidate scratch on the hottest
10327 // path in the encoder, so they live on the stack -- `side` is at most
10328 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
10329 // per motion-compensated trial otherwise.
10330 let mut prediction16 = [0u16; BLOCK * BLOCK];
10331 let prediction16 = &mut prediction16[..side * side];
10332 mc::predict(
10333 reference,
10334 stride,
10335 ref_width,
10336 ref_height,
10337 x_q4,
10338 y_q4,
10339 side,
10340 side,
10341 prediction16,
10342 fctx,
10343 );
10344 let mut prediction = [0u8; BLOCK * BLOCK];
10345 let prediction = &mut prediction[..side * side];
10346 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
10347 *dst = src as u8;
10348 }
10349 plane.code_from_prediction_typed(
10350 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
10351 )
10352}
10353
10354/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
10355/// references predict into the `CONV_BUF` intermediate domain
10356/// ([`mc::predict_compound_intermediate`]) and are blended by
10357/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
10358/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
10359/// block, so the encoder's reconstruction is the decoder's.
10360#[allow(clippy::too_many_arguments)]
10361fn mc_trial_compound(
10362 plane: &Plane,
10363 x: usize,
10364 y: usize,
10365 side: usize,
10366 mvs: ((i32, i32), (i32, i32)),
10367 luma: bool,
10368 ref0: (&[u16], usize, usize, usize),
10369 ref1: (&[u16], usize, usize, usize),
10370 base_q_idx: u8,
10371 deadzone: f64,
10372 set: TxbSet,
10373 fctx: &crate::decode::FrameCtx,
10374) -> Trial {
10375 mc_trial_compound_typed(
10376 plane,
10377 x,
10378 y,
10379 side,
10380 mvs,
10381 luma,
10382 ref0,
10383 ref1,
10384 base_q_idx,
10385 deadzone,
10386 set,
10387 TxType::DctDct,
10388 fctx,
10389 )
10390}
10391
10392/// [`mc_trial_compound`] coding its residual with a named transform type
10393/// (lane-txset2).
10394#[allow(clippy::too_many_arguments)]
10395fn mc_trial_compound_typed(
10396 plane: &Plane,
10397 x: usize,
10398 y: usize,
10399 side: usize,
10400 (mv0, mv1): ((i32, i32), (i32, i32)),
10401 luma: bool,
10402 ref0: (&[u16], usize, usize, usize),
10403 ref1: (&[u16], usize, usize, usize),
10404 base_q_idx: u8,
10405 deadzone: f64,
10406 set: TxbSet,
10407 tx_type: TxType,
10408 fctx: &crate::decode::FrameCtx,
10409) -> Trial {
10410 let mut inter0 = [0i32; BLOCK * BLOCK];
10411 let mut inter1 = [0i32; BLOCK * BLOCK];
10412 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
10413 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
10414 mc::predict_compound_intermediate(
10415 r.0,
10416 r.1,
10417 r.2,
10418 r.3,
10419 mv_to_q4(x, mv.1, luma),
10420 mv_to_q4(y, mv.0, luma),
10421 mc::REF_NO_SCALE,
10422 side,
10423 side,
10424 fctx.interp_filter.get(),
10425 fctx.interp_filter.get(),
10426 dst,
10427 fctx,
10428 );
10429 }
10430 let mut blended16 = [0u16; BLOCK * BLOCK];
10431 let blended16 = &mut blended16[..side * side];
10432 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
10433 let mut prediction = [0u8; BLOCK * BLOCK];
10434 let prediction = &mut prediction[..side * side];
10435 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
10436 *dst = src as u8;
10437 }
10438 plane.code_from_prediction_typed(
10439 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
10440 )
10441}
10442
10443/// Codes one 32x32 block of an inter frame as whichever costs least of: each
10444/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
10445/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
10446/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
10447/// coding a real residual (`skip: false`) whenever one prices out cheaper
10448/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
10449/// missing inter `tx_type` symbol (the desync this function's candidates
10450/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
10451/// fixed.
10452///
10453/// The symbol costs this ranks candidates by use fixed contexts (0) for
10454/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
10455/// contexts for those come from its own neighbour bookkeeping
10456/// (`tile::Neighbours`), which is private to that module and not worth
10457/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
10458/// `drl_mode` contexts come straight from `stack`, which is exact, because
10459/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
10460/// the tile writer derives from the same grid state.
10461#[allow(clippy::too_many_arguments)]
10462/// One prediction of `side` x `side` samples from `reference`, as `u8` --
10463/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
10464/// four times the stack scratch that function sizes for [`BLOCK`].
10465fn predict_u8(
10466 reference: &[u16],
10467 stride: usize,
10468 ref_width: usize,
10469 ref_height: usize,
10470 (x, y): (usize, usize),
10471 side: usize,
10472 mv: (i32, i32),
10473 luma: bool,
10474 fctx: &crate::decode::FrameCtx,
10475) -> Vec<u8> {
10476 let mut prediction = vec![0u16; side * side];
10477 mc::predict(
10478 reference,
10479 stride,
10480 ref_width,
10481 ref_height,
10482 mv_to_q4(x, mv.1, luma),
10483 mv_to_q4(y, mv.0, luma),
10484 side,
10485 side,
10486 &mut prediction,
10487 fctx,
10488 );
10489 prediction.iter().map(|&v| v as u8).collect()
10490}
10491
10492/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
10493/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
10494/// references predict into the `CONV_BUF` intermediate domain and are blended
10495/// at the simple-average split `(8, 8)`, the same path (and so the same
10496/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
10497fn predict_compound_u8(
10498 ref0: (&[u16], usize, usize, usize),
10499 ref1: (&[u16], usize, usize, usize),
10500 (x, y): (usize, usize),
10501 side: usize,
10502 (mv0, mv1): ((i32, i32), (i32, i32)),
10503 luma: bool,
10504 fctx: &crate::decode::FrameCtx,
10505) -> Vec<u8> {
10506 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
10507 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
10508 mc::predict_compound_intermediate(
10509 r.0,
10510 r.1,
10511 r.2,
10512 r.3,
10513 mv_to_q4(x, mv.1, luma),
10514 mv_to_q4(y, mv.0, luma),
10515 mc::REF_NO_SCALE,
10516 side,
10517 side,
10518 fctx.interp_filter.get(),
10519 fctx.interp_filter.get(),
10520 dst,
10521 fctx,
10522 );
10523 }
10524 let mut blended = vec![0u16; side * side];
10525 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
10526 blended.iter().map(|&v| v as u8).collect()
10527}
10528
10529/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
10530/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
10531/// one motion vector where the four 64x64 roots below spend four of each.
10532///
10533/// SKIP only (`residual: false`): a 128x128 block's residual is four
10534/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
10535/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
10536/// path for -- offering one here would price a block
10537/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
10538/// the same reason: the compound arm at this size is untested against the
10539/// writer's own `write_compound_block` window.
10540///
10541/// Only a root whose whole 128x128 lies inside the true frame AND inside
10542/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
10543/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
10544/// block would have to be ranked over its inside part alone.
10545///
10546/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
10547/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
10548/// against the four superblocks plus the SPLIT symbol.
10549#[allow(clippy::too_many_arguments)]
10550fn search_root_128(
10551 luma: &mut Plane,
10552 chroma: &mut [Plane; 2],
10553 grid: &crate::mvstack::MiGrid,
10554 (root_r, root_c): (usize, usize),
10555 // The 32x32-block grid this tile's `blocks` vector is indexed on.
10556 (rows, cols): (usize, usize),
10557 // The frame's own mode-info grid, which bounds the root.
10558 (mi_cols, mi_rows): (u32, u32),
10559 search: Search<'_>,
10560 tpl_factors: &Option<Vec<f64>>,
10561 sb_q: Option<&Vec<u8>>,
10562 sb_cols: usize,
10563 tpl_cells_x: usize,
10564 base_q_idx: u8,
10565 // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
10566 // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
10567 dq_res: i32,
10568 reference: &Picture,
10569 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
10570 // built by the caller off the same grid the tile writer rebuilds its
10571 // stack from (empty unless the frame carries `reference_select` and
10572 // [`b128_compound`] is on).
10573 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10574 fctx: &crate::decode::FrameCtx,
10575) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
10576 const SIDE: usize = SUPERBLOCK * 2;
10577 const SIDE_MI: usize = SIDE / 4;
10578 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10579 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10580 if root_r * 2 + 3 >= rows
10581 || root_c * 2 + 3 >= cols
10582 || (mi_row + SIDE_MI) as u32 > mi_rows
10583 || (mi_col + SIDE_MI) as u32 > mi_cols
10584 || x128 + SIDE > luma.true_width
10585 || y128 + SIDE > luma.true_height
10586 {
10587 return None;
10588 }
10589 // One lambda for the whole root, the mean of what its four superblocks
10590 // would each be searched at -- the 128-vs-four comparison weighs one cost
10591 // against four, so both sides have to be priced at the same lambda (the
10592 // same rule the 64 root's own mean-of-sixteen tpl cells follows).
10593 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10594 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10595 (None, Some(f)) => {
10596 let mean = (0..16)
10597 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10598 .sum::<f64>()
10599 / 16.0;
10600 search.lambda * mean
10601 }
10602 (None, None) => search.lambda,
10603 };
10604 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10605 .iter()
10606 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10607 .sum::<f64>()
10608 / 4.0;
10609 // The qindex this root is really quantized at: the delta_q unit is the
10610 // 128 superblock, so the root's own top-left cell is the one coded
10611 // (lane-b128m), and the residual arm below has to quantize at exactly it.
10612 let root_search = Search {
10613 lambda,
10614 ..match sb_q {
10615 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10616 None => search,
10617 }
10618 };
10619 let stack = find_mv_stack(
10620 grid,
10621 mi_row,
10622 mi_col,
10623 SIDE_MI,
10624 SIDE_MI,
10625 LAST_FRAME,
10626 mi_cols as usize,
10627 mi_rows as usize,
10628 );
10629 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10630 let found = search_skip_64(
10631 luma,
10632 chroma,
10633 (x128, y128),
10634 (SIDE, SIDE),
10635 &root_search,
10636 false,
10637 reference,
10638 &stack,
10639 compound,
10640 fctx,
10641 );
10642 let (mut cost, mut block) = found?;
10643 if block.inter.is_some_and(|i| i.ref1.is_some()) {
10644 B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10645 }
10646 // lane-b128r: the same prediction with a REAL residual, priced against
10647 // the skip arm the search just committed to the planes (which IS the
10648 // winner's prediction, sample for sample). The block's residual is four
10649 // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
10650 // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
10651 // sides the forward network already reaches, never as one 128-point
10652 // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
10653 //
10654 // The four `txfm_partition` symbols the writer codes for them are not
10655 // priced, exactly as the 64 root does not price its own (their contexts
10656 // are only known at write time); at four symbols a root this is under a
10657 // bit against residuals of hundreds.
10658 if b128_residual() && block.skip {
10659 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10660 // only its top-left corner), packed per plane into one 64-wide grid
10661 // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
10662 // `write_inter_block_128` slices back out in the same chunk order.
10663 let mut packed = [
10664 vec![0i32; 64 * 64],
10665 vec![0i32; 64 * 64],
10666 vec![0i32; 64 * 64],
10667 ];
10668 let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
10669 let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
10670 for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
10671 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10672 let (cx, cy) = (px / 2, py / 2);
10673 let half = SUPERBLOCK / 2;
10674 let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
10675 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10676 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10677 sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
10678 + chroma[0].block_sse(cx, cy, half, &pred_u)
10679 + chroma[1].block_sse(cx, cy, half, &pred_v);
10680 let trials = [
10681 luma.code_from_prediction(
10682 px,
10683 py,
10684 SUPERBLOCK,
10685 &pred_y,
10686 false,
10687 root_search.base_q_idx,
10688 root_search.deadzone,
10689 TxbSet::Luma64,
10690 ),
10691 chroma[0].code_from_prediction(
10692 cx,
10693 cy,
10694 half,
10695 &pred_u,
10696 false,
10697 root_search.base_q_idx,
10698 root_search.deadzone,
10699 TxbSet::Chroma32,
10700 ),
10701 chroma[1].code_from_prediction(
10702 cx,
10703 cy,
10704 half,
10705 &pred_v,
10706 false,
10707 root_search.base_q_idx,
10708 root_search.deadzone,
10709 TxbSet::Chroma32,
10710 ),
10711 ];
10712 for (plane, trial) in trials.iter().enumerate() {
10713 sse_res += trial.sse;
10714 coeff_bits += trial.bits;
10715 for row in 0..32 {
10716 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10717 .copy_from_slice(&trial.levels[row * 32..][..32]);
10718 }
10719 }
10720 chunks.push(((cr, cc), trials));
10721 }
10722 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
10723 // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
10724 // coefficients.
10725 let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
10726 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10727 if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
10728 B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10729 for ((cr, cc), trials) in &chunks {
10730 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10731 let half = SUPERBLOCK / 2;
10732 luma.commit(px, py, SUPERBLOCK, &trials[0]);
10733 chroma[0].commit(px / 2, py / 2, half, &trials[1]);
10734 chroma[1].commit(px / 2, py / 2, half, &trials[2]);
10735 }
10736 cost = res_cost;
10737 block.skip = false;
10738 block.tx_depth = 0;
10739 block.luma_tx_types = Vec::new();
10740 block.luma = coeffs(&packed[0], 64);
10741 block.u = coeffs(&packed[1], 64);
10742 block.v = coeffs(&packed[2], 64);
10743 }
10744 }
10745 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10746 restore(luma, chroma, (x128, y128), SIDE, &base);
10747 // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
10748 // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
10749 // residual arm above codes it like every other block does.
10750 let dq = if block.skip {
10751 0.0
10752 } else {
10753 delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
10754 };
10755 Some((
10756 cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
10757 lambda,
10758 block,
10759 after,
10760 ))
10761}
10762
10763/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
10764/// arm the caller's [`search_skip_64`] just committed to the planes (which
10765/// IS the winner's prediction, sample for sample -- the same rule
10766/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
10767/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
10768/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
10769/// each trial at sides the forward network already reaches, never a
10770/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
10771/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
10772///
10773/// The depth-0 `txfm_partition` symbols the writer codes for the units are
10774/// not priced, exactly as [`search_root_128`] does not price its four (their
10775/// contexts are only known at write time); at two symbols a half this is
10776/// under a bit against residuals of hundreds. On a win (or under the witness
10777/// force) the trials are committed to the planes, `block` is flipped to
10778/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
10779/// slices back out, and the new cost is returned; otherwise `cost` passes
10780/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
10781#[allow(clippy::too_many_arguments)]
10782fn search_rect_residual(
10783 luma: &mut Plane,
10784 chroma: &mut [Plane; 2],
10785 // The piece's own top-left, in luma samples.
10786 (px, py): (usize, usize),
10787 // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
10788 (w, h): (usize, usize),
10789 cost: f64,
10790 lambda: f64,
10791 search: &Search<'_>,
10792 // The piece's own mv stack, for the skip symbol's cost either way.
10793 stack: &crate::mvstack::MvStack,
10794 block: &mut BlockCoeffs,
10795) -> f64 {
10796 /// The 64x64 "mu" chunk side, luma; chroma halves it.
10797 const MU: usize = SUPERBLOCK;
10798 let chunks: [(usize, usize); 2] = match (w, h) {
10799 (128, 64) => [(0, 0), (0, 1)],
10800 (64, 128) => [(0, 0), (1, 0)],
10801 _ => [(0, 0), (0, 0)],
10802 };
10803 let n = if w.max(h) > MU { 2 } else { 1 };
10804 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10805 // only its top-left corner), packed per plane into one 64-wide grid with
10806 // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
10807 // back out in the same chunk order.
10808 let mut packed = [
10809 vec![0i32; 64 * 64],
10810 vec![0i32; 64 * 64],
10811 vec![0i32; 64 * 64],
10812 ];
10813 let mut sse_skip = 0.0f64;
10814 let mut sse_res = 0.0f64;
10815 let mut coeff_bits = 0.0f64;
10816 let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
10817 for &(cr, cc) in &chunks[..n] {
10818 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10819 let (cx, cy) = (cxx / 2, cyy / 2);
10820 let half = MU / 2;
10821 let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
10822 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10823 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10824 sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
10825 + chroma[0].block_sse(cx, cy, half, &pred_u)
10826 + chroma[1].block_sse(cx, cy, half, &pred_v);
10827 let trials = [
10828 luma.code_from_prediction(
10829 cxx,
10830 cyy,
10831 MU,
10832 &pred_y,
10833 false,
10834 search.base_q_idx,
10835 search.deadzone,
10836 TxbSet::Luma64,
10837 ),
10838 chroma[0].code_from_prediction(
10839 cx,
10840 cy,
10841 half,
10842 &pred_u,
10843 false,
10844 search.base_q_idx,
10845 search.deadzone,
10846 TxbSet::Chroma32,
10847 ),
10848 chroma[1].code_from_prediction(
10849 cx,
10850 cy,
10851 half,
10852 &pred_v,
10853 false,
10854 search.base_q_idx,
10855 search.deadzone,
10856 TxbSet::Chroma32,
10857 ),
10858 ];
10859 for (plane, trial) in trials.iter().enumerate() {
10860 sse_res += trial.sse;
10861 coeff_bits += trial.bits;
10862 for row in 0..32 {
10863 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10864 .copy_from_slice(&trial.levels[row * 32..][..32]);
10865 }
10866 }
10867 trials_per_chunk.push(trials);
10868 }
10869 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
10870 // pays the same syntax with `skip` coded 0 instead of 1, plus its
10871 // coefficients.
10872 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10873 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10874 if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
10875 for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
10876 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10877 let (cx, cy) = (cxx / 2, cyy / 2);
10878 let half = MU / 2;
10879 luma.commit(cxx, cyy, MU, &trials[0]);
10880 chroma[0].commit(cx, cy, half, &trials[1]);
10881 chroma[1].commit(cx, cy, half, &trials[2]);
10882 }
10883 block.skip = false;
10884 block.tx_depth = 0;
10885 block.luma_tx_types = Vec::new();
10886 block.luma = coeffs(&packed[0], 64);
10887 block.u = coeffs(&packed[1], 64);
10888 block.v = coeffs(&packed[2], 64);
10889 B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10890 res_cost
10891 } else {
10892 cost
10893 }
10894}
10895
10896/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
10897/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
10898/// shipped NONE machinery halved. Skip-only by default, single reference or
10899/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
10900/// ([`search_rect_residual`]) -- exactly what
10901/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
10902/// reads at `sb128_rect`.
10903///
10904/// The FIRST half is published into `grid` before the second is searched --
10905/// the writer publishes it too, so a second half searched against the stale
10906/// grid would be priced (and its mv predicted) off a stack the decoder never
10907/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
10908/// both planes are put back before returning; the caller re-applies the
10909/// winner.
10910///
10911/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
10912/// carrying the root's own partition symbol so it ranks against
10913/// [`search_root_128`] and against the four superblocks below.
10914#[allow(clippy::too_many_arguments)]
10915fn search_root_128_rect(
10916 luma: &mut Plane,
10917 chroma: &mut [Plane; 2],
10918 grid: &mut crate::mvstack::MiGrid,
10919 (root_r, root_c): (usize, usize),
10920 (rows, cols): (usize, usize),
10921 (mi_cols, mi_rows): (u32, u32),
10922 search: Search<'_>,
10923 tpl_factors: &Option<Vec<f64>>,
10924 sb_q: Option<&Vec<u8>>,
10925 sb_cols: usize,
10926 tpl_cells_x: usize,
10927 base_q_idx: u8,
10928 // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
10929 dq_res: i32,
10930 reference: &Picture,
10931 // The `LAST` + extra-reference pairs offered at this root; only the
10932 // reference and its picture are read here, since each HALF derives its
10933 // own compound stack at its own rectangular window.
10934 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10935 horz: bool,
10936 fctx: &crate::decode::FrameCtx,
10937) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10938 const SIDE: usize = SUPERBLOCK * 2;
10939 const SIDE_MI: usize = SIDE / 4;
10940 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10941 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10942 if root_r * 2 + 3 >= rows
10943 || root_c * 2 + 3 >= cols
10944 || (mi_row + SIDE_MI) as u32 > mi_rows
10945 || (mi_col + SIDE_MI) as u32 > mi_cols
10946 || x128 + SIDE > luma.true_width
10947 || y128 + SIDE > luma.true_height
10948 {
10949 return None;
10950 }
10951 // The root's own lambda, the mean of its four superblocks' -- the same
10952 // one [`search_root_128`] prices with, so the three root candidates and
10953 // the four-superblock arm are all comparable.
10954 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10955 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10956 (None, Some(f)) => {
10957 let mean = (0..16)
10958 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10959 .sum::<f64>()
10960 / 16.0;
10961 search.lambda * mean
10962 }
10963 (None, None) => search.lambda,
10964 };
10965 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10966 .iter()
10967 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10968 .sum::<f64>()
10969 / 4.0;
10970 let root_search = Search {
10971 lambda,
10972 ..match sb_q {
10973 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10974 None => search,
10975 }
10976 };
10977 let (w, h) = if horz {
10978 (SIDE, SUPERBLOCK)
10979 } else {
10980 (SUPERBLOCK, SIDE)
10981 };
10982 let (w_mi, h_mi) = (w / 4, h / 4);
10983 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10984 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10985 let mut cost = 0.0f64;
10986 let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
10987 for i in 0..2usize {
10988 let (mr, mc) = if horz {
10989 (mi_row + i * 16, mi_col)
10990 } else {
10991 (mi_row, mi_col + i * 16)
10992 };
10993 let stack = find_mv_stack(
10994 grid,
10995 mr,
10996 mc,
10997 w_mi,
10998 h_mi,
10999 LAST_FRAME,
11000 mi_cols as usize,
11001 mi_rows as usize,
11002 );
11003 let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
11004 .iter()
11005 .map(|&(r, pic, _)| {
11006 (
11007 r,
11008 pic,
11009 crate::mvstack::find_mv_stack_compound(
11010 grid,
11011 mr,
11012 mc,
11013 w_mi,
11014 h_mi,
11015 (LAST_FRAME, r),
11016 mi_cols as usize,
11017 mi_rows as usize,
11018 grid.sign_bias_table(),
11019 &[(0, 0); 7],
11020 None,
11021 ),
11022 )
11023 })
11024 .collect();
11025 let found = search_skip_64(
11026 luma,
11027 chroma,
11028 (mc * 4, mr * 4),
11029 (w, h),
11030 &root_search,
11031 false,
11032 reference,
11033 &stack,
11034 &half_compound,
11035 fctx,
11036 );
11037 match found {
11038 Some((mut c, mut block)) => {
11039 // lane-rectres: the same prediction with a REAL residual,
11040 // priced against the skip arm the search just committed to
11041 // the planes -- two 64x64 mu chunks for a half.
11042 if rectres() && block.skip {
11043 c = search_rect_residual(
11044 luma,
11045 chroma,
11046 (mc * 4, mr * 4),
11047 (w, h),
11048 c,
11049 root_search.lambda,
11050 &root_search,
11051 &stack,
11052 &mut block,
11053 );
11054 }
11055 cost += c;
11056 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
11057 halves.push(block);
11058 }
11059 None => {
11060 restore(luma, chroma, (x128, y128), SIDE, &base);
11061 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11062 return None;
11063 }
11064 }
11065 }
11066 let after = snapshot(luma, chroma, (x128, y128), SIDE);
11067 restore(luma, chroma, (x128, y128), SIDE, &base);
11068 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11069 let symbol = if horz { 1 } else { 2 };
11070 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
11071 // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
11072 // codes the delta_q group whether it is skipped or not
11073 // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
11074 // half is at a non-origin mi and codes none.
11075 let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
11076 Some((
11077 cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
11078 lambda,
11079 [b0, b1],
11080 after,
11081 ))
11082}
11083
11084/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
11085/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
11086/// decoder's own). Each piece is priced through the same `search_skip_64`
11087/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
11088/// into `grid` before the next is searched -- the writer publishes it too, so
11089/// a later piece searched against a stale grid would be priced (and its mv
11090/// predicted) off a stack the decoder never derives (class
11091/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
11092/// are put back before returning; the caller re-applies the winner.
11093///
11094/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
11095/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
11096/// libaom's own AB shapes earn their keep.
11097///
11098/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
11099/// already carrying the root's own partition symbol so it ranks against the
11100/// other root candidates and against the four superblocks below.
11101#[allow(clippy::too_many_arguments)]
11102fn search_root_128_ab(
11103 luma: &mut Plane,
11104 chroma: &mut [Plane; 2],
11105 grid: &mut crate::mvstack::MiGrid,
11106 (root_r, root_c): (usize, usize),
11107 (rows, cols): (usize, usize),
11108 (mi_cols, mi_rows): (u32, u32),
11109 search: Search<'_>,
11110 tpl_factors: &Option<Vec<f64>>,
11111 sb_q: Option<&Vec<u8>>,
11112 sb_cols: usize,
11113 tpl_cells_x: usize,
11114 base_q_idx: u8,
11115 reference: &Picture,
11116 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11117 // The partition symbol, 4..=7.
11118 symbol: usize,
11119 fctx: &crate::decode::FrameCtx,
11120) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
11121 const SIDE: usize = SUPERBLOCK * 2;
11122 const SIDE_MI: usize = SIDE / 4;
11123 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
11124 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
11125 if root_r * 2 + 3 >= rows
11126 || root_c * 2 + 3 >= cols
11127 || (mi_row + SIDE_MI) as u32 > mi_rows
11128 || (mi_col + SIDE_MI) as u32 > mi_cols
11129 || x128 + SIDE > luma.true_width
11130 || y128 + SIDE > luma.true_height
11131 {
11132 return None;
11133 }
11134 // The root's own lambda, the mean of its four superblocks' -- the same one
11135 // [`search_root_128`] prices with, so every root candidate and the
11136 // four-superblock arm are comparable.
11137 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
11138 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
11139 (None, Some(f)) => {
11140 let mean = (0..16)
11141 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
11142 .sum::<f64>()
11143 / 16.0;
11144 search.lambda * mean
11145 }
11146 (None, None) => search.lambda,
11147 };
11148 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
11149 .iter()
11150 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
11151 .sum::<f64>()
11152 / 4.0;
11153 let root_search = Search {
11154 lambda,
11155 ..match sb_q {
11156 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
11157 None => search,
11158 }
11159 };
11160 let base = snapshot(luma, chroma, (x128, y128), SIDE);
11161 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
11162 let mut cost = 0.0f64;
11163 let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
11164 for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
11165 let (w_mi, h_mi) = (w / 4, h / 4);
11166 let stack = find_mv_stack(
11167 grid,
11168 mr,
11169 mc,
11170 w_mi,
11171 h_mi,
11172 LAST_FRAME,
11173 mi_cols as usize,
11174 mi_rows as usize,
11175 );
11176 let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
11177 .iter()
11178 .map(|&(r, pic, _)| {
11179 (
11180 r,
11181 pic,
11182 crate::mvstack::find_mv_stack_compound(
11183 grid,
11184 mr,
11185 mc,
11186 w_mi,
11187 h_mi,
11188 (LAST_FRAME, r),
11189 mi_cols as usize,
11190 mi_rows as usize,
11191 grid.sign_bias_table(),
11192 &[(0, 0); 7],
11193 None,
11194 ),
11195 )
11196 })
11197 .collect();
11198 let found = search_skip_64(
11199 luma,
11200 chroma,
11201 (mc * 4, mr * 4),
11202 (w, h),
11203 &root_search,
11204 false,
11205 reference,
11206 &stack,
11207 &piece_compound,
11208 fctx,
11209 );
11210 match found {
11211 Some((mut c, mut block)) => {
11212 // lane-rectres: the same prediction with a REAL residual,
11213 // priced against the skip arm the search just committed to
11214 // the planes -- one mu chunk for a 64x64 square, two for a
11215 // half. The 64x64 squares are where libaom's own AB shapes
11216 // earn their keep.
11217 if rectres() && block.skip {
11218 c = search_rect_residual(
11219 luma,
11220 chroma,
11221 (mc * 4, mr * 4),
11222 (w, h),
11223 c,
11224 root_search.lambda,
11225 &root_search,
11226 &stack,
11227 &mut block,
11228 );
11229 }
11230 cost += c;
11231 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
11232 pieces.push(block);
11233 }
11234 None => {
11235 restore(luma, chroma, (x128, y128), SIDE, &base);
11236 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11237 return None;
11238 }
11239 }
11240 }
11241 let after = snapshot(luma, chroma, (x128, y128), SIDE);
11242 restore(luma, chroma, (x128, y128), SIDE, &base);
11243 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11244 let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
11245 Some((
11246 cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
11247 lambda,
11248 [b0, b1, b2],
11249 after,
11250 ))
11251}
11252
11253/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
11254/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
11255/// SKIP, priced through the same `symbol_bits` path every other candidate
11256/// uses. The winner's prediction is committed to the planes (it IS the
11257/// reconstruction -- a skip block has no residual); the caller restores them
11258/// if the four quadrants come out cheaper.
11259///
11260/// `None` when no candidate could be coded at all (a `NEWMV` residual the
11261/// writer cannot name is simply not offered, and the other modes always are,
11262/// so this only happens if every candidate is refused).
11263fn search_skip_64(
11264 luma: &mut Plane,
11265 chroma: &mut [Plane; 2],
11266 (x, y): (usize, usize),
11267 // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
11268 // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
11269 // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
11270 // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
11271 // side (one square when it is square, two otherwise), and the residual
11272 // arm is only ever asked for at 64 -- a 128 block's residual is four
11273 // TX_64X64 units the writer has no path for.
11274 (bw, bh): (usize, usize),
11275 search: &Search,
11276 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
11277 // screen content -- see that function's doc).
11278 residual: bool,
11279 reference: &Picture,
11280 stack: &MvStack,
11281 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
11282 // superblock's 16x16-mi window, built off the same grid the tile writer
11283 // rebuilds it from (empty unless the frame carries `reference_select`).
11284 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11285 fctx: &crate::decode::FrameCtx,
11286) -> Option<(f64, BlockCoeffs)> {
11287 debug_assert!(
11288 (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
11289 "only a 64 root has a residual arm"
11290 );
11291 // The square units every trial below is taken on: the block itself when
11292 // it is square, its two halves otherwise. Luma first (in raster order),
11293 // then each chroma plane over the same tiling at half the side -- which is
11294 // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
11295 let sq = bw.min(bh);
11296 let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
11297 .flat_map(|plane| {
11298 let (ox, oy, s) = if plane == 0 {
11299 (x, y, sq)
11300 } else {
11301 (x / 2, y / 2, sq / 2)
11302 };
11303 (0..bh / sq).flat_map(move |j| {
11304 (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
11305 })
11306 })
11307 .collect();
11308 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11309 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11310 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11311 // What every candidate pays whatever its vector: `skip` coded 1, then
11312 // `is_inter` coded 1, then the LAST chain above.
11313 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
11314 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
11315 ref1: None,
11316 mv1: (0, 0),
11317 ref_frame: crate::mvstack::LAST_FRAME,
11318 mode,
11319 mv,
11320 ref_mv_idx,
11321 };
11322 let mut cands: Vec<(f64, InterInfo)> = vec![
11323 (
11324 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11325 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
11326 ),
11327 (
11328 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11329 info_of(InterMode::GlobalMv, (0, 0), 0),
11330 ),
11331 ];
11332 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11333 for idx in 1..=2usize {
11334 if let Some(e) = stack.entries.get(idx) {
11335 cands.push((
11336 near_bits + drl_bits_for(stack, 1, idx),
11337 info_of(InterMode::NearMv, e.mv, idx as u8),
11338 ));
11339 }
11340 }
11341 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
11342 // candidate below to pair with the second reference's NEAREST half.
11343 let mut last_new_mv: Option<(i32, i32)> = None;
11344 if leaf_new_mv() {
11345 let source_block = luma.source_block_rect(x, y, bw, bh);
11346 let (seeds, seed_n) = mv_seeds(stack);
11347 let found = motion::search(
11348 &reference.y,
11349 reference.width,
11350 luma.true_width,
11351 luma.true_height,
11352 &source_block,
11353 x,
11354 y,
11355 bw,
11356 bh,
11357 stack.pred_mv,
11358 &seeds[..seed_n],
11359 search.lambda,
11360 fctx,
11361 1,
11362 );
11363 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
11364 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
11365 last_new_mv = Some(mv);
11366 cands.push((
11367 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
11368 info_of(InterMode::NewMv, mv, ref_mv_idx),
11369 ));
11370 }
11371 }
11372
11373 let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
11374 for (bits, info) in cands {
11375 let trials: Vec<Trial> = units
11376 .iter()
11377 .map(|&(plane, px, py, s, is_luma)| {
11378 let (samples, stride, w, h) = match plane {
11379 0 => (
11380 &reference.y,
11381 reference.width,
11382 luma.true_width,
11383 luma.true_height,
11384 ),
11385 1 => (
11386 &reference.u,
11387 reference.width / 2,
11388 chroma[0].true_width,
11389 chroma[0].true_height,
11390 ),
11391 _ => (
11392 &reference.v,
11393 reference.width / 2,
11394 chroma[1].true_width,
11395 chroma[1].true_height,
11396 ),
11397 };
11398 let prediction =
11399 predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
11400 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
11401 // `skip` true: the trial is the prediction itself plus its SSE,
11402 // so no transform of any size is involved (the reason a 64x64
11403 // root can be coded at all before a forward TX_64X64 exists).
11404 target.code_from_prediction(
11405 px,
11406 py,
11407 s,
11408 &prediction,
11409 true,
11410 search.base_q_idx,
11411 search.deadzone,
11412 TxbSet::Luma32Inter,
11413 )
11414 })
11415 .collect();
11416 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
11417 if best.as_ref().is_none_or(|b| cost < b.0) {
11418 best = Some((cost, fixed + bits, info, trials));
11419 }
11420 }
11421
11422 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
11423 // superblock can form without a second motion search ([`b64_compound`]),
11424 // priced through the same `symbol_bits` path -- `fixed` minus the single
11425 // reference's tree, plus the pair tree and the compound mode.
11426 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
11427 let (ref1, g) = (*ref1, *g);
11428 // The whole `comp_mode` + reference-pair tree at the writer's own
11429 // contexts, for THIS pair (lane-ctx).
11430 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
11431 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
11432 let mode_bits_of =
11433 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
11434 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
11435 ref1: Some(ref1),
11436 mv1: mvs.1,
11437 ref_frame: crate::mvstack::LAST_FRAME,
11438 mode,
11439 mv: mvs.0,
11440 ref_mv_idx: 0,
11441 };
11442 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
11443 (
11444 cstack.nearest_mv,
11445 mode_bits_of(0),
11446 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
11447 ),
11448 (
11449 ((0, 0), (0, 0)),
11450 mode_bits_of(6),
11451 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
11452 ),
11453 ];
11454 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
11455 // above, its residual priced against compound stack entry 0 -- what
11456 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
11457 let cbase = cstack
11458 .entries
11459 .first()
11460 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
11461 if let Some(new_mv) = last_new_mv
11462 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
11463 {
11464 let mvs = (new_mv, cstack.nearest_mv.1);
11465 ccands.push((
11466 mvs,
11467 mode_bits_of(3) + b0,
11468 compound_info(InterMode::NewNearestMv, mvs),
11469 ));
11470 }
11471 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
11472 ccands.dedup_by_key(|c| c.0);
11473 for (mvs, bits, info) in ccands {
11474 let trials: Vec<Trial> = units
11475 .iter()
11476 .map(|&(plane, px, py, s, is_luma)| {
11477 let (r0, r1) = match plane {
11478 0 => (
11479 (
11480 reference.y.as_slice(),
11481 reference.width,
11482 luma.true_width,
11483 luma.true_height,
11484 ),
11485 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11486 ),
11487 1 => (
11488 (
11489 reference.u.as_slice(),
11490 reference.width / 2,
11491 chroma[0].true_width,
11492 chroma[0].true_height,
11493 ),
11494 (
11495 g.u.as_slice(),
11496 g.width / 2,
11497 chroma[0].true_width,
11498 chroma[0].true_height,
11499 ),
11500 ),
11501 _ => (
11502 (
11503 reference.v.as_slice(),
11504 reference.width / 2,
11505 chroma[1].true_width,
11506 chroma[1].true_height,
11507 ),
11508 (
11509 g.v.as_slice(),
11510 g.width / 2,
11511 chroma[1].true_width,
11512 chroma[1].true_height,
11513 ),
11514 ),
11515 };
11516 let prediction = predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
11517 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
11518 target.code_from_prediction(
11519 px,
11520 py,
11521 s,
11522 &prediction,
11523 true,
11524 search.base_q_idx,
11525 search.deadzone,
11526 TxbSet::Luma32Inter,
11527 )
11528 })
11529 .collect();
11530 let syntax = fixed - ref_bits + bits;
11531 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
11532 if best.as_ref().is_none_or(|b| cost < b.0) {
11533 best = Some((cost, syntax, info, trials));
11534 }
11535 }
11536 }
11537
11538 let (skip_cost, syntax, info, skip_trials) = best?;
11539
11540 // The winner's prediction coded with a REAL residual (lane-tx64): one
11541 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
11542 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
11543 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
11544 // the skip arm already chose is re-coded: the prediction with the lowest
11545 // SSE is also the cheapest residual to code, and a second 64x64 motion
11546 // search per superblock is the wall this root was taken to SAVE.
11547 //
11548 // Priced against the skip arm through the same `symbol_bits` path, so the
11549 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
11550 // arm charges 0 instead and adds its three planes' coefficient bits.
11551 let mut chosen = (skip_cost, true, skip_trials);
11552 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
11553 // into the plane, so the tail below does not commit over its units.
11554 let mut luma_committed = false;
11555 // The residual arm's luma levels and the `txfm_split` depth the writer
11556 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
11557 // four TX_32X32 units in 64x64 ones.
11558 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
11559 if residual {
11560 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
11561 // Square by construction (the `debug_assert` above), so `units` is
11562 // one entry per plane and `chosen.2[plane]` is that plane's trial.
11563 let residual_trials = [0usize, 1, 2].map(|plane| {
11564 let (target, px, py, s) = if plane == 0 {
11565 (&*luma, x, y, bw)
11566 } else {
11567 (&chroma[plane - 1], x / 2, y / 2, bw / 2)
11568 };
11569 target.code_from_prediction(
11570 px,
11571 py,
11572 s,
11573 &chosen.2[plane].reconstruction,
11574 false,
11575 search.base_q_idx,
11576 search.deadzone,
11577 sets[plane],
11578 )
11579 });
11580 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
11581 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
11582 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
11583 // four TX_32X32 units of `txfm_split = 1`, taken by the same
11584 // `commit_inter_luma` every other inter block's is (it commits the
11585 // winner and hands back the cost it took off the flat arm).
11586 let (levels, depth, gain, tx_types) = if b64_var_tx() {
11587 let second = info.ref1.and_then(|r1| {
11588 compound
11589 .iter()
11590 .find(|(r, _, _)| *r == r1)
11591 .map(|&(_, g, _)| {
11592 (
11593 info.mv1,
11594 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11595 )
11596 })
11597 });
11598 luma_committed = true;
11599 commit_inter_luma(
11600 luma,
11601 (x, y),
11602 bw,
11603 info.mv,
11604 (
11605 &reference.y,
11606 reference.width,
11607 luma.true_width,
11608 luma.true_height,
11609 ),
11610 search,
11611 &residual_trials[0],
11612 false,
11613 second,
11614 fctx,
11615 )
11616 } else {
11617 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
11618 };
11619 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
11620 + search.lambda * (syntax + unskip + coeff_bits)
11621 + gain;
11622 if cost < skip_cost {
11623 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11624 if depth == 1 {
11625 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11626 }
11627 luma_levels = Some((levels, depth, tx_types));
11628 chosen = (cost, false, residual_trials.to_vec());
11629 }
11630 }
11631
11632 let (cost, skip, trials) = chosen;
11633 // `commit_inter_luma` already wrote the residual arm's luma (its four
11634 // split units are not one 64-sided trial); a skip winner overwrites it.
11635 for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
11636 match plane {
11637 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
11638 0 => {}
11639 _ => chroma[plane - 1].commit(px, py, s, trial),
11640 }
11641 }
11642 Some((
11643 cost,
11644 BlockCoeffs {
11645 skip,
11646 inter: Some(info),
11647 // The chroma grids are whole TX_32X32; the luma one is the
11648 // 64-point transform's coded 32x32 corner at depth 0 and the
11649 // whole 64-sided block at depth 1 (lane-b64b).
11650 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
11651 luma_tx_types: match (skip, &luma_levels) {
11652 (false, Some((_, _, types))) => types.clone(),
11653 _ => Vec::new(),
11654 },
11655 luma: match (skip, &luma_levels) {
11656 (true, _) => Vec::new(),
11657 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
11658 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
11659 (false, None) => coeffs(&trials[0].levels, BLOCK),
11660 },
11661 u: if skip {
11662 Vec::new()
11663 } else {
11664 coeffs(&trials[1].levels, bw / 2)
11665 },
11666 v: if skip {
11667 Vec::new()
11668 } else {
11669 coeffs(&trials[2].levels, bw / 2)
11670 },
11671 ..BlockCoeffs::default()
11672 },
11673 ))
11674}
11675
11676fn search_inter_block(
11677 luma: &mut Plane,
11678 chroma: &mut [Plane; 2],
11679 (x, y): (usize, usize),
11680 search: &Search,
11681 mode_bits: &[f64; 13],
11682 reference: &Picture,
11683 stack: &MvStack,
11684 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
11685 // for the whole GOP, with the stack this block derives against it. Only
11686 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
11687 // second motion search would double the wall of the stage that already
11688 // owns most of it.
11689 extra: &[(i8, &Picture, &MvStack)],
11690 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
11691 // the caller off the same MI grid the tile writer will (empty unless the
11692 // frame carries `reference_select`).
11693 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11694 // lane-av1obmc: the mi grid this search's neighbours were published into
11695 // (`record_mi`) and this block's own place in it -- what the OBMC
11696 // candidate's eligibility walk and neighbour plan read, the same state
11697 // the tile writer will read when it codes the `motion_mode` symbol.
11698 grid: &MiGrid,
11699 (mi_row, mi_col): (usize, usize),
11700 (mi_rows, mi_cols): (usize, usize),
11701 fctx: &crate::decode::FrameCtx,
11702) -> (BlockCoeffs, f64) {
11703 // `luma_set` is the INTRA candidates' table; the two inter candidates
11704 // below price their coefficients through `TxbSet::Luma32Inter`, which is
11705 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
11706 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
11707 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
11708 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
11709
11710 // skip / intra_inter symbol costs at a fixed context -- see this
11711 // function's doc comment.
11712 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
11713 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
11714
11715 struct Candidate {
11716 cost: f64,
11717 luma: Trial,
11718 u: Trial,
11719 v: Trial,
11720 mode: u8,
11721 skip: bool,
11722 inter: Option<InterInfo>,
11723 /// The mode/mv syntax this candidate pays for, apart from its
11724 /// residual -- what the OBMC candidate below has to re-pay when it
11725 /// re-prices the winner's prediction.
11726 mode_bits: f64,
11727 }
11728 let mut best: Option<Candidate> = None;
11729 let mut consider = |candidate: Candidate| {
11730 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
11731 best = Some(candidate);
11732 }
11733 };
11734
11735 // The chroma trial an intra candidate prices does not depend on `mode`
11736 // at all -- both planes always code `DC_PRED` here (a coding choice this
11737 // search inherited, not this loop's to second-guess) at the same `reach:
11738 // Reach::none()` -- so it is the same call with the same inputs on every
11739 // one of the thirteen iterations below; run it once and reuse the result
11740 // rather than repeat an already-priced transform/quantize/entropy call
11741 // twelve times for nothing (bit-identical: the value each iteration
11742 // reads back is exactly what it used to recompute).
11743 let u_trial = chroma[0].trial(
11744 At {
11745 x: x / 2,
11746 y: y / 2,
11747 side: BLOCK / 2,
11748 reach: Reach::none(),
11749 set: chroma_set,
11750 },
11751 DC_PRED,
11752 0,
11753 search.base_q_idx,
11754 search.deadzone,
11755 fctx,
11756 );
11757 let v_trial = chroma[1].trial(
11758 At {
11759 x: x / 2,
11760 y: y / 2,
11761 side: BLOCK / 2,
11762 reach: Reach::none(),
11763 set: chroma_set,
11764 },
11765 DC_PRED,
11766 0,
11767 search.base_q_idx,
11768 search.deadzone,
11769 fctx,
11770 );
11771
11772 let intra_modes: Vec<u8> = match search.top_k {
11773 Some(k) if k < search.modes.len() => {
11774 let scored = luma.intra_scores(
11775 At {
11776 x,
11777 y,
11778 side: BLOCK,
11779 reach,
11780 set: luma_set,
11781 },
11782 search.modes,
11783 mode_bits,
11784 search.lambda,
11785 fctx,
11786 );
11787 prune_by_sad(search.modes, scored, k)
11788 }
11789 _ => search.modes.to_vec(),
11790 };
11791 census_add(5, 1);
11792 census_add(
11793 6,
11794 if search.arf_leaf_intra {
11795 intra_modes.len()
11796 } else {
11797 0
11798 },
11799 );
11800 // lane-arfmode: arm 1 drops the whole-32 block's intra candidates at the
11801 // top ARF too -- the probe proved the ARF's intra AREA lives HERE, not at
11802 // the leaves (film A arm 1 vs control byte-identical with the leaf gate
11803 // alone), so "the 32x32 whole keeps intra as the scene-cut hatch" was a
11804 // hatch nothing else was using. Counted once per block.
11805 if search.arf_leaf_intra {
11806 for &mode in &intra_modes {
11807 let luma_trial = luma.trial(
11808 At {
11809 x,
11810 y,
11811 side: BLOCK,
11812 reach,
11813 set: luma_set,
11814 },
11815 mode,
11816 0,
11817 search.base_q_idx,
11818 search.deadzone,
11819 fctx,
11820 );
11821 let u = u_trial.clone();
11822 let v = v_trial.clone();
11823 let cost = luma_trial.sse
11824 + u.sse
11825 + v.sse
11826 + search.lambda
11827 * (luma_trial.bits
11828 + u.bits
11829 + v.bits
11830 + mode_bits[usize::from(mode)]
11831 + skip_bits(false)
11832 + intra_inter_bits(false));
11833 consider(Candidate {
11834 cost,
11835 luma: luma_trial,
11836 u,
11837 v,
11838 mode,
11839 skip: false,
11840 inter: None,
11841 mode_bits: mode_bits[usize::from(mode)],
11842 });
11843 }
11844 } else {
11845 arfmode_hit(0);
11846 }
11847
11848 // The reference frame buffer a spec decoder holds is exactly the true
11849 // (unpadded) coded extent -- a superblock whose partition stops early at
11850 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
11851 // beyond it, so those samples are never part of the decoded picture.
11852 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
11853 // reference sample position clamp), not to this crate's own
11854 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
11855 // here would let a fractional-pel read past the true edge pick up this
11856 // encoder's own uncoded padding instead of the true edge's replicated
11857 // value a decoder computes.
11858 let ref_luma = (
11859 &reference.y,
11860 reference.width,
11861 luma.true_width,
11862 luma.true_height,
11863 );
11864 let ref_u = (
11865 &reference.u,
11866 reference.width / 2,
11867 chroma[0].true_width,
11868 chroma[0].true_height,
11869 );
11870 let ref_v = (
11871 &reference.v,
11872 reference.width / 2,
11873 chroma[1].true_width,
11874 chroma[1].true_height,
11875 );
11876 // Every single-reference mode the writer can code (spec 5.11.24's symbol
11877 // chain, mirrored by `tile::write_inter_mode`), priced with the static
11878 // CDFs at this block's own stack contexts. A candidate is a motion
11879 // vector plus the cheapest syntax that reaches it, so two modes landing
11880 // on the same vector share one set of trials: the added modes cost
11881 // mode-bit arithmetic, not another motion compensation.
11882 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11883 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11884 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
11885 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
11886 // the loop cannot reach is never offered below -- every candidate's
11887 // index is one this same loop walks to.
11888 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
11889 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11890 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
11891 (
11892 stack.nearest_mv,
11893 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11894 InterInfo {
11895 ref1: None,
11896 mv1: (0, 0),
11897 ref_frame: crate::mvstack::LAST_FRAME,
11898 mode: InterMode::NearestMv,
11899 mv: stack.nearest_mv,
11900 ref_mv_idx: 0,
11901 },
11902 ),
11903 // GLOBALMV is the identity model's zero vector -- this encoder writes
11904 // no `gm_params` -- and the cheapest syntax of the four on the static
11905 // content where that vector is also the right one.
11906 (
11907 (0, 0),
11908 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11909 InterInfo {
11910 ref1: None,
11911 mv1: (0, 0),
11912 ref_frame: crate::mvstack::LAST_FRAME,
11913 mode: InterMode::GlobalMv,
11914 mv: (0, 0),
11915 ref_mv_idx: 0,
11916 },
11917 ),
11918 ];
11919 let near_bits =
11920 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11921 for idx in 1..=2usize {
11922 if let Some(e) = stack.entries.get(idx) {
11923 cands.push((
11924 e.mv,
11925 near_bits + drl_bits(1, idx),
11926 InterInfo {
11927 ref1: None,
11928 mv1: (0, 0),
11929 ref_frame: crate::mvstack::LAST_FRAME,
11930 mode: InterMode::NearMv,
11931 mv: e.mv,
11932 ref_mv_idx: idx as u8,
11933 },
11934 ));
11935 }
11936 }
11937
11938 let source_block = luma.source_block(x, y, BLOCK);
11939 let (seeds, seed_n) = mv_seeds(stack);
11940 #[cfg(test)]
11941 let t = stage_start();
11942 let found = motion::search(
11943 ref_luma.0,
11944 ref_luma.1,
11945 ref_luma.2,
11946 ref_luma.3,
11947 &source_block,
11948 x,
11949 y,
11950 BLOCK,
11951 BLOCK,
11952 stack.pred_mv,
11953 &seeds[..seed_n],
11954 search.lambda,
11955 fctx,
11956 1,
11957 );
11958 #[cfg(test)]
11959 stage_since(0, t);
11960 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
11961 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
11962 // costs, for the census below (`None` when the writer cannot name it).
11963 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
11964 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
11965 // the same vector costs a different residual from each: take the index
11966 // whose residual plus DRL bits is cheapest, not entry 0 by default.
11967 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
11968 newmv_syntax = Some((mv, bits));
11969 cands.push((
11970 mv,
11971 last_ref_bits
11972 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
11973 + bits
11974 + mv_rate_surcharge(bits),
11975 InterInfo {
11976 ref1: None,
11977 mv1: (0, 0),
11978 ref_frame: crate::mvstack::LAST_FRAME,
11979 mode: InterMode::NewMv,
11980 mv,
11981 ref_mv_idx,
11982 },
11983 ));
11984 }
11985
11986 // Each extra reference's own `NEWMV` vector, for the compound
11987 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
11988 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
11989 for &(ref_frame, g, gstack) in extra {
11990 let g_ref_bits = single_ref_bits(ref_frame, gstack);
11991 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
11992 cands.push((
11993 gstack.nearest_mv,
11994 g_ref_bits
11995 + g_not_new
11996 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
11997 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
11998 InterInfo {
11999 ref1: None,
12000 mv1: (0, 0),
12001 ref_frame,
12002 mode: InterMode::NearestMv,
12003 mv: gstack.nearest_mv,
12004 ref_mv_idx: 0,
12005 },
12006 ));
12007 cands.push((
12008 (0, 0),
12009 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
12010 InterInfo {
12011 ref1: None,
12012 mv1: (0, 0),
12013 ref_frame,
12014 mode: InterMode::GlobalMv,
12015 mv: (0, 0),
12016 ref_mv_idx: 0,
12017 },
12018 ));
12019 // A motion search of this reference's own: without it, GOLDEN/ALTREF
12020 // can only be coded at a vector some neighbour already found, which
12021 // is why they carried a third of the inter blocks at their two
12022 // search-free modes alone.
12023 // The search is skipped when this reference's own NEARESTMV already
12024 // prices out `margin` times better than LAST's best vector does --
12025 // one candidate evaluation (`motion::cost_at`) standing in for a
12026 // whole search of ~50.
12027 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
12028 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
12029 // neighbour already found, which is how GOLDEN/ALTREF were offered
12030 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
12031 // own value from the second motion search's wall.
12032 let searched =
12033 extra_ref_new_mv() && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
12034 let margin = extra_new_skip_margin();
12035 if searched {
12036 newmv_census_global(0);
12037 }
12038 let skip_search = searched
12039 && margin > 0.0
12040 && motion::cost_at(
12041 &g.y,
12042 g.width,
12043 luma.true_width,
12044 luma.true_height,
12045 &source_block,
12046 x,
12047 y,
12048 BLOCK,
12049 BLOCK,
12050 gstack.nearest_mv,
12051 gstack.pred_mv,
12052 search.lambda,
12053 fctx,
12054 ) * margin
12055 <= found.cost;
12056 if skip_search {
12057 newmv_census_global(1);
12058 }
12059 if searched && !skip_search {
12060 let (gseeds, gn) = mv_seeds(gstack);
12061 #[cfg(test)]
12062 let t = stage_start();
12063 let gfound = motion::search(
12064 &g.y,
12065 g.width,
12066 luma.true_width,
12067 luma.true_height,
12068 &source_block,
12069 x,
12070 y,
12071 BLOCK,
12072 BLOCK,
12073 gstack.pred_mv,
12074 &gseeds[..gn],
12075 search.lambda,
12076 fctx,
12077 ref_distance(ref_frame),
12078 );
12079 #[cfg(test)]
12080 stage_since(0, t);
12081 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
12082 extra_new_mvs.push((ref_frame, gmv));
12083 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
12084 cands.push((
12085 gmv,
12086 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
12087 InterInfo {
12088 ref1: None,
12089 mv1: (0, 0),
12090 ref_frame,
12091 mode: InterMode::NewMv,
12092 mv: gmv,
12093 ref_mv_idx,
12094 },
12095 ));
12096 }
12097 }
12098 }
12099
12100 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
12101 // trial set each: both references predict the block and the two
12102 // predictions are averaged, which is what pays on content where neither
12103 // reference alone is right. Priced with the same static-CDF approximation
12104 // the single-reference candidates use, plus the compound-only symbols
12105 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
12106 // The two compound-mode arms, each measured alone on the BD gate before
12107 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
12108 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
12109 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
12110 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
12111 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
12112 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
12113 // the keep rule. Still behind the knob.
12114 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
12115 let half_new = true;
12116 for (ref1, g, cstack) in compound {
12117 let (ref1, g) = (*ref1, *g);
12118 // The whole `comp_mode` + reference-pair tree at the writer's own
12119 // contexts, for THIS pair (lane-ctx).
12120 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
12121 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
12122 let mode_bits_of =
12123 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
12124 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
12125 (
12126 cstack.nearest_mv,
12127 mode_bits_of(0),
12128 InterInfo {
12129 ref_frame: crate::mvstack::LAST_FRAME,
12130 mode: InterMode::NearestNearestMv,
12131 mv: cstack.nearest_mv.0,
12132 mv1: cstack.nearest_mv.1,
12133 ref1: Some(ref1),
12134 ref_mv_idx: 0,
12135 },
12136 ),
12137 (
12138 ((0, 0), (0, 0)),
12139 mode_bits_of(6),
12140 InterInfo {
12141 ref_frame: crate::mvstack::LAST_FRAME,
12142 mode: InterMode::GlobalGlobalMv,
12143 mv: (0, 0),
12144 mv1: (0, 0),
12145 ref1: Some(ref1),
12146 ref_mv_idx: 0,
12147 },
12148 ),
12149 ];
12150 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
12151 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
12152 // the stack is deep enough for that walk to read one.
12153 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
12154 let drl = if cstack.entries.len() > 2 {
12155 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
12156 } else {
12157 0.0
12158 };
12159 ccands.push((
12160 (e.mv0, e.mv1),
12161 mode_bits_of(1) + drl,
12162 InterInfo {
12163 ref_frame: crate::mvstack::LAST_FRAME,
12164 mode: InterMode::NearNearMv,
12165 mv: e.mv0,
12166 mv1: e.mv1,
12167 ref1: Some(ref1),
12168 ref_mv_idx: 0,
12169 },
12170 ));
12171 }
12172 // The half-new modes and `NEW_NEWMV`, all seeded from the two
12173 // single-reference searches this block already ran -- no joint search
12174 // of its own. Every residual is priced against stack entry 0, which
12175 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
12176 let cbase = cstack
12177 .entries
12178 .first()
12179 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
12180 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
12181 ccands.push((
12182 (mv, cstack.nearest_mv.1),
12183 mode_bits_of(3) + b0,
12184 InterInfo {
12185 ref_frame: crate::mvstack::LAST_FRAME,
12186 mode: InterMode::NewNearestMv,
12187 mv,
12188 mv1: cstack.nearest_mv.1,
12189 ref1: Some(ref1),
12190 ref_mv_idx: 0,
12191 },
12192 ));
12193 }
12194 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
12195 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
12196 ccands.push((
12197 (cstack.nearest_mv.0, mv1),
12198 mode_bits_of(2) + b1,
12199 InterInfo {
12200 ref_frame: crate::mvstack::LAST_FRAME,
12201 mode: InterMode::NearestNewMv,
12202 mv: cstack.nearest_mv.0,
12203 mv1,
12204 ref1: Some(ref1),
12205 ref_mv_idx: 0,
12206 },
12207 ));
12208 }
12209 let base = cbase;
12210 if let (Some(b0), Some(b1)) =
12211 (mv_residual_bits(mv, base.0), mv_residual_bits(mv1, base.1))
12212 {
12213 ccands.push((
12214 (mv, mv1),
12215 mode_bits_of(7) + b0 + b1,
12216 InterInfo {
12217 ref_frame: crate::mvstack::LAST_FRAME,
12218 mode: InterMode::NewNewMv,
12219 mv,
12220 mv1,
12221 ref1: Some(ref1),
12222 ref_mv_idx: 0,
12223 },
12224 ));
12225 }
12226 }
12227 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
12228 ccands.dedup_by_key(|c| c.0);
12229 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
12230 let g_u = (
12231 g.u.as_slice(),
12232 g.width / 2,
12233 chroma[0].true_width,
12234 chroma[0].true_height,
12235 );
12236 let g_v = (
12237 g.v.as_slice(),
12238 g.width / 2,
12239 chroma[1].true_width,
12240 chroma[1].true_height,
12241 );
12242 for (mvs, bits, info) in ccands {
12243 let luma_trial = mc_trial_compound(
12244 luma,
12245 x,
12246 y,
12247 BLOCK,
12248 mvs,
12249 true,
12250 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12251 g_luma,
12252 search.base_q_idx,
12253 search.deadzone,
12254 TxbSet::Luma32Inter,
12255 fctx,
12256 );
12257 let u = mc_trial_compound(
12258 &chroma[0],
12259 x / 2,
12260 y / 2,
12261 BLOCK / 2,
12262 mvs,
12263 false,
12264 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12265 g_u,
12266 search.base_q_idx,
12267 search.deadzone,
12268 chroma_set,
12269 fctx,
12270 );
12271 let v = mc_trial_compound(
12272 &chroma[1],
12273 x / 2,
12274 y / 2,
12275 BLOCK / 2,
12276 mvs,
12277 false,
12278 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12279 g_v,
12280 search.base_q_idx,
12281 search.deadzone,
12282 chroma_set,
12283 fctx,
12284 );
12285 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12286 && u.levels.iter().all(|&l| l == 0)
12287 && v.levels.iter().all(|&l| l == 0);
12288 let cost = luma_trial.sse
12289 + u.sse
12290 + v.sse
12291 + search.lambda
12292 * (skip_bits(skip)
12293 + intra_inter_bits(true)
12294 + bits
12295 + if skip {
12296 0.0
12297 } else {
12298 luma_trial.bits + u.bits + v.bits
12299 });
12300 consider(Candidate {
12301 cost,
12302 luma: luma_trial,
12303 u,
12304 v,
12305 mode: DC_PRED,
12306 skip,
12307 mode_bits: bits,
12308 inter: Some(info),
12309 });
12310 }
12311 }
12312
12313 // One trial set per distinct (reference, vector) pair: sort, cheapest
12314 // syntax first, and drop the rest of each pair's run.
12315 cands.sort_by(|a, b| {
12316 (a.2.ref_frame, a.0)
12317 .cmp(&(b.2.ref_frame, b.0))
12318 .then(a.1.total_cmp(&b.1))
12319 });
12320 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
12321 census_add(7, cands.len());
12322 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
12323 // this block reaches WITHOUT it, taken inside the one loop that prices
12324 // them all (a second pricing pass would be a second oracle).
12325 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
12326 {
12327 for (mv, mode_bits_inter, info) in cands {
12328 let (ref_luma, ref_u, ref_v) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame)
12329 {
12330 Some(&(_, g, _)) => (
12331 (&g.y, g.width, luma.true_width, luma.true_height),
12332 (
12333 &g.u,
12334 g.width / 2,
12335 chroma[0].true_width,
12336 chroma[0].true_height,
12337 ),
12338 (
12339 &g.v,
12340 g.width / 2,
12341 chroma[1].true_width,
12342 chroma[1].true_height,
12343 ),
12344 ),
12345 None => (ref_luma, ref_u, ref_v),
12346 };
12347 let luma_trial = mc_trial(
12348 luma,
12349 x,
12350 y,
12351 BLOCK,
12352 mv,
12353 true,
12354 ref_luma.0,
12355 ref_luma.1,
12356 ref_luma.2,
12357 ref_luma.3,
12358 false,
12359 search.base_q_idx,
12360 search.deadzone,
12361 TxbSet::Luma32Inter,
12362 fctx,
12363 );
12364 let u = mc_trial(
12365 &chroma[0],
12366 x / 2,
12367 y / 2,
12368 BLOCK / 2,
12369 mv,
12370 false,
12371 ref_u.0,
12372 ref_u.1,
12373 ref_u.2,
12374 ref_u.3,
12375 false,
12376 search.base_q_idx,
12377 search.deadzone,
12378 chroma_set,
12379 fctx,
12380 );
12381 let v = mc_trial(
12382 &chroma[1],
12383 x / 2,
12384 y / 2,
12385 BLOCK / 2,
12386 mv,
12387 false,
12388 ref_v.0,
12389 ref_v.1,
12390 ref_v.2,
12391 ref_v.3,
12392 false,
12393 search.base_q_idx,
12394 search.deadzone,
12395 chroma_set,
12396 fctx,
12397 );
12398 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12399 && u.levels.iter().all(|&l| l == 0)
12400 && v.levels.iter().all(|&l| l == 0);
12401 let cost = luma_trial.sse
12402 + u.sse
12403 + v.sse
12404 + search.lambda
12405 * (skip_bits(skip)
12406 + intra_inter_bits(true)
12407 + mode_bits_inter
12408 + if skip {
12409 0.0
12410 } else {
12411 luma_trial.bits + u.bits + v.bits
12412 });
12413 consider(Candidate {
12414 cost,
12415 luma: luma_trial,
12416 u,
12417 v,
12418 mode: DC_PRED,
12419 skip,
12420 mode_bits: mode_bits_inter,
12421 inter: Some(info),
12422 });
12423 if newmv_census_on() {
12424 if info.mode == InterMode::NewMv
12425 && info.ref1.is_none()
12426 && info.ref_frame == crate::mvstack::LAST_FRAME
12427 {
12428 new_cost = cost;
12429 } else {
12430 other_cost = other_cost.min(cost);
12431 }
12432 }
12433 }
12434 }
12435 if let Some((new_mv, bits)) = newmv_syntax {
12436 newmv_census_block(
12437 BLOCK,
12438 true,
12439 new_cost,
12440 other_cost,
12441 new_mv,
12442 stack.nearest_mv,
12443 bits,
12444 );
12445 } else {
12446 newmv_census_block(
12447 BLOCK,
12448 false,
12449 f64::INFINITY,
12450 other_cost,
12451 mv,
12452 stack.nearest_mv,
12453 0.0,
12454 );
12455 }
12456
12457 let best = best.expect("the search offers at least the intra modes");
12458 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
12459 // offered to the SINGLE-REFERENCE winner only -- libaom's
12460 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
12461 // compound block, so the writer codes no symbol for one. The prediction
12462 // is built by the DECODER's own plan and blend
12463 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
12464 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
12465 // this search's `grid` already carries, so what is priced here is what a
12466 // decoder reconstructs -- never a second implementation of the blend.
12467 //
12468 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
12469 // on). Native crop BD, the standing recipe, with it on against the same
12470 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
12471 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
12472 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
12473 // one UP -- the keep rule wants two down and one flat, so it stays off.
12474 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
12475 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
12476 // things bound it and are the upgrade path: only the 32x32 winner is
12477 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
12478 // that is where libaom cashes most of its OBMC gain), and the symbol/
12479 // residual price here is the static-CDF estimate.
12480 let mut best = best;
12481 let mut motion_won = 0u8;
12482 if let Some(info) = best
12483 .inter
12484 .filter(|i| i.ref1.is_none() && (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on()))
12485 {
12486 let mut refs: [Option<&Picture>; 8] = [None; 8];
12487 refs[LAST_FRAME as usize] = Some(reference);
12488 for &(r, p, _) in extra {
12489 refs[r as usize] = Some(p);
12490 }
12491 // This block's OWN reference planes: the single-reference winner may
12492 // be one of the extra references, not LAST.
12493 let planes: [(&[u16], usize, usize, usize); 3] =
12494 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12495 Some(&(_, g, _)) => [
12496 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12497 (
12498 g.u.as_slice(),
12499 g.width / 2,
12500 chroma[0].true_width,
12501 chroma[0].true_height,
12502 ),
12503 (
12504 g.v.as_slice(),
12505 g.width / 2,
12506 chroma[1].true_width,
12507 chroma[1].true_height,
12508 ),
12509 ],
12510 None => [
12511 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12512 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12513 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12514 ],
12515 };
12516 // The alphabet `tile::write_motion_mode` will code this block's
12517 // symbol against, mirrored term for term (libaom
12518 // `motion_mode_allowed`).
12519 let warp_alphabet = warp_on()
12520 && crate::decode::num_proj_ref(
12521 grid,
12522 mi_row,
12523 mi_col,
12524 8,
12525 8,
12526 mi_cols,
12527 mi_rows,
12528 info.ref_frame,
12529 fctx,
12530 ) >= 1;
12531 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
12532 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
12533 if crate::envflags::env_flag!("EC_AV1_OBMC") {
12534 if let Some(pred) = obmc_prediction(
12535 grid,
12536 (mi_row, mi_col),
12537 (mi_rows, mi_cols),
12538 (x, y),
12539 BLOCK,
12540 info.mv,
12541 &refs,
12542 planes,
12543 reference.width,
12544 fctx,
12545 ) {
12546 candidates.push((1, pred));
12547 }
12548 }
12549 if warp_alphabet {
12550 if let Some(pred) = warp_prediction(
12551 grid,
12552 (mi_row, mi_col),
12553 (mi_rows, mi_cols),
12554 (x, y),
12555 BLOCK,
12556 info.mv,
12557 info.ref_frame,
12558 planes,
12559 fctx,
12560 ) {
12561 candidates.push((2, pred));
12562 }
12563 }
12564 for (motion, pred) in candidates {
12565 let luma_trial = luma.code_from_prediction(
12566 x,
12567 y,
12568 BLOCK,
12569 &pred[0],
12570 false,
12571 search.base_q_idx,
12572 search.deadzone,
12573 TxbSet::Luma32Inter,
12574 );
12575 let u = chroma[0].code_from_prediction(
12576 x / 2,
12577 y / 2,
12578 BLOCK / 2,
12579 &pred[1],
12580 false,
12581 search.base_q_idx,
12582 search.deadzone,
12583 chroma_set,
12584 );
12585 let v = chroma[1].code_from_prediction(
12586 x / 2,
12587 y / 2,
12588 BLOCK / 2,
12589 &pred[2],
12590 false,
12591 search.base_q_idx,
12592 search.deadzone,
12593 chroma_set,
12594 );
12595 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12596 && u.levels.iter().all(|&l| l == 0)
12597 && v.levels.iter().all(|&l| l == 0);
12598 let cost = luma_trial.sse
12599 + u.sse
12600 + v.sse
12601 + search.lambda
12602 * (skip_bits(skip)
12603 + intra_inter_bits(true)
12604 + best.mode_bits
12605 + mm(motion)
12606 + if skip {
12607 0.0
12608 } else {
12609 luma_trial.bits + u.bits + v.bits
12610 });
12611 if cost < best.cost + search.lambda * mm(motion_won) {
12612 motion_won = motion;
12613 best = Candidate {
12614 cost,
12615 luma: luma_trial,
12616 u,
12617 v,
12618 mode: DC_PRED,
12619 skip,
12620 mode_bits: best.mode_bits,
12621 inter: best.inter,
12622 };
12623 }
12624 }
12625 }
12626 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
12627 // default OFF): the four 16x16 units of `commit_inter_luma` against the
12628 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
12629 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
12630 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
12631 // it, and it is worse again on the deciding native table: film 1080p
12632 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
12633 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
12634 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
12635 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
12636 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
12637 // +28.4/+47.4/-4.0 -- the native table decides.)
12638 //
12639 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
12640 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
12641 // either, and the census names the row: the split units' own set
12642 // `Luma16Inter` is priced within 1.4% of what it is written at in every
12643 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
12644 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
12645 // so a perfect pricer would split even more, and more splitting is what
12646 // measured worse. The four extra txb_skip/eob symbols simply cost more
12647 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
12648 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
12649 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
12650 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
12651 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
12652 // plain translation, which is not the prediction it was priced from.
12653 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
12654 Some(info) => {
12655 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12656 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12657 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12658 };
12659 let second = info.ref1.and_then(|r| {
12660 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
12661 (
12662 info.mv1,
12663 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12664 )
12665 })
12666 });
12667 match info.ref1.is_some() && second.is_none() {
12668 true => {
12669 luma.commit(x, y, BLOCK, &best.luma);
12670 (best.luma.levels.clone(), 0, 0.0, Vec::new())
12671 }
12672 false => commit_inter_luma(
12673 luma,
12674 (x, y),
12675 BLOCK,
12676 info.mv,
12677 own,
12678 search,
12679 &best.luma,
12680 best.skip,
12681 second,
12682 fctx,
12683 ),
12684 }
12685 }
12686 None => {
12687 luma.commit(x, y, BLOCK, &best.luma);
12688 (best.luma.levels.clone(), 0, 0.0, Vec::new())
12689 }
12690 };
12691 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
12692 let [bu, bv] = match (
12693 best.inter.filter(|_| motion_won == 0),
12694 luma_tx_types.first().copied(),
12695 ) {
12696 (Some(info), Some(t)) => {
12697 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12698 Some(&(_, g, _)) => (
12699 (
12700 g.u.as_slice(),
12701 g.width / 2,
12702 chroma[0].true_width,
12703 chroma[0].true_height,
12704 ),
12705 (
12706 g.v.as_slice(),
12707 g.width / 2,
12708 chroma[1].true_width,
12709 chroma[1].true_height,
12710 ),
12711 ),
12712 None => (
12713 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12714 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12715 ),
12716 };
12717 let sec = info.ref1.and_then(|r| {
12718 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
12719 (
12720 info.mv1,
12721 [
12722 (
12723 g.u.as_slice(),
12724 g.width / 2,
12725 chroma[0].true_width,
12726 chroma[0].true_height,
12727 ),
12728 (
12729 g.v.as_slice(),
12730 g.width / 2,
12731 chroma[1].true_width,
12732 chroma[1].true_height,
12733 ),
12734 ],
12735 )
12736 })
12737 });
12738 recode_inter_chroma(
12739 chroma,
12740 (x, y),
12741 BLOCK,
12742 info.mv,
12743 [ou, ov],
12744 sec,
12745 search,
12746 chroma_set,
12747 t,
12748 fctx,
12749 )
12750 .unwrap_or([best.u, best.v])
12751 }
12752 _ => [best.u, best.v],
12753 };
12754 let best = Candidate {
12755 u: bu,
12756 v: bv,
12757 ..best
12758 };
12759 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
12760 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
12761 (
12762 BlockCoeffs {
12763 luma_tx_types,
12764 angle_delta_y: 0,
12765 cfl_alphas: None,
12766 filter_intra: None,
12767 luma: coeffs(&levels, BLOCK),
12768 u: coeffs(&best.u.levels, BLOCK / 2),
12769 v: coeffs(&best.v.levels, BLOCK / 2),
12770 mode: best.mode,
12771 uv_mode: DC_PRED,
12772 skip: best.skip,
12773 inter: best.inter,
12774 motion_mode: motion_won,
12775 eight: None,
12776 dv: None,
12777 palette: None,
12778 palette_uv: None,
12779 tx_depth,
12780 },
12781 best.cost + dcost,
12782 )
12783}
12784
12785/// lane-av1tpl: the strength `k` of the temporal lambda weighting
12786/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
12787/// is what every measurement before this lane was taken on. Swept by
12788/// `EC_AV1_TPL=<k>`.
12789///
12790/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
12791/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
12792/// baseline exactly, which is the control the rest of the table is read
12793/// against:
12794///
12795/// | k | film 1080p | film 2160p | screen |
12796/// |---|---|---|---|
12797/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
12798/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
12799/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
12800/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
12801/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
12802///
12803/// 0.5 is the only arm that is at least flat on every row and down on five of
12804/// the six columns, so it ships as the default. The lookahead pass that feeds
12805/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
12806const TPL_STRENGTH: f64 = 0.5;
12807
12808/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
12809/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
12810/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
12811/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
12812///
12813/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
12814/// nothing to vary the quantizer BY and codes no delta syntax at all.
12815fn deltaq_res_log2() -> Option<u8> {
12816 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
12817 u8::MAX => {}
12818 4 => return None,
12819 r => return Some(r),
12820 }
12821 match crate::envflags::var("EC_AV1_DELTAQ")
12822 .ok()
12823 .as_deref()
12824 .map(str::trim)
12825 {
12826 Some("0") => None,
12827 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
12828 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
12829 }
12830}
12831
12832/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
12833/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
12834/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
12835/// speed presets take, because the streams every other test pins move under
12836/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
12837static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
12838
12839/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
12840#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
12841pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
12842 DELTAQ_OVERRIDE.store(
12843 res_log2.unwrap_or(u8::MAX),
12844 std::sync::atomic::Ordering::Relaxed,
12845 );
12846}
12847
12848/// How much of the derived qindex step is actually taken
12849/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
12850fn deltaq_k() -> f64 {
12851 crate::envflags::var("EC_AV1_DELTAQ_K")
12852 .ok()
12853 .and_then(|v| v.trim().parse::<f64>().ok())
12854 .filter(|k| k.is_finite() && *k >= 0.0)
12855 .unwrap_or(1.0)
12856}
12857
12858/// The largest qindex the map may move a superblock by, either way
12859/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
12860/// deltaq around a quarter of the base qindex).
12861fn deltaq_clamp() -> i32 {
12862 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
12863 .ok()
12864 .and_then(|v| v.trim().parse::<i32>().ok())
12865 .filter(|c| (0..=63).contains(c))
12866 .unwrap_or(16)
12867}
12868
12869/// The qindex a lambda factor `f` asks for, derived rather than fitted.
12870///
12871/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
12872/// square of the quantizer step (`encode_inter_frame`'s own
12873/// `lambda = .. * step * step`), so the step this superblock wants is
12874/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
12875/// step ratio is inverted through the table itself -- the index whose `ac_q`
12876/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
12877/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
12878/// bounds it, and the answer is snapped onto the `res` grid so that every
12879/// superblock's qindex is congruent to `base` and the coded delta is a whole
12880/// number of steps.
12881fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
12882 let base_ac = f64::from(ac_q(8, i32::from(base)));
12883 let target = base_ac * f.max(1e-6).sqrt();
12884 let exact = (1..=255)
12885 .min_by(|&a, &b| {
12886 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
12887 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
12888 })
12889 .expect("the qindex range is not empty")
12890 - i32::from(base);
12891 let want = (exact as f64 * k).round() as i32;
12892 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
12893 // and need not be a whole number of steps, and clamping afterwards would
12894 // hand back a qindex that is not congruent to `base`.
12895 let max_steps = clamp / res;
12896 let steps = (want as f64 / f64::from(res)).round() as i32;
12897 let delta = steps.clamp(-max_steps, max_steps) * res;
12898 (i32::from(base) + delta).clamp(1, 255) as u8
12899}
12900
12901/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
12902/// objective would, from the SAME tpl dependence ratio our own map already
12903/// carries (`EC_AV1_DQ_TPL=1`).
12904///
12905/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
12906/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
12907/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
12908/// same expression at frame scope) by it, and asks
12909/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
12910/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
12911/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
12912/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
12913/// libaom reads `r0`. The offset is clamped to libaom's own
12914/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
12915/// twice the +-16 qindex [`deltaq_for_factor`] allows.
12916///
12917/// Two things differ from [`deltaq_for_factor`] and both are the point of the
12918/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
12919/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
12920/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
12921/// much stronger for the same map. `strength` scales the offset.
12922fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
12923 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
12924 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
12925 let exact = (1..=255)
12926 .min_by(|&a, &b| {
12927 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
12928 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
12929 })
12930 .expect("the qindex range is not empty")
12931 - i32::from(base);
12932 let want = exact as f64 * strength;
12933 // Snapped onto the `res` grid first, so the coded delta is a whole number
12934 // of steps, then bounded by libaom's own `res * 9 - 1`.
12935 let max_steps = (res * 9 - 1) / res;
12936 let steps = (want / f64::from(res)).round() as i32;
12937 let delta = steps.clamp(-max_steps, max_steps) * res;
12938 (i32::from(base) + delta).clamp(1, 255) as u8
12939}
12940
12941/// The frame-level `r0` libaom's objective divides by: the log-mean of
12942/// `1 + r` over the frame's cells, minus 1.
12943fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
12944 if ratio.is_empty() {
12945 return 0.0;
12946 }
12947 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
12948 m.exp() - 1.0
12949}
12950
12951/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
12952/// [`deltaq_for_factor`] derivation.
12953///
12954/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
12955/// the strength (default 1.0 = libaom's own offset when the flag armed it);
12956/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
12957fn dq_tpl_strength(level: DqLevel) -> Option<f64> {
12958 let m = dq_level_k()[level as usize];
12959 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
12960 .ok()
12961 .and_then(|v| v.trim().parse::<f64>().ok())
12962 .filter(|k| k.is_finite() && *k >= 0.0);
12963 let base = match crate::envflags::var("EC_AV1_DQ_TPL")
12964 .ok()
12965 .as_deref()
12966 .map(str::trim)
12967 {
12968 Some("0") => return None,
12969 Some(_) => Some(env_k.unwrap_or(1.0)),
12970 None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))),
12971 };
12972 base.map(|k| k * m).filter(|k| *k > 0.0)
12973}
12974
12975/// lane-arfq: which pyramid level the frame asking for a
12976/// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it
12977/// codes no `delta_q` syntax at all (the whole lever lives in
12978/// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the
12979/// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job.
12980#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12981pub(crate) enum DqLevel {
12982 /// The mini-GOP's own hidden `ALTREF`, which every other frame of the
12983 /// group predicts from (directly or through the mid level).
12984 TopArf = 0,
12985 /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it.
12986 MidArf = 1,
12987 /// A shown leaf -- and every frame of the flat, non-pyramid path.
12988 Leaf = 2,
12989}
12990
12991/// The per-level multiplier on the [`dq_tpl_strength`] the preset carries:
12992/// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else
12993/// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes
12994/// no `delta_q` (see [`DqLevel`]).
12995fn dq_level_k() -> [f64; 3] {
12996 dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref())
12997}
12998
12999/// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an
13000/// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry.
13001fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] {
13002 let mut k = crate::speed::DQ_LEVEL_K;
13003 if let Some(spec) = spec {
13004 for (slot, field) in k.iter_mut().zip(spec.split(':')) {
13005 if let Some(v) = field
13006 .trim()
13007 .parse::<f64>()
13008 .ok()
13009 .filter(|v: &f64| v.is_finite() && *v >= 0.0)
13010 {
13011 *slot = v;
13012 }
13013 }
13014 }
13015 k
13016}
13017
13018/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
13019/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
13020/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
13021/// the same tpl map -- and which of the two the frame actually coded.
13022fn dq_census() -> bool {
13023 crate::envflags::var("EC_AV1_DQ_CENSUS")
13024 .ok()
13025 .as_deref()
13026 .map(str::trim)
13027 == Some("1")
13028}
13029
13030/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
13031fn dq_summary(offsets: &[i32]) -> String {
13032 let n = offsets.len().max(1);
13033 let (lo, hi) = offsets
13034 .iter()
13035 .fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
13036 let nz = offsets.iter().filter(|&&o| o != 0).count();
13037 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
13038 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
13039 let mut levels: Vec<i32> = offsets.to_vec();
13040 levels.sort_unstable();
13041 levels.dedup();
13042 format!(
13043 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
13044 offsets.len(),
13045 levels.len()
13046 )
13047}
13048
13049/// How many DISTINCT per-superblock quantizer levels the last inter frame's
13050/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
13051/// (class `gate-blind-to-feature`: every exactness assert below passes on a
13052/// grid that is one flat value, i.e. on no delta_q at all). Process-global
13053/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
13054/// keeps the LARGEST count seen since the last read.
13055static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
13056
13057/// [`DELTAQ_LEVELS`], reset to 0.
13058#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
13059pub(crate) fn take_deltaq_levels() -> usize {
13060 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
13061}
13062
13063/// This superblock's search state: the quantizer it is coded at, and the
13064/// lambda that quantizer implies. RD lambda goes as the square of the step,
13065/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
13066/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
13067/// before lane-deltaq).
13068fn sb_q_search<'m>(
13069 sb_q: &[u8],
13070 sb_cols: usize,
13071 base_q_idx: u8,
13072 (sb_r, sb_c): (usize, usize),
13073 base: Search<'m>,
13074) -> Search<'m> {
13075 let q = sb_q[sb_r * sb_cols + sb_c];
13076 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
13077 Search {
13078 base_q_idx: q,
13079 lambda: base.lambda * ratio * ratio,
13080 ..base
13081 }
13082}
13083
13084fn tpl_strength() -> f64 {
13085 std::env::var("EC_AV1_TPL")
13086 .ok()
13087 .and_then(|v| v.parse::<f64>().ok())
13088 .filter(|k| k.is_finite() && *k >= 0.0)
13089 .unwrap_or(TPL_STRENGTH)
13090}
13091
13092/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
13093/// the frame being coded. 1 turns the weighting off; 2 is the shipped
13094/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
13095/// [`tpl_propagating`], which is the map that can actually use them and is
13096/// the default since lane-av1tpl3, so the default window is 8. Swept by
13097/// `EC_AV1_TPL_D=<d>`.
13098///
13099/// The streaming facade holds `depth - 1` pictures back so it feeds
13100/// `encode_inter_frame` the same window `encode_sequence` does; both read
13101/// THIS function, so the two paths cannot disagree about the window.
13102pub(crate) const TPL_DEPTH: usize = 8;
13103
13104/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
13105/// 0.5 is libaom's own square-root compression of its dependence ratio.
13106const TPL_POWER: f64 = 0.5;
13107
13108/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
13109/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
13110///
13111/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
13112/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
13113/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
13114///
13115/// | k | D | p | film 1080p | film 2160p | screen |
13116/// |---|---|---|---|---|---|
13117/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
13118/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
13119/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
13120/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
13121/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
13122/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
13123/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
13124/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
13125/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
13126/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
13127/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
13128/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
13129///
13130/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
13131/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
13132/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
13133/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
13134/// 0.1..0.4 UP on film 2160p, so it shipped off.
13135///
13136/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
13137/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
13138/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
13139/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
13140/// wherever the window leans on a flat bar, which is exactly where coding is
13141/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
13142/// (libaom's own granularity) puts a busy cell's denominator next to the flat
13143/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
13144/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
13145/// the same native gate (baseline = the shipped one-frame map):
13146///
13147/// | arm | film 1080p | film 2160p | screen |
13148/// |---|---|---|---|
13149/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
13150/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
13151/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
13152/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
13153/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
13154/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
13155/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
13156/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
13157/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
13158/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
13159///
13160/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
13161/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
13162/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
13163/// floor is a real effect on the ratio and never a win once the aggregation
13164/// is in -- the aggregation is the same fix, done where libaom does it.
13165fn tpl_propagating() -> bool {
13166 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
13167}
13168
13169pub(crate) fn tpl_depth() -> usize {
13170 std::env::var("EC_AV1_TPL_D")
13171 .ok()
13172 .and_then(|v| v.parse::<usize>().ok())
13173 .filter(|d| *d >= 1)
13174 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
13175 .max(1)
13176}
13177
13178/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
13179/// process, so the gate can price it against the encode it rides on.
13180static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
13181
13182/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
13183/// the winning displacement and its SAD.
13184///
13185/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
13186/// the left/above winners, first-best tie-break. Built once on the frame's
13187/// own thread and read-only afterwards, so it cannot make a tile's bytes
13188/// depend on the thread count.
13189fn tpl_coarse_pass(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<((i32, i32), u32)> {
13190 let (cells_x, cells_y) = (width / 16, height / 16);
13191 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
13192 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
13193 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
13194 return u32::MAX;
13195 }
13196 let (sx, sy) = (sx as usize, sy as usize);
13197 let mut sum = 0u32;
13198 for r in 0..16 {
13199 let a = &next[(by + r) * width + bx..][..16];
13200 let b = &cur[(sy + r) * width + sx..][..16];
13201 sum += a
13202 .iter()
13203 .zip(b)
13204 .map(|(&p, &q)| u32::from(p.abs_diff(q)))
13205 .sum::<u32>();
13206 }
13207 sum
13208 };
13209 let mut out = Vec::with_capacity(cells_x * cells_y);
13210 let mut above = vec![(0i32, 0i32); cells_x];
13211 for cy in 0..cells_y {
13212 let mut left = (0i32, 0i32);
13213 for cx in 0..cells_x {
13214 let (bx, by) = (cx * 16, cy * 16);
13215 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
13216 for cand in [left, above[cx]] {
13217 if cand != (0, 0) {
13218 let s = sad(bx, by, cand);
13219 if s < best.0 {
13220 best = (s, cand);
13221 }
13222 }
13223 }
13224 for step in [8i32, 4, 2, 1] {
13225 let centre = best.1;
13226 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
13227 let mv = (centre.0 + dx, centre.1 + dy);
13228 if mv.0.abs() > 32 || mv.1.abs() > 32 {
13229 continue;
13230 }
13231 let s = sad(bx, by, mv);
13232 if s < best.0 {
13233 best = (s, mv);
13234 }
13235 }
13236 }
13237 left = best.1;
13238 above[cx] = best.1;
13239 out.push((best.1, best.0));
13240 }
13241 }
13242 out
13243}
13244
13245/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
13246/// transform: here, the mean absolute deviation of the cell from its own DC.
13247/// It is the denominator every propagated cost is read against, so only its
13248/// SHAPE across the frame matters, not its scale.
13249fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
13250 let (cells_x, cells_y) = (width / 16, height / 16);
13251 let mut out = Vec::with_capacity(cells_x * cells_y);
13252 for cy in 0..cells_y {
13253 for cx in 0..cells_x {
13254 let (bx, by) = (cx * 16, cy * 16);
13255 let mut sum = 0u32;
13256 for r in 0..16 {
13257 sum += frame[(by + r) * width + bx..][..16]
13258 .iter()
13259 .map(|&p| u32::from(p))
13260 .sum::<u32>();
13261 }
13262 let dc = ((sum + 128) / 256) as u8;
13263 let mut cost = 0u32;
13264 for r in 0..16 {
13265 cost += frame[(by + r) * width + bx..][..16]
13266 .iter()
13267 .map(|&p| u32::from(p.abs_diff(dc)))
13268 .sum::<u32>();
13269 }
13270 out.push(cost);
13271 }
13272 }
13273 out
13274}
13275
13276/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
13277/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
13278/// splats its own area, at its winning displacement, onto the (at most four)
13279/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
13280fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
13281 let start = std::time::Instant::now();
13282 let (cells_x, cells_y) = (width / 16, height / 16);
13283 let pass = tpl_coarse_pass(cur, next, width, height);
13284 let mut area = vec![0.0f64; cells_x * cells_y];
13285 for cy in 0..cells_y {
13286 for cx in 0..cells_x {
13287 let (mv, _) = pass[cy * cells_x + cx];
13288 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
13289 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
13290 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
13291 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
13292 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
13293 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
13294 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
13295 }
13296 }
13297 }
13298 }
13299 TPL_NANOS.fetch_add(
13300 start.elapsed().as_nanos() as u64,
13301 std::sync::atomic::Ordering::Relaxed,
13302 );
13303 area
13304}
13305
13306/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
13307/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
13308/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
13309/// Decreasing in referenced-ness (a block the next frame leans on is coded
13310/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
13311/// total lambda scale is only redistributed, never moved -- a global move is
13312/// the thing lane-av1lambda already measured inert.
13313fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
13314 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
13315 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
13316 let mut out = Vec::with_capacity(sb_cols * sb_rows);
13317 for sr in 0..sb_rows {
13318 for sc in 0..sb_cols {
13319 let mut sum = 0.0;
13320 for r in 0..4 {
13321 for c in 0..4 {
13322 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
13323 }
13324 }
13325 let w_rel = sum / 16.0 / mean;
13326 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
13327 }
13328 }
13329 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
13330 let mut hist = [0usize; 8];
13331 for w in map {
13332 hist[((w / mean * 2.0) as usize).min(7)] += 1;
13333 }
13334 let (lo, hi) = out
13335 .iter()
13336 .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
13337 eprintln!(
13338 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
13339 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
13340 map.len(),
13341 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
13342 );
13343 }
13344 out
13345}
13346
13347/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
13348/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
13349/// much of the WHOLE lookahead window leans on that cell.
13350///
13351/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
13352/// coarse pass gives a displacement and an inter cost; a cell's own
13353/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
13354/// cell well saves the frames that predict from it -- and it is splatted,
13355/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
13356/// displacement lands on. Walking `f` from the far end of the window back to
13357/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
13358/// area map could not do at all.
13359///
13360/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
13361/// factor over the frame is exactly 1: a cell the window leans on is coded
13362/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
13363/// scale only moves around, never up or down -- a global move is what
13364/// lane-av1lambda already measured inert.
13365/// Returns the per-cell lambda factors AND the per-cell dependence ratio
13366/// `mc_dep / intra` they were derived from -- the second half is what
13367/// [`deltaq_libaom`] needs, since the factor alone has been through a
13368/// mean normalisation the raw ratio cannot be recovered across.
13369fn tpl_lambda_factors(
13370 frames: &[&[u8]],
13371 width: usize,
13372 height: usize,
13373 k: f64,
13374) -> (Vec<f64>, Vec<f64>) {
13375 let start = std::time::Instant::now();
13376 let (cells_x, cells_y) = (width / 16, height / 16);
13377 let cells = cells_x * cells_y;
13378 let levels = frames.len();
13379 let intra: Vec<Vec<u32>> = frames
13380 .iter()
13381 .map(|f| tpl_intra_costs(f, width, height))
13382 .collect();
13383 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
13384 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
13385 .collect();
13386 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
13387 for f in (1..levels).rev() {
13388 for cy in 0..cells_y {
13389 for cx in 0..cells_x {
13390 let ci = cy * cells_x + cx;
13391 let (mv, inter) = passes[f - 1][ci];
13392 let saved = f64::from(intra[f][ci].saturating_sub(inter));
13393 let propagate = saved + mc_dep[f][ci];
13394 if propagate <= 0.0 {
13395 continue;
13396 }
13397 // The 16x16 window of the PREVIOUS frame this cell predicted
13398 // from, spread over the cells it overlaps.
13399 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
13400 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
13401 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
13402 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
13403 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
13404 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
13405 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
13406 }
13407 }
13408 }
13409 }
13410 }
13411 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
13412 // tail (a nearly flat cell the window leans on has a tiny denominator),
13413 // and at p = 1 that tail slams into the clamp. libaom reads its own
13414 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
13415 // sweeps the exponent, 1 being the raw ratio.
13416 let power = std::env::var("EC_AV1_TPL_P")
13417 .ok()
13418 .and_then(|v| v.parse::<f64>().ok())
13419 .filter(|p| p.is_finite() && *p > 0.0)
13420 .unwrap_or(TPL_POWER);
13421 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
13422 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
13423 // `0` to take either back out); `FLOOR` defaults to off.
13424 //
13425 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
13426 // frame's own mean intra cost. A cell of flat content has a near-zero
13427 // MAD, so its ratio explodes exactly where coding is cheap.
13428 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
13429 // and mc_dep are summed over the 64x64 superblock first -- libaom's
13430 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
13431 // per-16x16 numbers), which is also what makes the ratio survive one
13432 // flat cell next to a busy one.
13433 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
13434 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
13435 // harder than the `p` exponent alone can.
13436 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
13437 .ok()
13438 .and_then(|v| v.parse::<f64>().ok())
13439 .filter(|f| f.is_finite() && *f >= 0.0)
13440 .unwrap_or(0.0);
13441 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
13442 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
13443 let intra_mean = intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
13444 let floor = floor_frac * intra_mean;
13445 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
13446 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
13447 // every cell under it. The edge groups are partial and summed as they are.
13448 let ratio: Vec<f64> = if sb_agg {
13449 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
13450 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
13451 for cy in 0..cells_y {
13452 for cx in 0..cells_x {
13453 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
13454 e.0 += mc_dep[0][cy * cells_x + cx];
13455 e.1 += denom(cy * cells_x + cx);
13456 }
13457 }
13458 (0..cells)
13459 .map(|c| {
13460 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
13461 dep / den.max(1.0)
13462 })
13463 .collect()
13464 } else {
13465 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
13466 };
13467 let mut out: Vec<f64> = ratio
13468 .iter()
13469 .map(|&r| {
13470 let r = if log_beta { (1.0 + r).log2() } else { r };
13471 (1.0 + k * r).powf(-power)
13472 })
13473 .collect();
13474 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
13475 for f in &mut out {
13476 *f = (*f / mean).clamp(0.25, 4.0);
13477 }
13478 TPL_NANOS.fetch_add(
13479 start.elapsed().as_nanos() as u64,
13480 std::sync::atomic::Ordering::Relaxed,
13481 );
13482 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
13483 let mut hist = [0usize; 8];
13484 for &f in &out {
13485 hist[((f * 4.0) as usize).min(7)] += 1;
13486 }
13487 let (lo, hi) = out
13488 .iter()
13489 .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
13490 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
13491 eprintln!(
13492 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
13493 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
13494 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
13495 );
13496 }
13497 (out, ratio)
13498}
13499
13500/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
13501/// references name, which slot it refreshes, whether it is shown when it is
13502/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
13503/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
13504/// 0/2 alternation, every frame shown, every reference in the past).
13505///
13506/// The sign bias is carried rather than derived here because only the caller
13507/// knows what order hint each slot holds; it is armed onto the tile writer
13508/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
13509/// the writer scans the same stacks the decoder will.
13510#[derive(Debug, Clone, Copy)]
13511pub(crate) struct PyramidFrame {
13512 /// The slot `LAST_FRAME` (and every reference this encoder does not name
13513 /// apart) reads.
13514 pub last_slot: u8,
13515 /// The single slot `refresh_frame_flags` sets.
13516 pub self_slot: u8,
13517 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
13518 /// pyramid, which is what makes `sign_bias`'s last entry true.
13519 pub altref_slot: u8,
13520 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
13521 /// picture (the leaf chain alternates its refresh between two slots, so
13522 /// the frame before `LAST` is still intact). `None` leaves
13523 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
13524 /// wrote before, and the caller then passes no `last2` picture either.
13525 pub last2_slot: Option<u8>,
13526 /// `show_frame`: false for a hidden frame, output later by a
13527 /// `show_existing_frame` header.
13528 pub show_frame: bool,
13529 /// lane-arfq: which level's `delta_q` strength this frame reads
13530 /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid
13531 /// one share `Level::Arf` and differ only by their q offset.
13532 pub dq_level: DqLevel,
13533 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
13534 pub sign_bias: crate::mvstack::SignBiasTable,
13535}
13536
13537/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
13538/// `temporal_filter` in the small: every 16x16 luma block of `src` is
13539/// motion-compensated from each picture of `window` (the group's own display
13540/// neighbours, nearest first) and averaged in with weight
13541/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
13542/// nothing and one that matches well cancels the grain the block's residual
13543/// would otherwise have to code.
13544///
13545/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
13546/// rides the luma block's own vector (halved), which is what libaom does at
13547/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
13548/// grid tiles it exactly.
13549///
13550/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
13551/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
13552/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
13553/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
13554/// quality the ARF is coded at, so the substitution itself costs little.
13555// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and
13556// `ARF_TF_WIN_FUT` future ones); this takes every picture in it.
13557pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
13558 const SIDE: usize = 16;
13559 let neighbours: Vec<&Picture> = window
13560 .iter()
13561 .filter(|p| p.width == src.width && p.height == src.height)
13562 .collect();
13563 if neighbours.is_empty() || strength <= 0.0 {
13564 return src.clone();
13565 }
13566 let mut out = src.clone();
13567 // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
13568 // `None` when the displaced block leaves the picture.
13569 let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
13570 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
13571 if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
13572 return None;
13573 }
13574 let (sy, sx) = (sy as usize, sx as usize);
13575 let mut acc = 0u64;
13576 for row in 0..SIDE {
13577 let c = &src.y[(by + row) * src.width + bx..][..SIDE];
13578 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
13579 acc += c
13580 .iter()
13581 .zip(p)
13582 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
13583 .sum::<u64>();
13584 }
13585 Some((acc, (sy, sx)))
13586 };
13587 // The log-step diamond `arf_pred_census` priced this with.
13588 let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
13589 let mut best = sad(r, bx, by, (0, 0))?;
13590 let mut centre = (0isize, 0isize);
13591 let mut step = 16isize;
13592 while step >= 1 {
13593 let from = centre;
13594 for (dy, dx) in [
13595 (-1, -1),
13596 (-1, 0),
13597 (-1, 1),
13598 (0, -1),
13599 (0, 1),
13600 (1, -1),
13601 (1, 0),
13602 (1, 1),
13603 ] {
13604 let mv = (from.0 + dy * step, from.1 + dx * step);
13605 if let Some(s) = sad(r, bx, by, mv) {
13606 if s.0 < best.0 {
13607 best = s;
13608 centre = mv;
13609 }
13610 }
13611 }
13612 step /= 2;
13613 }
13614 Some(best.1)
13615 };
13616 let (cw, ch) = (src.width / 2, src.height / 2);
13617 for by in (0..src.height).step_by(SIDE) {
13618 for bx in (0..src.width).step_by(SIDE) {
13619 if by + SIDE > src.height || bx + SIDE > src.width {
13620 continue;
13621 }
13622 let mut y_acc = vec![0f64; SIDE * SIDE];
13623 let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
13624 let mut wsum = 1.0f64;
13625 // Chroma keeps its OWN weight sum: an edge block whose halved
13626 // vector leaves the chroma plane contributes to luma only, and
13627 // dividing chroma by the luma sum would darken it (class
13628 // `metric blind to a plane`, on the encoder side).
13629 let mut cwsum = 1.0f64;
13630 for row in 0..SIDE {
13631 for col in 0..SIDE {
13632 y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
13633 }
13634 }
13635 for row in 0..SIDE / 2 {
13636 for col in 0..SIDE / 2 {
13637 let i = (by / 2 + row) * cw + bx / 2 + col;
13638 c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
13639 c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
13640 }
13641 }
13642 for r in &neighbours {
13643 let Some((sy, sx)) = search(r, bx, by) else {
13644 continue;
13645 };
13646 let mut sse = 0f64;
13647 for row in 0..SIDE {
13648 for col in 0..SIDE {
13649 let d = f64::from(src.y[(by + row) * src.width + bx + col])
13650 - f64::from(r.y[(sy + row) * r.width + sx + col]);
13651 sse += d * d;
13652 }
13653 }
13654 let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
13655 for row in 0..SIDE {
13656 for col in 0..SIDE {
13657 y_acc[row * SIDE + col] +=
13658 w * f64::from(r.y[(sy + row) * r.width + sx + col]);
13659 }
13660 }
13661 // Chroma reads the luma vector halved; a block on the picture
13662 // edge whose halved vector would leave the chroma plane is
13663 // left to luma alone rather than clamped to a different
13664 // displacement than the luma it must stay registered with.
13665 let (cy, cx) = (sy / 2, sx / 2);
13666 if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
13667 for row in 0..SIDE / 2 {
13668 for col in 0..SIDE / 2 {
13669 let i = (cy + row) * cw + cx + col;
13670 c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
13671 c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
13672 }
13673 }
13674 cwsum += w;
13675 }
13676 wsum += w;
13677 }
13678 for row in 0..SIDE {
13679 for col in 0..SIDE {
13680 out.y[(by + row) * src.width + bx + col] =
13681 (y_acc[row * SIDE + col] / wsum).round() as u16;
13682 }
13683 }
13684 for row in 0..SIDE / 2 {
13685 for col in 0..SIDE / 2 {
13686 let i = (by / 2 + row) * cw + bx / 2 + col;
13687 out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
13688 out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
13689 }
13690 }
13691 }
13692 }
13693 out
13694}
13695
13696/// Encodes one picture as an inter frame predicting from `reference`'s
13697/// reconstruction, which the caller decoded (or, for the frame right after
13698/// the key frame, is the key frame's own reconstruction).
13699pub(crate) fn encode_inter_frame(
13700 picture: &Picture,
13701 reference: &Picture,
13702 base_q_idx: u8,
13703 deadzone: f64,
13704 order_hint: u32,
13705 // The order hint each of the seven `ref_frame_idx` entries names, which a
13706 // decoder reads out of its own reference state -- only spec 5.9.22's
13707 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
13708 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
13709 // callers that follow this crate's own flat slot plan.
13710 order_hints: [u32; 7],
13711 render: (usize, usize),
13712 // The tables this frame's writer starts from: what the previous frame
13713 // stored into the slot this one's `primary_ref_frame` names. `None`
13714 // starts from the defaults, which is right only for the frame straight
13715 // after a key frame.
13716 start_cdfs: Option<&crate::cdf_state::Cdfs>,
13717 // The key frame's own (padded) reconstruction, which every frame of the
13718 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
13719 // with `LAST_FRAME` alone, exactly as before.
13720 golden: Option<&Picture>,
13721 // The frame two back, held in the slot this frame is about to refresh
13722 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
13723 // inter frames of a GOP, where the frame two back IS the key frame.
13724 altref: Option<&Picture>,
13725 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
13726 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
13727 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
13728 // take. `None` (every caller but the pyramid leaves) codes the frame
13729 // with the reference set unchanged.
13730 last2: Option<&Picture>,
13731 fctx: &crate::decode::FrameCtx,
13732 // Where this frame sits in the coding-order pyramid; `None` is the flat
13733 // one-shown-frame-per-picture stream this encoder wrote before.
13734 pyramid: Option<PyramidFrame>,
13735 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
13736 // them), padded like this one -- the lookahead window the per-block
13737 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
13738 // EMPTY slice codes the frame at one lambda, as before.
13739 lookahead: &[Picture],
13740) -> Result<Encoded> {
13741 picture.check()?;
13742 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
13743 return Err(Error::unsupported(
13744 "AV1 encode",
13745 "an inter frame is coded only for a picture that is a whole number \
13746 of 64x64 superblocks -- the inter tile writer never splits a \
13747 superblock's partition below that",
13748 ));
13749 }
13750 if reference.width != picture.width || reference.height != picture.height {
13751 return Err(Error::unsupported(
13752 "AV1 encode",
13753 "the reference picture must be the same size as the one being coded",
13754 ));
13755 }
13756
13757 // The single slot this crate's inter frames ever predict from or
13758 // refresh (`inter_frame_headers`'s contract): every frame both reads and
13759 // overwrites slot 0, so the frame just coded is always what the next one
13760 // predicts against.
13761 const LAST_SLOT: u8 = 0;
13762 // Slot 0 and slot 2 alternate so the frame two back survives one more
13763 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
13764 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
13765 // in the very slot it will overwrite.
13766 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
13767 let last_slot = pyramid.map_or(
13768 if order_hint <= 1 {
13769 LAST_SLOT
13770 } else if (order_hint - 1) % 2 == 1 {
13771 0
13772 } else {
13773 2
13774 },
13775 |p| p.last_slot,
13776 );
13777 // `render`, not `picture.width`/`picture.height`: `picture` here is
13778 // already padded to a whole number of superblocks (`encode_sequence`'s
13779 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
13780 // every true-edge clamp downstream) must come from the frame's real,
13781 // unpadded size, same as `key_frame_headers_colour` takes `render` and
13782 // not the padded picture in `encode_key_frame_inner`.
13783 let (seq, mut header) = inter_frame_headers_slots(
13784 render.0,
13785 render.1,
13786 base_q_idx,
13787 order_hint,
13788 last_slot,
13789 self_slot,
13790 match pyramid {
13791 Some(p) => p.altref_slot,
13792 None if altref.is_some() => self_slot,
13793 None => GOLDEN_SLOT,
13794 },
13795 )?;
13796 header.render_width = render.0 as u32;
13797 header.render_height = render.1 as u32;
13798 // lane-refs: this frame's motion-compensation kernel, written into the
13799 // header AND armed on the context every prediction reads, in one place so
13800 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
13801 // tile decodes to different pixels than the encoder scored).
13802 header.interpolation_filter = frame_interp_filter();
13803 fctx.interp_filter.set(mc::InterpFilterKind::from_header(
13804 header.interpolation_filter,
13805 ));
13806 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
13807 // The order hint behind each `ref_frame_idx` entry. The flat path's own
13808 // slot plan (`inter_frame_headers_slots`) is: every reference but
13809 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
13810 // `ALTREF_FRAME`, which reads the frame two back when there is one;
13811 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
13812 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
13813 header.order_hints = order_hints;
13814 // lane-last2: `inter_frame_headers_slots` points every un-named
13815 // reference at `last_slot`; the pyramid's leaf chain retains a second,
13816 // older picture and names it here. The caller's `sign_bias` /
13817 // `order_hints` entry 1 is derived from this same slot, so the stack
13818 // scans and `skipModeAllowed` read what the decoder will.
13819 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
13820 header.ref_frame_idx[1] = slot;
13821 }
13822 header.reference_select = reference_select();
13823 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
13824 // per-reference order-hint distance is read by the block SEARCH, which
13825 // runs long before the writer arms these (the distance-scaled search step
13826 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
13827 // never reached the tool).
13828 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
13829 // lane-hpmv: armed here for the same reason the order hints are -- the
13830 // block SEARCH reads it (its eighth-pel stage) long before the writer.
13831 let hp_mv = header.allow_high_precision_mv;
13832 crate::tile::arm_high_precision_mv(hp_mv);
13833 if let Some(p) = pyramid {
13834 header.show_frame = p.show_frame;
13835 header.showable_frame = !p.show_frame;
13836 header.ref_frame_sign_bias = p.sign_bias;
13837 }
13838 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
13839 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
13840 // block inside this frame codes and searches its own `tx_depth`, the same
13841 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
13842 let tx_select = tx_select() && tx_select_inter();
13843 if tx_select {
13844 header.tx_mode = TxMode::Select;
13845 }
13846
13847 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
13848 // lane-palw: the encoder's own in-process reconstruct reads its palette
13849 // colour-index maps back through `decode::palette_onscreen`, which takes
13850 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
13851 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
13852 // them here so the reconstruct clamps a block cut by the frame edge
13853 // exactly as the writer now does.
13854 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
13855 fctx.seg_mi_dims.set(frame_mi_dims);
13856 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
13857 // here (see `encode_key_frame_inner`).
13858 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
13859 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
13860 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
13861 // This frame's own `allow_screen_content_tools`. It can only be set when
13862 // the SEQUENCE offers the bit at all, which is the key frame's decision
13863 // ([`SEQ_SCREEN`]): a frame header that contradicts
13864 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
13865 // encode.
13866 let screen =
13867 seq_screen() && screen_content(&picture_y8, picture.width, true_width, true_height);
13868 header.allow_screen_content_tools = screen;
13869 // lane-txi, as on the key frame: the header bit the writer's own
13870 // `Cdfs` then reads for every luma `tx_type` symbol.
13871 header.reduced_tx_set = !wide_tx_set(screen);
13872 // lane-intertx, desync (a): the frame context this value is read back
13873 // through ([`decode::reduce_inherited_chroma_tx_type`] inside
13874 // `recode_inter_chroma`, and every inter decode helper the search's own
13875 // trial decode shares) must carry THIS frame's bit, not whatever the
13876 // previous frame's trial decode last left in the shared cell -- a stale
13877 // `true` here narrows the chroma allowance the search reconstructs
13878 // against under the one the header's bit actually allows.
13879 fctx.reduced_tx_set_inter.set(header.reduced_tx_set);
13880 // The search prices coefficients against the tables this frame's writer
13881 // starts from, not against the defaults (lane-av1txbits) -- but only on a
13882 // frame the screen detector said no to (lane-av1price2): armed HERE, after
13883 // `screen` exists, and again on every search/tile worker below.
13884 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
13885 let mut luma = Plane {
13886 source: &picture_y8,
13887 reconstruction: vec![128; picture_y8.len()],
13888 width: picture.width,
13889 height: picture.height,
13890 true_width,
13891 true_height,
13892 tile_x0: 0,
13893 tile_y0: 0,
13894 tile_x1: picture.width,
13895 tile_y1: picture.height,
13896 ctx: CoefCtxMap::default(),
13897 };
13898 let mut chroma = [
13899 Plane {
13900 source: &picture_u8,
13901 reconstruction: vec![128; picture_u8.len()],
13902 width: picture.width / 2,
13903 height: picture.height / 2,
13904 true_width: true_width / 2,
13905 true_height: true_height / 2,
13906 tile_x0: 0,
13907 tile_y0: 0,
13908 tile_x1: picture.width / 2,
13909 tile_y1: picture.height / 2,
13910 ctx: CoefCtxMap::default(),
13911 },
13912 Plane {
13913 source: &picture_v8,
13914 reconstruction: vec![128; picture_v8.len()],
13915 width: picture.width / 2,
13916 height: picture.height / 2,
13917 true_width: true_width / 2,
13918 true_height: true_height / 2,
13919 tile_x0: 0,
13920 tile_y0: 0,
13921 tile_x1: picture.width / 2,
13922 tile_y1: picture.height / 2,
13923 ctx: CoefCtxMap::default(),
13924 },
13925 ];
13926
13927 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
13928 let top_arf = matches!(
13929 pyramid,
13930 Some(p) if p.dq_level == DqLevel::TopArf
13931 );
13932 let arfmode_v = arfmode();
13933 let search = Search {
13934 base_q_idx,
13935 deadzone,
13936 lambda: lambda_scale()
13937 * match pyramid {
13938 Some(p) if !p.show_frame => hidden_lambda_factor(),
13939 _ => 1.0,
13940 }
13941 * step
13942 * step,
13943 modes: &KEY_FRAME_MODES,
13944 top_k: prune_top_k_inter(),
13945 screen,
13946 // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose
13947 // offset is the pyramid's own `arf_q_offset`) reads its leaf offer
13948 // set from [`crate::speed::ARFMODE`]; every other frame -- the mid
13949 // and quarter hidden frames, the leaves, the flat path -- keeps the
13950 // full set.
13951 arf_leaf_intra: !top_arf || arfmode_v & 1 == 0,
13952 arf_leaf8: !top_arf || arfmode_v & 2 == 0,
13953 arf_leaf_compound: !top_arf || arfmode_v & 4 == 0,
13954 };
13955 let mode_bits_table = inter_mode_bits();
13956 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
13957 // this frame the NEXT one predicts from. Off (`None`) without a
13958 // lookahead picture or at strength 0.
13959 let tpl_k = tpl_strength();
13960 let window: Vec<&Picture> = lookahead
13961 .iter()
13962 .take_while(|n| n.width == picture.width && n.height == picture.height)
13963 .collect();
13964 let tpl_sources: Vec<Vec<u8>> = window
13965 .iter()
13966 .map(|n| n.y.iter().map(|&v| v as u8).collect())
13967 .collect();
13968 let tpl_cells_x = picture.width / 16;
13969 // `.1` is the propagating map's raw per-cell dependence ratio, which only
13970 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
13971 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> = (tpl_k > 0.0 && !tpl_sources.is_empty())
13972 .then(|| {
13973 if tpl_propagating() {
13974 let mut frames: Vec<&[u8]> = vec![&picture_y8];
13975 frames.extend(tpl_sources.iter().map(Vec::as_slice));
13976 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
13977 (f, Some(r))
13978 } else {
13979 // The shipped map is one factor per 64x64; it is spread over that
13980 // superblock's own 16 cells so the application site below (which
13981 // averages the four cells of a 32x32 block) reads exactly the
13982 // superblock factor, whichever map fed it.
13983 let map = tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
13984 let cells_y = picture.height / 16;
13985 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
13986 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
13987 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
13988 .collect();
13989 (f, None)
13990 }
13991 });
13992 let (tpl_factors, tpl_ratio) = match tpl_both {
13993 Some((f, r)) => (Some(f), r),
13994 None => (None, None),
13995 };
13996
13997 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
13998 // coding surface's: `blocks` carries one entry per 32x32 block the tile
13999 // writer will actually visit, same count it checks `blocks.len()`
14000 // against, which is fewer than the padded surface's own block count
14001 // whenever the true size is not a 64x64 multiple.
14002 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
14003 let (cols, rows) = (cols as usize, rows as usize);
14004 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
14005 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
14006 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
14007 // only when the map is, and `delta_q_res` follows straight into the frame
14008 // header (`write_delta_q_params`) and into the tile writer's own plan.
14009 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
14010 // measured the per-superblock quantizer as a win on both films and a
14011 // 0.5 loss vs libaom on the desktop capture, so a frame that set
14012 // `allow_screen_content_tools` codes no delta syntax at all and stays
14013 // byte-identical to the pre-lane encoder.
14014 // lane-arfq: the level whose `delta_q` strength this frame reads; the
14015 // flat path (no pyramid) is a leaf.
14016 let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level);
14017 let deltaq_res: Option<i32> = tpl_factors
14018 .as_ref()
14019 .filter(|_| !screen)
14020 .and(deltaq_res_log2().map(|r| 1i32 << r));
14021 // The same 16-cell mean the superblock's own lambda takes, clamped to the
14022 // map the frame actually has -- read over the factors or over the raw
14023 // dependence ratios, whichever mapping is asking.
14024 let sb_mean = |m: &[f64], sb: usize| {
14025 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
14026 (0..16)
14027 .map(|i| {
14028 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
14029 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
14030 })
14031 .sum::<f64>()
14032 / 16.0
14033 };
14034 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
14035 // raw dependence ratio; without it (and always without a ratio map, i.e.
14036 // on the one-frame area map) the shipped derivation stands.
14037 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
14038 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
14039 match (libaom, tpl_ratio.as_deref(), r_frame) {
14040 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
14041 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
14042 }
14043 };
14044 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
14045 (Some(f), Some(res)) => {
14046 let libaom = dq_tpl_strength(dq_level);
14047 let mut g: Vec<u8> = (0..sb_cols * _sb_rows)
14048 .map(|sb| sb_qindex(f, res, sb, libaom))
14049 .collect();
14050 // lane-b128m: under 128 superblocks the delta_q syntax is coded
14051 // ONCE per 128 root (the reader's own unit), so all four 64x64
14052 // cells of a root have to be searched -- and quantized -- at the
14053 // one qindex the root's top-left cell codes.
14054 if sb128_on() {
14055 for sb_r in 0.._sb_rows {
14056 for sb_c in 0..sb_cols {
14057 let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
14058 g[sb_r * sb_cols + sb_c] = q;
14059 }
14060 }
14061 }
14062 Some(g)
14063 }
14064 _ => None,
14065 };
14066 // lane-dq census: both mappings on the SAME superblocks, whether or not
14067 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
14068 // off, and the census then prices the default `res = 4` grid).
14069 if dq_census() {
14070 if let Some(f) = &tpl_factors {
14071 let res = deltaq_res.unwrap_or(4);
14072 let off = |libaom: Option<f64>| -> Vec<i32> {
14073 (0..sb_cols * _sb_rows)
14074 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
14075 .collect()
14076 };
14077 let strength = dq_tpl_strength(dq_level);
14078 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
14079 let coded = match (deltaq_res.is_some(), strength) {
14080 (false, _) => "none".to_string(),
14081 (true, None) => "ours".to_string(),
14082 (true, Some(k)) => format!("libaom k={k}"),
14083 };
14084 eprintln!(
14085 "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
14086 sb_cols * _sb_rows,
14087 r_frame.unwrap_or(f64::NAN),
14088 dq_summary(&ours),
14089 dq_summary(&aom),
14090 );
14091 }
14092 }
14093 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
14094 header.delta.q_present = true;
14095 header.delta.q_res = res.trailing_zeros() as u8;
14096 }
14097 // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
14098 // below, so the root search prices the group the writer really codes.
14099 let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
14100 if let Some(g) = &sb_q {
14101 let mut levels: Vec<u8> = g.clone();
14102 levels.sort_unstable();
14103 levels.dedup();
14104 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
14105 }
14106 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
14107 // This frame's tile grid, as in `encode_key_frame_inner`.
14108 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
14109 let layout = crate::tile::TileLayout::new(
14110 header.mi_cols,
14111 header.mi_rows,
14112 tile_cols_log2,
14113 tile_rows_log2,
14114 );
14115 header.tile_info = tile_info_of(&layout, 1);
14116 let header_tile_info = header.tile_info.clone();
14117 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
14118 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
14119 // once per frame (lane-av1rd2), not once per block, which is a whole
14120 // plane's map per 32x32 block and now per leaf too.
14121 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
14122 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
14123 // availability -- intra edges and the MV stack's scans alike -- already
14124 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
14125 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
14126 // giving each job its own planes and its own `MiGrid` therefore leaves
14127 // every decision, and so every coded bit, exactly where the whole-frame
14128 // loop left it, at any tile count and any thread count.
14129 let (frame_width, frame_height) = (picture.width, picture.height);
14130 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
14131 let [cb, cr] = &mut chroma;
14132 let chroma_out = [
14133 crate::par::Shared::new(&mut cb.reconstruction),
14134 crate::par::Shared::new(&mut cr.reconstruction),
14135 ];
14136 let search_tile = |index: usize,
14137 fctx: &crate::decode::FrameCtx|
14138 -> Result<Vec<(usize, Quadrant)>> {
14139 // Thread-local, and this job may be running on a `search_tiles`
14140 // worker: `ref_distance`'s order-hint distance (the scaled motion
14141 // search step) is read by the SEARCH, so every worker arms it or the
14142 // tile's bits depend on the thread count.
14143 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
14144 crate::tile::arm_high_precision_mv(hp_mv);
14145 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
14146 let rect = layout.rect(index);
14147 let mut luma = fresh_plane(
14148 &picture_y8,
14149 frame_width,
14150 frame_height,
14151 true_width,
14152 true_height,
14153 );
14154 let mut chroma = [
14155 fresh_plane(
14156 &picture_u8,
14157 frame_width / 2,
14158 frame_height / 2,
14159 true_width / 2,
14160 true_height / 2,
14161 ),
14162 fresh_plane(
14163 &picture_v8,
14164 frame_width / 2,
14165 frame_height / 2,
14166 true_width / 2,
14167 true_height / 2,
14168 ),
14169 ];
14170 clip_planes_to_tile(&mut luma, &mut chroma, rect);
14171 let mut grid = MiGrid::new(mi_cols, mi_rows);
14172 grid.set_sign_bias(sign_bias);
14173 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
14174 // built once per tile job (`obmc_prediction`).
14175 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
14176 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
14177 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
14178 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
14179 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
14180 grid.set_tile_bounds(
14181 rect.mi_row0 as usize,
14182 rect.mi_col0 as usize,
14183 rect.mi_row1 as usize,
14184 rect.mi_col1 as usize,
14185 );
14186 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
14187 // lane-b128: under a 128x128 superblock the search walks the roots the
14188 // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
14189 // not plain raster -- a search that visits BL before TR builds every mv
14190 // stack and neighbour context off blocks the writer has not coded yet,
14191 // which is what made the write-time drl clamp fire at all (lane-sb128b).
14192 // At a 64 superblock the two orders are identical and this is the same
14193 // raster loop as before.
14194 let sb128_search = sb128_on();
14195 let root_step = if sb128_search { 2 } else { 1 };
14196 let mut roots: Vec<(usize, usize)> = Vec::new();
14197 {
14198 let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
14199 let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
14200 let mut r = r0;
14201 while r < r1 {
14202 let mut c = c0;
14203 while c < c1 {
14204 roots.push((r, c));
14205 c += root_step;
14206 }
14207 r += root_step;
14208 }
14209 }
14210 for (root_r, root_c) in roots {
14211 // The 64x64 cells of this root, in the writer's own order.
14212 let cells: Vec<(usize, usize)> = if sb128_search {
14213 [(0, 0), (0, 1), (1, 0), (1, 1)]
14214 .into_iter()
14215 .map(|(dr, dc)| (root_r + dr, root_c + dc))
14216 .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
14217 .collect()
14218 } else {
14219 vec![(root_r, root_c)]
14220 };
14221 // What the four cells below really cost, against which the whole
14222 // 128x128 candidate is weighed.
14223 let mark128 = blocks.len();
14224 let mut root_cost = 0.0f64;
14225 // The 128 root's own compound pairs, at its 32x32-mi window (the 64
14226 // root builds the same list one size down, per superblock).
14227 let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14228 if header.reference_select && b128_compound() && !screen && sb128_search {
14229 [
14230 (crate::mvstack::GOLDEN_FRAME, golden),
14231 (crate::mvstack::ALTREF_FRAME, altref),
14232 ]
14233 .into_iter()
14234 .filter_map(|(r, pic)| {
14235 pic.map(|p| {
14236 (
14237 r,
14238 p,
14239 crate::mvstack::find_mv_stack_compound(
14240 &grid,
14241 root_r * 16,
14242 root_c * 16,
14243 32,
14244 32,
14245 (crate::mvstack::LAST_FRAME, r),
14246 mi_cols,
14247 mi_rows,
14248 grid.sign_bias_table(),
14249 &[(0, 0); 7],
14250 None,
14251 ),
14252 )
14253 })
14254 })
14255 .collect()
14256 } else {
14257 Vec::new()
14258 };
14259 let root128 = (sb128_search && b128_root() && cells.len() == 4)
14260 .then(|| {
14261 search_root_128(
14262 &mut luma,
14263 &mut chroma,
14264 &grid,
14265 (root_r, root_c),
14266 (rows, cols),
14267 (header.mi_cols, header.mi_rows),
14268 search,
14269 &tpl_factors,
14270 sb_q.as_ref(),
14271 sb_cols,
14272 tpl_cells_x,
14273 base_q_idx,
14274 dq_res,
14275 reference,
14276 &root_compound,
14277 fctx,
14278 )
14279 })
14280 .flatten();
14281 // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
14282 // are priced; the cheaper one competes with the NONE block and with
14283 // the four superblocks below.
14284 let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
14285 let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
14286 .then(|| {
14287 let mut best: Option<(bool, _)> = None;
14288 for horz in [true, false] {
14289 if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
14290 continue;
14291 }
14292 let Some(found) = search_root_128_rect(
14293 &mut luma,
14294 &mut chroma,
14295 &mut grid,
14296 (root_r, root_c),
14297 (rows, cols),
14298 (header.mi_cols, header.mi_rows),
14299 search,
14300 &tpl_factors,
14301 sb_q.as_ref(),
14302 sb_cols,
14303 tpl_cells_x,
14304 base_q_idx,
14305 dq_res,
14306 reference,
14307 &root_compound,
14308 horz,
14309 fctx,
14310 ) else {
14311 continue;
14312 };
14313 if best
14314 .as_ref()
14315 .is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0)
14316 {
14317 best = Some((horz, found));
14318 }
14319 }
14320 best
14321 })
14322 .flatten();
14323 // lane-ab128: and the same root as one of the four AB shapes -- two
14324 // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
14325 // the cheapest joins the candidate list below.
14326 let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
14327 let root_ab = (sb128_search
14328 && (b128_ab() || forced_ab != 0)
14329 && cells.len() == 4
14330 && forced_rect == 0)
14331 .then(|| {
14332 let mut best: Option<(usize, _)> = None;
14333 for symbol in 4..=7usize {
14334 if forced_ab != 0 && usize::from(forced_ab) != symbol {
14335 continue;
14336 }
14337 let Some(found) = search_root_128_ab(
14338 &mut luma,
14339 &mut chroma,
14340 &mut grid,
14341 (root_r, root_c),
14342 (rows, cols),
14343 (header.mi_cols, header.mi_rows),
14344 search,
14345 &tpl_factors,
14346 sb_q.as_ref(),
14347 sb_cols,
14348 tpl_cells_x,
14349 base_q_idx,
14350 reference,
14351 &root_compound,
14352 symbol,
14353 fctx,
14354 ) else {
14355 continue;
14356 };
14357 if best
14358 .as_ref()
14359 .is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0)
14360 {
14361 best = Some((symbol, found));
14362 }
14363 }
14364 best
14365 })
14366 .flatten();
14367 for (sb_r, sb_c) in cells {
14368 // lane-b64: the whole superblock as ONE 64x64 block, tried before
14369 // its quadrants are (`search_skip_64`) and compared against the
14370 // four of them below. Only a superblock wholly inside the true
14371 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
14372 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
14373 // only that the block's half is inside, and the trial is ranked
14374 // over the inside part alone ([`Plane::block_sse`]).
14375 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
14376 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
14377 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
14378 && x64 + SUPERBLOCK <= luma.true_width
14379 && y64 + SUPERBLOCK <= luma.true_height;
14380 let edge_inside = b64_edge()
14381 && crate::tile::has_half(
14382 sb_c as u32 * crate::tile::SB_MI,
14383 crate::tile::SB_MI,
14384 header.mi_cols,
14385 )
14386 && crate::tile::has_half(
14387 sb_r as u32 * crate::tile::SB_MI,
14388 crate::tile::SB_MI,
14389 header.mi_rows,
14390 );
14391 let sb64_legal = b64_root()
14392 && sb_r * 2 + 1 < rows
14393 && sb_c * 2 + 1 < cols
14394 && (whole_inside || edge_inside);
14395 // One lambda for the whole superblock, the same mean the 32x32
14396 // level takes over its own four tpl cells: the 64-vs-four-32
14397 // comparison below weighs one cost against four, so both sides
14398 // have to be priced at the same lambda.
14399 let sb_search = match &tpl_factors {
14400 // lane-deltaq: with a per-superblock quantizer the lambda
14401 // comes from that quantizer, not from the raw map factor --
14402 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
14403 Some(_) if sb_q.is_some() => sb_q_search(
14404 sb_q.as_ref().expect("armed"),
14405 sb_cols,
14406 base_q_idx,
14407 (sb_r, sb_c),
14408 search,
14409 ),
14410 Some(f) if sb64_legal => {
14411 let mean = (0..16)
14412 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
14413 .sum::<f64>()
14414 / 16.0;
14415 Search {
14416 lambda: search.lambda * mean,
14417 ..search
14418 }
14419 }
14420 _ => search,
14421 };
14422 let mark = blocks.len();
14423 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
14424 let mut sb_cost = 0.0f64;
14425 if sb64_legal {
14426 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
14427 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
14428 let stack =
14429 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
14430 // lane-b64b: the `LAST` + extra-reference pairs at this
14431 // superblock's own 16x16-mi window, the same stacks the tile
14432 // writer's `Whole64` arm rebuilds. Empty unless the frame
14433 // codes `reference_select`, which is what gates the syntax.
14434 // `!screen` for the same reason the residual arm is gated
14435 // there ([`b64_residual`]): a desktop capture's superblocks
14436 // are flat runs the skip arm already codes for nothing, and
14437 // MEASURED, compound at the root cost it +33.4/-23.8 ->
14438 // +33.7/-23.6 while both film rows gained (step 1's table).
14439 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14440 if header.reference_select && b64_compound() && !screen {
14441 [
14442 (crate::mvstack::GOLDEN_FRAME, golden),
14443 (crate::mvstack::ALTREF_FRAME, altref),
14444 ]
14445 .into_iter()
14446 .filter_map(|(r, pic)| {
14447 pic.map(|p| {
14448 (
14449 r,
14450 p,
14451 crate::mvstack::find_mv_stack_compound(
14452 &grid,
14453 mi_row,
14454 mi_col,
14455 16,
14456 16,
14457 (crate::mvstack::LAST_FRAME, r),
14458 mi_cols,
14459 mi_rows,
14460 grid.sign_bias_table(),
14461 &[(0, 0); 7],
14462 None,
14463 ),
14464 )
14465 })
14466 })
14467 .collect()
14468 } else {
14469 Vec::new()
14470 };
14471 if let Some((cost, block)) = search_skip_64(
14472 &mut luma,
14473 &mut chroma,
14474 (x64, y64),
14475 (SUPERBLOCK, SUPERBLOCK),
14476 &sb_search,
14477 b64_residual() && !screen,
14478 reference,
14479 &stack,
14480 &sb_compound,
14481 fctx,
14482 ) {
14483 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
14484 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
14485 let cost = cost
14486 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
14487 sb64 = Some((cost, block, after));
14488 }
14489 }
14490 // A superblock whose 64x64 trial already codes almost nothing per
14491 // pixel is taken outright and its quadrants are never searched --
14492 // the same `split_rd_breakout` shape the 32x32 level uses one
14493 // size up, and where this lever BUYS wall instead of spending it.
14494 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
14495 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, sb_search.lambda)
14496 });
14497 for quadrant in 0..if early64 { 0 } else { 4 } {
14498 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
14499 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
14500 // decision under it (partition, mode, tx, motion) reads
14501 // `search.lambda`, so scaling the one field here scales all
14502 // of them. 32x32 and not the 16x16 the map is built at
14503 // because the whole-vs-split comparison right below weighs
14504 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
14505 // would make those two numbers incomparable.
14506 let search = match &tpl_factors {
14507 // lane-deltaq: the quantizer is a SUPERBLOCK-level
14508 // symbol, so all four quadrants take their superblock's
14509 // own qindex and the lambda it implies. No granularity is
14510 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
14511 // factor per superblock, shared by its sixteen cells.
14512 Some(_) if sb_q.is_some() => sb_q_search(
14513 sb_q.as_ref().expect("armed"),
14514 sb_cols,
14515 base_q_idx,
14516 (sb_r, sb_c),
14517 search,
14518 ),
14519 Some(f) => {
14520 let mean = (0..4)
14521 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
14522 .sum::<f64>()
14523 / 4.0;
14524 Search {
14525 lambda: search.lambda * mean,
14526 ..search
14527 }
14528 }
14529 None => search,
14530 };
14531 // Same filter as the tile writer's: a quadrant whose own mi
14532 // origin is not inside the true frame is never coded.
14533 if r32 >= rows || c32 >= cols {
14534 continue;
14535 }
14536 // spec `decode_partition`'s hasRows/hasCols recomputed at this
14537 // 32x32 block's own half (`crate::tile::has_half`), same as
14538 // the key frame search: the true frame edge can fall inside a
14539 // quadrant a superblock-level check already let through, and
14540 // such a quadrant cannot be left whole -- it must split into
14541 // the 16x16 leaves that are actually inside the true frame
14542 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
14543 // arm).
14544 let (has_cols32, has_rows32) = (
14545 crate::tile::has_half(
14546 c32 as u32 * crate::tile::BLOCK_MI,
14547 crate::tile::BLOCK_MI,
14548 header.mi_cols,
14549 ),
14550 crate::tile::has_half(
14551 r32 as u32 * crate::tile::BLOCK_MI,
14552 crate::tile::BLOCK_MI,
14553 header.mi_rows,
14554 ),
14555 );
14556 if has_cols32 && has_rows32 {
14557 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
14558 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
14559 let stack = find_mv_stack(
14560 &grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows,
14561 );
14562 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
14563 (crate::mvstack::LAST2_FRAME, last2),
14564 (crate::mvstack::GOLDEN_FRAME, golden),
14565 (crate::mvstack::ALTREF_FRAME, altref),
14566 ]
14567 .into_iter()
14568 .filter_map(|(r, pic)| {
14569 pic.map(|p| {
14570 (
14571 r,
14572 p,
14573 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
14574 )
14575 })
14576 })
14577 .collect();
14578 let extra: Vec<(i8, &Picture, &MvStack)> =
14579 extra_stacks.iter().map(|(r, p, st)| (*r, *p, st)).collect();
14580 // The COMPOUND stack of each `LAST` + extra pair, off the
14581 // same grid (and the same armed sign bias) the tile writer
14582 // rebuilds it from. Empty unless this frame codes
14583 // `reference_select`, which is what gates the syntax.
14584 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14585 if header.reference_select {
14586 extra_stacks
14587 .iter()
14588 .map(|&(r, p, _)| {
14589 (
14590 r,
14591 p,
14592 crate::mvstack::find_mv_stack_compound(
14593 &grid,
14594 mi_row,
14595 mi_col,
14596 8,
14597 8,
14598 (crate::mvstack::LAST_FRAME, r),
14599 mi_cols,
14600 mi_rows,
14601 grid.sign_bias_table(),
14602 &[(0, 0); 7],
14603 None,
14604 ),
14605 )
14606 })
14607 .collect()
14608 } else {
14609 Vec::new()
14610 };
14611
14612 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
14613 let (block, mut cost_whole) = search_inter_block(
14614 &mut luma,
14615 &mut chroma,
14616 (x, y),
14617 &search,
14618 &mode_bits_table,
14619 reference,
14620 &stack,
14621 &extra,
14622 &compound,
14623 &grid,
14624 (mi_row, mi_col),
14625 (mi_rows, mi_cols),
14626 fctx,
14627 );
14628 cost_whole += search.lambda * partition_bits(BLOCK, false);
14629 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
14630
14631 // What four 16x16 leaves cost instead (spec
14632 // PARTITION_SPLIT at BLOCK_32X32, which
14633 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
14634 // already writes for a straddling quadrant). Each leaf is
14635 // searched against the reconstruction -- and the `mi`
14636 // grid -- the ones before it left, exactly as the writer
14637 // and the decoder will read them.
14638 //
14639 // A block the whole-32 search left skipped (no residual
14640 // at all) is not offered the split: libaom prunes the
14641 // same way at cpu-used 6, and it is where the wall would
14642 // otherwise go on static content.
14643 let leaf_positions: Vec<(usize, usize)> =
14644 (0..4).map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)).collect();
14645 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
14646 crate::tile::has_half(
14647 sc as u32 * crate::tile::SUB_MI,
14648 crate::tile::SUB_MI,
14649 header.mi_cols,
14650 ) && crate::tile::has_half(
14651 sr as u32 * crate::tile::SUB_MI,
14652 crate::tile::SUB_MI,
14653 header.mi_rows,
14654 )
14655 });
14656 // The breakout above: a 32x32 block that codes almost
14657 // nothing is not offered the split at all.
14658 let breakout = split_breakout_coeffs();
14659 let split = (!block.skip
14660 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
14661 && (breakout == 0 || block.luma.len() > 4 * breakout)
14662 && leaves_legal
14663 && split_inter_blocks())
14664 .then(|| {
14665 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
14666 let mut cost = search.lambda * partition_bits(BLOCK, true);
14667 let mut leaves = Vec::with_capacity(4);
14668 for &(sr, sc) in &leaf_positions {
14669 let (mi_row, mi_col) = (sr * 4, sc * 4);
14670 let (lx, ly) = (sc * SUB, sr * SUB);
14671 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
14672 let stack = find_mv_stack(
14673 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
14674 );
14675 let cstacks = leaf_compound_stacks(
14676 &grid,
14677 mi_row,
14678 mi_col,
14679 4,
14680 4,
14681 mi_cols,
14682 mi_rows,
14683 header.reference_select,
14684 golden,
14685 altref,
14686 );
14687 let (leaf, leaf_cost) = code_square_inter(
14688 &mut luma,
14689 &mut chroma,
14690 (lx, ly),
14691 SUB,
14692 &search,
14693 &mode_bits_table,
14694 reference,
14695 &stack,
14696 &cstacks,
14697 &grid,
14698 (mi_row, mi_col),
14699 (mi_rows, mi_cols),
14700 &obmc_refs,
14701 fctx,
14702 );
14703 let leaf_cost =
14704 leaf_cost + search.lambda * partition_bits(SUB, false);
14705 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
14706
14707 // And what four 8x8 leaves cost instead --
14708 // the same tree one step further down, which
14709 // the writer codes as a real PARTITION_SPLIT
14710 // at BLOCK_16X16 (lane-av1rd2). Same
14711 // skipped-block prune as the level above.
14712 let eight = (!leaf.skip
14713 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
14714 && (breakout == 0 || leaf.luma.len() > breakout)
14715 && split_inter_8()
14716 // lane-arfmode: arm 2 makes 16x16 the top
14717 // ARF's leaf floor -- the RD-optional 8x8
14718 // comparison is not offered. Counted only
14719 // when every other prune let it through,
14720 // so the counter means "refused", not
14721 // "never considered". The spec-forced 8x8s
14722 // at a straddling 16x16 (the
14723 // `sub_positions` path below) are a
14724 // different site and stay.
14725 && (search.arf_leaf8 || arfmode_hit_and_no()))
14726 .then(|| {
14727 restore(&mut luma, &mut chroma, (lx, ly), SUB, &leaf_base);
14728 let mut cost8 = search.lambda
14729 * (partition_bits(SUB, true)
14730 + 4.0 * partition_bits(8, false));
14731 let mut eight = Vec::with_capacity(4);
14732 for i in 0..4 {
14733 let (mr, mc) = (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
14734 let stack8 = find_mv_stack(
14735 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
14736 );
14737 let cstacks8: Vec<(
14738 i8,
14739 &Picture,
14740 crate::mvstack::CompoundMvStack,
14741 )> = if header.reference_select && leaf_compound() {
14742 [
14743 (crate::mvstack::GOLDEN_FRAME, golden),
14744 (crate::mvstack::ALTREF_FRAME, altref),
14745 ]
14746 .into_iter()
14747 .filter_map(|(r, pic)| {
14748 pic.map(|p| {
14749 (
14750 r,
14751 p,
14752 crate::mvstack::find_mv_stack_compound(
14753 &grid,
14754 mr,
14755 mc,
14756 2,
14757 2,
14758 (crate::mvstack::LAST_FRAME, r),
14759 mi_cols,
14760 mi_rows,
14761 grid.sign_bias_table(),
14762 &[(0, 0); 7],
14763 None,
14764 ),
14765 )
14766 })
14767 })
14768 .collect()
14769 } else {
14770 Vec::new()
14771 };
14772 let (leaf8, cost) = code_square_inter(
14773 &mut luma,
14774 &mut chroma,
14775 (lx + (i % 2) * 8, ly + (i / 2) * 8),
14776 8,
14777 &search,
14778 &mode_bits_table,
14779 reference,
14780 &stack8,
14781 &cstacks8,
14782 &grid,
14783 (mr, mc),
14784 (mi_rows, mi_cols),
14785 &obmc_refs,
14786 fctx,
14787 );
14788 cost8 += cost;
14789 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
14790 eight.push(leaf8);
14791 }
14792 (eight, cost8)
14793 });
14794 match eight {
14795 Some((eight, cost8)) if cost8 < leaf_cost => {
14796 partition_hit(3);
14797 cost += cost8;
14798 leaves.push(BlockCoeffs {
14799 eight: Some(eight),
14800 ..BlockCoeffs::default()
14801 });
14802 continue;
14803 }
14804 Some(_) => {
14805 restore(&mut luma, &mut chroma, (lx, ly), SUB, &after_leaf)
14806 }
14807 None => {}
14808 }
14809 partition_hit(2);
14810 cost += leaf_cost;
14811 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
14812 leaves.push(leaf);
14813 }
14814 (leaves, cost)
14815 });
14816 if let Some((leaves, cost)) = split {
14817 if cost < cost_whole {
14818 // The leaves' own `mi` cells are already in the
14819 // grid, and their reconstruction is what the
14820 // planes hold.
14821 partition_hit(1);
14822 sb_cost += cost;
14823 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
14824 continue;
14825 }
14826 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
14827 }
14828 partition_hit(0);
14829 sb_cost += cost_whole;
14830 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
14831 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
14832 } else {
14833 // The sub-positions actually inside the true frame, same
14834 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
14835 let sub_positions: Vec<(usize, usize)> = (0..4)
14836 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
14837 .filter(|&(sr, sc)| {
14838 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
14839 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
14840 })
14841 .collect();
14842 // Each leaf searches intra against its own `NEARESTMV`
14843 // candidate (`code_square_inter`), same real-inter choice
14844 // `search_inter_block` makes for a whole 32x32 block, at
14845 // this leaf's own 4x4-mi mv-stack window -- unless the
14846 // leaf's own half itself straddles the true edge, which
14847 // it codes as two (or one, at a true corner) 8x8 leaves
14848 // (`crate::tile::write_leaf8`'s inter counterpart),
14849 // mirroring the key frame search's straddling-16x16
14850 // handling above (lane-av1inter8).
14851 let mut leaves = Vec::with_capacity(sub_positions.len());
14852 for (sr, sc) in sub_positions {
14853 let (has_cols16, has_rows16) = (
14854 crate::tile::has_half(
14855 sc as u32 * crate::tile::SUB_MI,
14856 crate::tile::SUB_MI,
14857 header.mi_cols,
14858 ),
14859 crate::tile::has_half(
14860 sr as u32 * crate::tile::SUB_MI,
14861 crate::tile::SUB_MI,
14862 header.mi_rows,
14863 ),
14864 );
14865 if has_cols16 && has_rows16 {
14866 let (x, y) = (sc * SUB, sr * SUB);
14867 let (mi_row, mi_col) = (sr * 4, sc * 4);
14868 let stack = find_mv_stack(
14869 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
14870 );
14871 let cstacks = leaf_compound_stacks(
14872 &grid,
14873 mi_row,
14874 mi_col,
14875 4,
14876 4,
14877 mi_cols,
14878 mi_rows,
14879 header.reference_select,
14880 golden,
14881 altref,
14882 );
14883 let (block, _) = code_square_inter(
14884 &mut luma,
14885 &mut chroma,
14886 (x, y),
14887 SUB,
14888 &search,
14889 &mode_bits_table,
14890 reference,
14891 &stack,
14892 &cstacks,
14893 &grid,
14894 (mi_row, mi_col),
14895 (mi_rows, mi_cols),
14896 &obmc_refs,
14897 fctx,
14898 );
14899 // One publication point for every coded leaf
14900 // (`record_mi`): this site used to spell the vote
14901 // out with `ref_frame` pinned to LAST and `mv1`
14902 // to (0,0), which is the encoder-grid-drift class
14903 // -- correct only for as long as a leaf can never
14904 // be compound.
14905 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
14906 leaves.push(block);
14907 } else {
14908 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
14909 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
14910 let mut eight = Vec::with_capacity(2);
14911 for i in 0..4 {
14912 let leaf_x = x_sub + (i % 2) * 8;
14913 let leaf_y = y_sub + (i / 2) * 8;
14914 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
14915 continue;
14916 }
14917 let (mi_row, mi_col) =
14918 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
14919 let stack = find_mv_stack(
14920 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
14921 );
14922 let cstacks = leaf_compound_stacks(
14923 &grid,
14924 mi_row,
14925 mi_col,
14926 2,
14927 2,
14928 mi_cols,
14929 mi_rows,
14930 header.reference_select,
14931 golden,
14932 altref,
14933 );
14934 let (leaf, _) = code_square_inter(
14935 &mut luma,
14936 &mut chroma,
14937 (leaf_x, leaf_y),
14938 8,
14939 &search,
14940 &mode_bits_table,
14941 reference,
14942 &stack,
14943 &cstacks,
14944 &grid,
14945 (mi_row, mi_col),
14946 (mi_rows, mi_cols),
14947 &obmc_refs,
14948 fctx,
14949 );
14950 // Same publication point as the 16x16
14951 // straddling leaf above (`record_mi`).
14952 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
14953 eight.push(leaf);
14954 }
14955 leaves.push(BlockCoeffs {
14956 eight: Some(eight),
14957 ..BlockCoeffs::default()
14958 });
14959 }
14960 }
14961 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
14962 }
14963 }
14964 // The 64x64 root against what its four quadrants really cost.
14965 if let Some((cost64, block, after)) = sb64
14966 && (early64
14967 || cost64
14968 < sb_cost
14969 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
14970 {
14971 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14972 if block.inter.is_some_and(|i| i.ref1.is_some()) {
14973 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14974 }
14975 if !whole_inside {
14976 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14977 }
14978 blocks.truncate(mark);
14979 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
14980 // Overwrites every 16x16 mi cell the quadrant searches
14981 // published under this superblock, so the next block's stack
14982 // is built off the block that was really coded.
14983 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
14984 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
14985 for q in 1..4 {
14986 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
14987 blocks.push((r32 * cols + c32, Quadrant::Covered));
14988 }
14989 root_cost += cost64;
14990 } else {
14991 root_cost += sb_cost;
14992 }
14993 }
14994 // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
14995 // `partition_w128` symbol) against what its four superblocks really
14996 // cost, the same weighing the 64 root does one size down. Both sides
14997 // carry their own partition symbol, so the comparison is complete.
14998 // The root candidates, each tagged with the PARTITION symbol its
14999 // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
15000 // shapes (lane-ab128).
15001 let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
15002 if let Some((c, l, b, a)) = root128 {
15003 cands.push((c, l, 0, vec![b], a));
15004 }
15005 if let Some((horz, (c, l, halves, a))) = root_rect {
15006 cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
15007 }
15008 if let Some((symbol, (c, l, pieces, a))) = root_ab {
15009 cands.push((c, l, symbol, pieces.to_vec(), a));
15010 }
15011 // The witness knobs drop every other arm outright: on synthetic
15012 // content the whole block always wins its own comparison.
15013 if forced_rect != 0 {
15014 cands.retain(|c| c.2 == 1 || c.2 == 2);
15015 }
15016 if forced_ab != 0 {
15017 cands.retain(|c| c.2 == usize::from(forced_ab));
15018 }
15019 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
15020 // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
15021 // superblock arm codes the delta_q group too -- the Whole64 writer
15022 // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
15023 // with `!sb128_armed()`) and every smaller shape below it pass
15024 // `is_whole_sb = false` under a 128 grid, so the arm's first
15025 // (root-origin) superblock codes the group even when skipped. Only the skipped 128
15026 // NONE root escapes it, so the split side is charged here at the same
15027 // root lambda the candidates are priced with.
15028 let split_dq =
15029 delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
15030 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
15031 && (cost128
15032 < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
15033 // The witness knobs take the root whatever it costs, so the
15034 // forced block really reaches the writer.
15035 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
15036 || forced_rect != 0
15037 || forced_ab != 0)
15038 {
15039 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
15040 blocks.truncate(mark128);
15041 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
15042 let at = (root_r * 2) * cols + root_c * 2;
15043 match shape {
15044 0 => {
15045 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15046 let block = halves.into_iter().next().expect("the NONE arm's block");
15047 record_mi(
15048 &mut grid,
15049 root_r * 16,
15050 root_c * 16,
15051 32,
15052 block.inter,
15053 block.skip,
15054 );
15055 blocks.push((at, Quadrant::Whole128(block)));
15056 }
15057 // lane-ab128: three pieces, published at their own footprints
15058 // in the writer's own order ([`ab128_pieces`]).
15059 symbol @ 4..=7 => {
15060 B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15061 for (((mr, mc), (w, h)), piece) in
15062 ab128_pieces(symbol, (root_r * 16, root_c * 16))
15063 .iter()
15064 .zip(&halves)
15065 {
15066 record_mi_rect(
15067 &mut grid,
15068 *mr,
15069 *mc,
15070 (w / 4, h / 4),
15071 piece.inter,
15072 piece.skip,
15073 );
15074 }
15075 blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
15076 }
15077 symbol => {
15078 let horz = symbol == 1;
15079 if horz {
15080 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15081 } else {
15082 B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15083 }
15084 let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
15085 for (i, half) in halves.iter().enumerate() {
15086 let (mr, mc) = if horz {
15087 (root_r * 16 + i * 16, root_c * 16)
15088 } else {
15089 (root_r * 16, root_c * 16 + i * 16)
15090 };
15091 record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
15092 }
15093 blocks.push((at, Quadrant::Rect128(horz, halves)));
15094 }
15095 }
15096 for q in 1..16 {
15097 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
15098 blocks.push((r32 * cols + c32, Quadrant::Covered));
15099 }
15100 }
15101 }
15102 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
15103 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
15104 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
15105 for (&out, tile) in chroma_out.iter().zip(&chroma) {
15106 copy_rect(
15107 out,
15108 &tile.reconstruction,
15109 frame_width / 2,
15110 x0 / 2,
15111 y0 / 2,
15112 x1.div_ceil(2),
15113 y1.div_ceil(2),
15114 );
15115 }
15116 Ok(blocks)
15117 };
15118 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
15119 .into_iter()
15120 .flatten()
15121 {
15122 blocks[at] = quadrant;
15123 }
15124
15125 // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
15126 // superblock roots the search left whole, so a flat BD result is
15127 // attributable (class `gate-blind-to-feature`). A key frame codes none:
15128 // only the inter writer has a 128x128 block.
15129 if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
15130 let whole = blocks
15131 .iter()
15132 .filter(|q| matches!(q, Quadrant::Whole128(_)))
15133 .count();
15134 let roots = blocks
15135 .iter()
15136 .filter(|q| !matches!(q, Quadrant::Covered))
15137 .count();
15138 // lane-b128r: of those roots, how many code a REAL residual rather
15139 // than the skip-only block lane-b128 shipped -- the fire count this
15140 // arm's own gate row is read against.
15141 let residual = blocks
15142 .iter()
15143 .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
15144 .count();
15145 // lane-b128r: and how many named a second reference (the compound
15146 // arm at the 128 root).
15147 let compound = blocks
15148 .iter()
15149 .filter(
15150 |q| matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some())),
15151 )
15152 .count();
15153 // lane-b128hv: and how many roots took a rect cut instead, per shape
15154 // -- the HORZ/VERT fire count the gate rows are read against.
15155 let horz = blocks
15156 .iter()
15157 .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
15158 .count();
15159 let vert = blocks
15160 .iter()
15161 .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
15162 .count();
15163 let rect_compound = blocks
15164 .iter()
15165 .filter(|q| {
15166 matches!(q, Quadrant::Rect128(_, hs)
15167 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
15168 })
15169 .count();
15170 // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
15171 // .. _VERT_B order -- the per-shape fire count its gate rows are read
15172 // against.
15173 let ab: [usize; 4] = std::array::from_fn(|i| {
15174 blocks
15175 .iter()
15176 .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
15177 .count()
15178 });
15179 eprintln!(
15180 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
15181 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
15182 compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
15183 {roots} coded blocks ({:.1}% of the frame's area at 128)",
15184 ab[0],
15185 ab[1],
15186 ab[2],
15187 ab[3],
15188 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
15189 / blocks.len().max(1) as f64,
15190 );
15191 }
15192 let modes = blocks
15193 .iter()
15194 .flat_map(Quadrant::blocks)
15195 .map(|b| b.mode)
15196 .collect::<Vec<_>>();
15197 let inter_block_share = blocks
15198 .iter()
15199 .flat_map(Quadrant::blocks)
15200 .filter(|b| b.inter.is_some())
15201 .count() as f64
15202 / modes.len() as f64;
15203 for block in blocks.iter().flat_map(Quadrant::blocks) {
15204 if let Some(info) = block.inter {
15205 let r = (info.ref_frame as usize).min(7);
15206 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15207 }
15208 }
15209 #[cfg(test)]
15210 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
15211 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
15212 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
15213 // next frame's writer starts from them -- exactly what
15214 // `crate::stream::stored_cdfs_for` hands the decoder.
15215 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
15216 let mut cdfs = start_cdfs
15217 .cloned()
15218 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
15219 // lane-txi: set per frame, never inherited from the snapshot the
15220 // previous frame stored -- the content gate can flip the bit between
15221 // frames (class `per-tile-state-not-reset`).
15222 cdfs.reduced_tx_set = header.reduced_tx_set;
15223 let start_cdfs = CdfSnapshot(cdfs);
15224 let reference_select_bit = header.reference_select;
15225 let switchable_motion_mode = header.is_motion_mode_switchable;
15226 let warped_motion = header.allow_warped_motion;
15227 let order_hint_bits = seq.order_hint_bits;
15228 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
15229 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
15230 // What this frame stores is the LARGEST tile's end-of-tile tables --
15231 // its own header's `context_update_tile_id` (spec 7.20), which
15232 // `tile_info_of` set to exactly that tile.
15233 let store_tile = layout.largest_tile();
15234 let end_cdfs = std::cell::RefCell::new(None);
15235 // As in `encode_key_frame_inner`: every tile starts from this frame's
15236 // own tables, so no tile depends on any other.
15237 let code_tiles = |bits: u8,
15238 sb_cols: usize,
15239 cdef_grid: &[u8],
15240 units: &[Option<crate::restoration::WienerInfo>]|
15241 -> Result<Vec<Vec<u8>>> {
15242 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
15243 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
15244 crate::tile::arm_delta_q(
15245 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
15246 sb_cols,
15247 sb_q.clone().unwrap_or_default(),
15248 base_q_idx,
15249 );
15250 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
15251 crate::tile::arm_sb128(sb128_on());
15252 crate::tile::arm_sign_bias(sign_bias);
15253 // Thread-locals: every tile job arms its own worker.
15254 crate::tile::arm_reference_select(reference_select_bit);
15255 crate::tile::arm_motion_mode(switchable_motion_mode);
15256 crate::tile::arm_warped_motion(warped_motion);
15257 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
15258 crate::tile::arm_high_precision_mv(hp_mv);
15259 crate::tile::arm_screen(screen);
15260 crate::tile::arm_frame_mi_dims(frame_mi_dims);
15261 crate::tile::arm_filter_intra(filter_intra_on());
15262 let mut cdfs = start_cdfs.0.clone();
15263 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
15264 // Each tile's own MV grid: a candidate scan never reaches past
15265 // the tile's bounds, so a grid holding only this tile's own
15266 // blocks reads exactly as the decoder's frame-wide one does
15267 // under `MiGrid::set_tile_bounds`.
15268 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
15269 mv_grid.set_sign_bias(sign_bias);
15270 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
15271 mi_cols,
15272 mi_rows,
15273 base_q_idx,
15274 &blocks,
15275 tx_select,
15276 &mut cdfs,
15277 layout.rect(index),
15278 &mut mv_grid,
15279 )?;
15280 Ok((bytes, Some(cdfs)))
15281 })?;
15282 if let Some(cdfs) = stored {
15283 *end_cdfs.borrow_mut() = Some(cdfs);
15284 }
15285 Ok(out)
15286 };
15287 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
15288 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
15289 // this tile against the same single-slot reference this encoder predicted
15290 // from, under each candidate level.
15291 // The reference a DECODER holds is this frame's cropped size, not the
15292 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
15293 // reference whose height is not the header's own `frame_height` (spec
15294 // 7.9's compatible-size rule), and the chained-decode round trips prove
15295 // the two predict identically.
15296 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
15297 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
15298 reference.clone()
15299 } else {
15300 Picture {
15301 width: fw,
15302 height: fh,
15303 y: crop_plane(&reference.y, reference.width, fw, fh),
15304 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
15305 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
15306 }
15307 };
15308 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
15309 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
15310 // blocks may name GOLDEN needs that plane too, cropped the same way.
15311 let trial_golden = golden.map(|g| {
15312 if (g.width, g.height) == (fw, fh) {
15313 g.clone()
15314 } else {
15315 Picture {
15316 width: fw,
15317 height: fh,
15318 y: crop_plane(&g.y, g.width, fw, fh),
15319 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
15320 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
15321 }
15322 }
15323 });
15324 let trial_altref = altref.map(|a| {
15325 if (a.width, a.height) == (fw, fh) {
15326 a.clone()
15327 } else {
15328 Picture {
15329 width: fw,
15330 height: fh,
15331 y: crop_plane(&a.y, a.width, fw, fh),
15332 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
15333 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
15334 }
15335 }
15336 });
15337 let trial_last2 = last2.map(|l| {
15338 if (l.width, l.height) == (fw, fh) {
15339 l.clone()
15340 } else {
15341 Picture {
15342 width: fw,
15343 height: fh,
15344 y: crop_plane(&l.y, l.width, fw, fh),
15345 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
15346 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
15347 }
15348 }
15349 });
15350 let mut refs: [Option<&Picture>; 8] = [None; 8];
15351 refs[1] = Some(&trial_ref);
15352 refs[2] = trial_last2.as_ref();
15353 refs[4] = trial_golden.as_ref();
15354 refs[7] = trial_altref.as_ref();
15355 let refpix = crate::decode::RefPix::ready(refs);
15356 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
15357 // sum the block search believed it was minimising. Against the
15358 // post-filter per-frame PSNR the gate prints, this separates a trial
15359 // whose reconstruction is a lie from a filter stage that undoes the win.
15360 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
15361 let sse: u64 = luma
15362 .reconstruction
15363 .chunks(luma.width)
15364 .take(luma.true_height)
15365 .zip(picture_y8.chunks(luma.width))
15366 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
15367 .map(|(&r, &s)| {
15368 let d = i64::from(r) - i64::from(s);
15369 (d * d) as u64
15370 })
15371 .sum();
15372 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
15373 }
15374 let post = |luma: &Plane<'_>, tag: &str| {
15375 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
15376 return;
15377 }
15378 let sse: u64 = luma
15379 .reconstruction
15380 .chunks(luma.width)
15381 .take(luma.true_height)
15382 .zip(picture_y8.chunks(luma.width))
15383 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
15384 .map(|(&r, &s)| {
15385 let d = i64::from(r) - i64::from(s);
15386 (d * d) as u64
15387 })
15388 .sum();
15389 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
15390 };
15391 pick_and_apply_filters(
15392 &mut header,
15393 &mut luma,
15394 &mut chroma,
15395 [&picture_y8, &picture_u8, &picture_v8],
15396 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
15397 // this frame's own `tx_select`, so the search runs under inter
15398 // `TxMode::Select` too (it used to skip and leave every inter frame
15399 // unfiltered once Select became the default).
15400 true,
15401 &mut tiles,
15402 search.lambda,
15403 fctx,
15404 &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows),
15405 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
15406 // are what the NEXT frame writes from, so the winning re-code
15407 // publishes its own into `end_cdfs` -- the first write's are stale
15408 // the moment a second tile is coded.
15409 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
15410 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
15411 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
15412 crate::decode::decode_inter_frame_tiles_lr(
15413 &payloads,
15414 &header_tile_info,
15415 h.mi_cols,
15416 h.mi_rows,
15417 base_q_idx,
15418 h.frame_width,
15419 h.frame_height,
15420 &refpix,
15421 cdef,
15422 lf,
15423 h.allow_high_precision_mv,
15424 h.force_integer_mv,
15425 Some(fctx.interp_filter.get()),
15426 seq.enable_dual_filter,
15427 h.reference_select,
15428 // lane-txi: this frame's own bit, not the hardcoded `true`
15429 // the wrapper used to pass.
15430 h.reduced_tx_set,
15431 tx_select,
15432 lr,
15433 // The trial decode re-reads the tile the writer just wrote,
15434 // so it starts from the same tables the writer did (this
15435 // frame's `start_cdfs`), not from the defaults.
15436 Some(start_cdfs.0.clone()),
15437 sign_bias,
15438 h.allow_screen_content_tools,
15439 switchable_motion_mode,
15440 h.allow_warped_motion,
15441 seq.enable_filter_intra,
15442 // lane-deltaq: this frame's own delta_q/delta_lf params, so
15443 // the trial decode reads the per-superblock `delta_qindex`
15444 // syntax the writer just wrote.
15445 h.delta.clone(),
15446 fctx,
15447 )
15448 },
15449 )?;
15450 post(&luma, "EC_POSTFILTER");
15451 let mut cdfs = end_cdfs
15452 .into_inner()
15453 .unwrap_or_else(|| start_cdfs.0.clone());
15454 cdfs.reset_counts();
15455 let next_cdfs = CdfSnapshot(cdfs);
15456 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
15457 header.tile_info.tile_size_bytes = tile_size_bytes;
15458 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
15459 let mut stream = temporal_delimiter();
15460 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
15461
15462 let [u, v] = chroma;
15463 Ok(Encoded {
15464 stream,
15465 modes,
15466 inter_block_share,
15467 reconstruction: Picture {
15468 width: luma.width,
15469 height: luma.height,
15470 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15471 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15472 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15473 },
15474 tile,
15475 mi_cols: header.mi_cols,
15476 mi_rows: header.mi_rows,
15477 base_q_idx,
15478 tx_select,
15479 switchable_motion_mode,
15480 screen,
15481 reduced_tx_set: header.reduced_tx_set,
15482 start_cdfs,
15483 next_cdfs,
15484 loop_filter: header.loop_filter,
15485 cdef: header.cdef,
15486 loop_restoration: header.loop_restoration,
15487 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
15488 // intra frames only).
15489 allow_intrabc: false,
15490 delta: header.delta.clone(),
15491 })
15492}
15493
15494/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
15495/// frame's temporal unit followed by one inter frame's temporal unit per
15496/// remaining picture, all sharing the key frame's sequence header -- and
15497/// each frame's own [`Encoded`], in coding order.
15498#[derive(Clone, Debug)]
15499pub struct EncodedSequence {
15500 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
15501 /// sequence header and the key frame) followed by each later frame's
15502 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
15503 /// the sequence header the key frame carried).
15504 pub stream: Vec<u8>,
15505 /// One entry per picture, in DISPLAY order — the order a decoder outputs
15506 /// them and the order `pictures` came in. Without a pyramid that is also
15507 /// the coding order; with one the two differ, and `coding_order` is the
15508 /// map between them.
15509 pub frames: Vec<Encoded>,
15510 /// The index into `frames` of each coded frame, in CODING order — what a
15511 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
15512 /// `0..frames.len()` on the flat path.
15513 pub coding_order: Vec<usize>,
15514}
15515
15516/// Encodes a sequence of pictures as a key frame followed by one inter frame
15517/// per remaining picture, each predicting from the previous frame's own
15518/// decoded reconstruction — never from the source, which is what a decoder
15519/// cannot see. Every picture must be the same even size (any even width and
15520/// height — each is padded to a whole number of 64x64 superblocks
15521/// internally, which is what lets an inter frame's reference always match
15522/// the frame being coded against it), and `pictures` must be non-empty.
15523///
15524/// # Errors
15525/// Returns an error when `pictures` is empty, when any picture besides the
15526/// first is not the same size as the first, or under the same conditions
15527/// [`encode_key_frame`] and the inter frame path do.
15528pub(crate) fn encode_sequence_with_ctx(
15529 pictures: &[Picture],
15530 base_q_idx: u8,
15531 deadzone: f64,
15532 fctx: &crate::decode::FrameCtx,
15533) -> Result<EncodedSequence> {
15534 let Some((first, rest)) = pictures.split_first() else {
15535 return Err(Error::unsupported(
15536 "AV1 encode",
15537 "a sequence needs at least one picture",
15538 ));
15539 };
15540 first.check_even()?;
15541 let render = (first.width, first.height);
15542 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
15543 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
15544 // the leaves that predict backward off it, and a `show_existing_frame`
15545 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
15546 // an A/B. Screen content stays flat (the content gate in
15547 // `Av1Encoder::encode_frames`, whose detector this asks first so the
15548 // whole sequence path is decided in one place), and so does a run that
15549 // asks for a quantizer rounding offset the facade does not carry: the
15550 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
15551 // the ablations' -- must keep the flat path rather than be silently
15552 // ignored.
15553 //
15554 // The reordering itself is NOT reimplemented here: it is the facade's
15555 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
15556 // called with this sequence's shape, so the two paths cannot drift.
15557 let pyramid = crate::encoder::Pyramid::from_env()
15558 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
15559 .filter(|_| !picture_is_screen(first));
15560 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
15561 if let Some(pyramid) = pyramid {
15562 for picture in rest {
15563 picture.check_even()?;
15564 if (picture.width, picture.height) != render {
15565 return Err(Error::unsupported(
15566 "AV1 encode",
15567 "every picture in a sequence must be the same size as the first",
15568 ));
15569 }
15570 }
15571 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
15572 pictures,
15573 base_q_idx,
15574 pyramid,
15575 armed_tiles(),
15576 );
15577 }
15578 // The key frame and every inter frame after it are coded at the same
15579 // padded size, so the reference each inter frame predicts from -- the
15580 // previous frame's own uncropped reconstruction, at the size a decoder's
15581 // reference buffer actually holds -- always matches the frame being
15582 // coded against it.
15583 let key = encode_key_frame_inner(
15584 &first.padded_to(SUPERBLOCK),
15585 base_q_idx,
15586 deadzone,
15587 &KEY_FRAME_MODES,
15588 split_blocks(),
15589 render,
15590 unspecified_color_config(),
15591 fctx,
15592 )?;
15593 let mut stream = key.stream.clone();
15594 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
15595 // key frame refreshes every slot, each inter frame only slot 0), which is
15596 // what `GOLDEN_FRAME` names.
15597 let golden = key.reconstruction.clone();
15598 // The frame two back, once there is one that is not the key frame
15599 // itself (which `GOLDEN_FRAME` already names).
15600 let mut prev2: Option<Picture> = None;
15601 let mut carried = key.next_cdfs.clone();
15602 let mut reference = key.reconstruction.clone();
15603 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
15604 for (i, picture) in rest.iter().enumerate() {
15605 picture.check_even()?;
15606 // lane-av1tpl2: the lookahead window the per-block lambda weighting
15607 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
15608 // sources at this frame's coded (padded) size. The tail of the
15609 // sequence gets a shorter window, and the last frame none at all.
15610 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
15611 .iter()
15612 .take(tpl_depth() - 1)
15613 .map(|n| n.padded_to(SUPERBLOCK))
15614 .collect();
15615 if (picture.width, picture.height) != render {
15616 return Err(Error::unsupported(
15617 "AV1 encode",
15618 "every picture in a sequence must be the same size as the first",
15619 ));
15620 }
15621 let order_hint = (i + 1) as u32;
15622 let inter = encode_inter_frame(
15623 &picture.padded_to(SUPERBLOCK),
15624 &reference,
15625 base_q_idx,
15626 deadzone,
15627 order_hint,
15628 flat_order_hints(order_hint, 0, prev2.is_some()),
15629 render,
15630 Some(&carried.0),
15631 Some(&golden),
15632 prev2.as_ref(),
15633 None,
15634 fctx,
15635 None,
15636 &lookahead,
15637 )?;
15638 stream.extend_from_slice(&inter.stream);
15639 carried = inter.next_cdfs.clone();
15640 prev2 = Some(std::mem::replace(
15641 &mut reference,
15642 inter.reconstruction.clone(),
15643 ));
15644 frames.push(crop_encoded(&inter, render.0, render.1));
15645 }
15646 Ok(EncodedSequence {
15647 stream,
15648 coding_order: (0..frames.len()).collect(),
15649 frames,
15650 })
15651}
15652
15653#[cfg(test)]
15654mod tests {
15655
15656 /// Every (site, frame type, block side) the census can be called with
15657 /// lands in its own ten-counter bucket, inside the array (class
15658 /// `enumerate-table-domain`: an off-by-one here would silently add two
15659 /// sites' trials together).
15660 #[test]
15661 fn the_split_census_buckets_are_distinct_and_in_bounds() {
15662 let mut seen = std::collections::BTreeSet::new();
15663 for site in 0..2 {
15664 for key in [true, false] {
15665 for side in [8usize, 16, 32, 64] {
15666 let base = super::split_census_base(site, key, side);
15667 assert!(
15668 base + 10 <= super::SPLIT_CENSUS.len(),
15669 "{site} {key} {side}"
15670 );
15671 assert!(seen.insert(base), "{site} {key} {side} collides");
15672 }
15673 }
15674 }
15675 assert_eq!(seen.len(), 16);
15676 }
15677
15678 /// An [`crate::mvstack::MvStack`] with every context at zero and no
15679 /// neighbours, for the pricer tests below to fill the one band each of
15680 /// them is about.
15681 /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
15682 /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
15683 /// against the same stack -- an offer the writer clamps prices the
15684 /// residual against a predictor the decoder never derives, which is the
15685 /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
15686 /// side, so the stream stays legal; here the pricer's own offer set is
15687 /// enumerated, class `enumerate-table-domain`).
15688 ///
15689 /// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt
15690 /// r2, 2026-09-29). It replaces the clip gate
15691 /// `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`,
15692 /// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a
15693 /// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable
15694 /// while the invariant above holds, so no recipe could ever satisfy it.
15695 /// Deletion loses no coverage on either half:
15696 /// * the clamp half -- this test IS the coverage, and it is strictly
15697 /// stronger than any clip gate: it enumerates the pricer's whole offer
15698 /// set against the writer's rule for every stack size 0..=4, and larger
15699 /// stacks add entries the pricers never offer (`best_new_mv_syntax`
15700 /// breaks at `entries.len() <= idx` for `idx > 0`, so indices 3/4 are
15701 /// unreachable at ANY stack size), which is why 0..=4 bounds the
15702 /// domain rather than sampling it;
15703 /// * the pixel half -- the deleted gate's own decode-vs-encoder-
15704 /// reconstruction compare on a 1280x768 sb128 sequence is already made
15705 /// four times over, by `a_128_superblock_clip_whose_root_search_codes_
15706 /// 128x128_blocks_decodes_exact`,
15707 /// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`,
15708 /// `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact`
15709 /// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
15710 /// (same geometry, same `force_sb128(true)`, same own-reconstruction AND
15711 /// ffmpeg compare).
15712 /// MEASURED before deleting (153 clip x size x frame-count x q combinations,
15713 /// `enc_probe`): `tile::drl_clamp_hits()` = 0 on every one. MUTATION PROOF
15714 /// the clip was never the variable: widening `best_new_mv_syntax`'s offer
15715 /// set to `0..5` fires the counter immediately (9/2/2/1 on
15716 /// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8,
15717 /// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp`
15718 /// and `DRL_CLAMP_HITS` are KEPT as the tripwire for the owning fix
15719 /// (`deferred(unblock: the DRL owner widens the pricer past the writer's
15720 /// `start + 2` ceiling, or retires the counter)`) -- this test will go red
15721 /// the moment either happens, which is the signal to re-open the cell.
15722 ///
15723 /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
15724 #[test]
15725 fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
15726 for n in 0..=4usize {
15727 let mut stack = bare_stack();
15728 for i in 0..n {
15729 stack.entries.push(crate::mvstack::StackEntry {
15730 mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
15731 weight: 1,
15732 });
15733 stack.drl_ctx.push(0);
15734 }
15735 stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
15736 stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
15737 stack.pred_mv = stack.nearest_mv;
15738 // Aim the vector at each entry in turn, so every index the offer
15739 // set holds is the one that wins at least once.
15740 for target in 0..n.max(1) {
15741 let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
15742 let (_, idx) =
15743 best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable");
15744 let idx = usize::from(idx);
15745 assert_eq!(
15746 crate::tile::signalled_drl_idx(n, 0, idx),
15747 idx,
15748 "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
15749 );
15750 }
15751 // The NEARMV arm's own offer set (`search_inter_block`,
15752 // `search_skip_64`): indices 1 and 2, offered only when the stack
15753 // really holds that entry.
15754 for idx in 1..=2usize {
15755 if stack.entries.get(idx).is_some() {
15756 assert_eq!(
15757 crate::tile::signalled_drl_idx(n, 1, idx),
15758 idx,
15759 "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
15760 );
15761 }
15762 }
15763 }
15764 }
15765
15766 fn bare_stack() -> crate::mvstack::MvStack {
15767 crate::mvstack::MvStack {
15768 entries: Default::default(),
15769 nearest_mv: (0, 0),
15770 near_mv: (0, 0),
15771 pred_mv: (0, 0),
15772 new_mv_ctx: 0,
15773 ref_mv_ctx: 0,
15774 zero_mv_ctx: 0,
15775 drl_ctx: Default::default(),
15776 above_refs: (None, None),
15777 left_refs: (None, None),
15778 above_nbr: None,
15779 left_nbr: None,
15780 above_skip: false,
15781 left_skip: false,
15782 }
15783 }
15784
15785 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
15786 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
15787 /// own neighbour-derived context. Red before lane-ctx, where the pricer
15788 /// spent four constants at CDF row 0 that assumed the pair was
15789 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
15790 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
15791 #[test]
15792 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
15793 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
15794 use crate::encode::symbol_bits as b;
15795 use crate::mvstack::{
15796 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
15797 LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
15798 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
15799 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
15800 };
15801 // (pair, unidirectional?, the tree's symbols as (table, p index,
15802 // context selector, value)) -- transcribed from the writer.
15803 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
15804 type Sym = (char, usize, usize, usize);
15805 let cases: [((i8, i8), bool, &[Sym]); 7] = [
15806 (
15807 (LAST_FRAME, LAST2_FRAME),
15808 true,
15809 &[('u', 0, 1, 0), ('u', 1, 7, 0)],
15810 ),
15811 (
15812 (LAST_FRAME, LAST3_FRAME),
15813 true,
15814 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
15815 ),
15816 (
15817 (LAST_FRAME, GOLDEN_FRAME),
15818 true,
15819 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
15820 ),
15821 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
15822 (
15823 (LAST_FRAME, ALTREF_FRAME),
15824 false,
15825 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
15826 ),
15827 (
15828 (LAST_FRAME, BWDREF_FRAME),
15829 false,
15830 &[
15831 ('c', 0, 3, 0),
15832 ('c', 1, 4, 0),
15833 ('b', 0, 2, 0),
15834 ('b', 1, 6, 0),
15835 ],
15836 ),
15837 (
15838 (LAST_FRAME, ALTREF2_FRAME),
15839 false,
15840 &[
15841 ('c', 0, 3, 0),
15842 ('c', 1, 4, 0),
15843 ('b', 0, 2, 0),
15844 ('b', 1, 6, 1),
15845 ],
15846 ),
15847 ];
15848 let nbr = |ref0, ref1: Option<i8>| {
15849 Some(NeighbourRef {
15850 is_inter: true,
15851 ref0,
15852 ref1,
15853 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
15854 })
15855 };
15856 // No neighbours (every context zero), then a mixed pair that puts the
15857 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
15858 for (above_nbr, left_nbr, above_refs, left_refs) in [
15859 (None, None, (None, None), (None, None)),
15860 (
15861 nbr(LAST_FRAME, None),
15862 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
15863 (Some(LAST_FRAME), None),
15864 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
15865 ),
15866 ] {
15867 let stack = crate::mvstack::MvStack {
15868 above_nbr,
15869 left_nbr,
15870 above_refs,
15871 left_refs,
15872 ..bare_stack()
15873 };
15874 let (a, a1) = above_refs;
15875 let (l, l1) = left_refs;
15876 let ctx_of = |sel: usize| match sel {
15877 1 => single_ref_p1_ctx(a, a1, l, l1),
15878 2 => single_ref_p2_ctx(a, a1, l, l1),
15879 3 => single_ref_p3_ctx(a, a1, l, l1),
15880 4 => single_ref_p4_ctx(a, a1, l, l1),
15881 5 => single_ref_p5_ctx(a, a1, l, l1),
15882 6 => single_ref_p6_ctx(a, a1, l, l1),
15883 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
15884 };
15885 for (pair, unidir, symbols) in cases {
15886 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
15887 + b(
15888 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
15889 usize::from(!unidir),
15890 );
15891 for &(table, p, sel, v) in symbols {
15892 let row = ctx_of(sel);
15893 want += match table {
15894 'u' => b(&UNI_COMP_REF[row][p], v),
15895 'c' => b(&COMP_REF[row][p], v),
15896 _ => b(&COMP_BWDREF[row][p], v),
15897 };
15898 }
15899 let got = super::compound_ref_bits(pair, &stack);
15900 assert!(
15901 (got - want).abs() < 1e-9,
15902 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
15903 priced {got} bits, writer codes {want}"
15904 );
15905 }
15906 }
15907 }
15908
15909 /// The `skip` and `is_inter` symbols are priced at the SAME context
15910 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
15911 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
15912 /// on every neighbour configuration whose context is not zero (class
15913 /// pricer-context-zero).
15914 #[test]
15915 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
15916 use crate::cdf::{INTRA_INTER, SKIP};
15917 use crate::encode::symbol_bits as b;
15918 use crate::mvstack::NeighbourRef;
15919 let nbr = |is_inter| NeighbourRef {
15920 is_inter,
15921 ref0: if is_inter {
15922 crate::mvstack::LAST_FRAME
15923 } else {
15924 0
15925 },
15926 ref1: None,
15927 uni: false,
15928 };
15929 for (above, left, above_skip, left_skip) in [
15930 (None, None, false, false),
15931 (Some(nbr(true)), Some(nbr(true)), true, false),
15932 (Some(nbr(false)), Some(nbr(false)), true, true),
15933 (Some(nbr(false)), None, false, true),
15934 (None, Some(nbr(true)), true, true),
15935 ] {
15936 let stack = crate::mvstack::MvStack {
15937 above_nbr: above,
15938 left_nbr: left,
15939 above_skip,
15940 left_skip,
15941 ..bare_stack()
15942 };
15943 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
15944 let ii_ctx = crate::tile::intra_inter_ctx(
15945 above.is_some(),
15946 left.is_some(),
15947 above.is_some_and(|n| n.is_inter),
15948 left.is_some_and(|n| n.is_inter),
15949 );
15950 for v in [false, true] {
15951 let (got, want) = (
15952 super::skip_bits_at(&stack, v),
15953 b(&SKIP[skip_ctx], usize::from(v)),
15954 );
15955 assert!(
15956 (got - want).abs() < 1e-9,
15957 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
15958 );
15959 let (got, want) = (
15960 super::intra_inter_bits_at(&stack, v),
15961 b(&INTRA_INTER[ii_ctx], usize::from(v)),
15962 );
15963 assert!(
15964 (got - want).abs() < 1e-9,
15965 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
15966 );
15967 }
15968 }
15969 }
15970
15971 /// [`super::single_ref_bits`] pays exactly what tile.rs'
15972 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
15973 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
15974 /// the context that symbol's own `single_ref_p*_ctx` derives from the
15975 /// block's above/left neighbours. Red before lane-pricer, where every
15976 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
15977 #[test]
15978 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
15979 use crate::cdf::SINGLE_REF as SR;
15980 use crate::encode::symbol_bits as b;
15981 use crate::mvstack::{
15982 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
15983 LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
15984 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
15985 };
15986 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
15987 above_refs,
15988 left_refs,
15989 above_nbr,
15990 left_nbr,
15991 ..bare_stack()
15992 };
15993 let nbr = |ref0, ref1| {
15994 Some(crate::mvstack::NeighbourRef {
15995 is_inter: true,
15996 ref0,
15997 ref1,
15998 uni: false,
15999 })
16000 };
16001 // (reference, the symbols `write_single_ref` emits as (p index, value))
16002 let cases: [(i8, &[(usize, usize)]); 7] = [
16003 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
16004 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
16005 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
16006 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
16007 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
16008 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
16009 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
16010 ];
16011 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
16012 // that puts every p* context on a different row -- the second with a
16013 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
16014 // off row 0.
16015 for (above_refs, left_refs, above_nbr, left_nbr) in [
16016 ((None, None), (None, None), None, None),
16017 (
16018 (Some(LAST_FRAME), None),
16019 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
16020 nbr(LAST_FRAME, None),
16021 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
16022 ),
16023 ] {
16024 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
16025 let (a, a1) = above_refs;
16026 let (l, l1) = left_refs;
16027 let ctx_of = |p: usize| match p {
16028 0 => single_ref_p1_ctx(a, a1, l, l1),
16029 1 => single_ref_p2_ctx(a, a1, l, l1),
16030 2 => single_ref_p3_ctx(a, a1, l, l1),
16031 3 => single_ref_p4_ctx(a, a1, l, l1),
16032 4 => single_ref_p5_ctx(a, a1, l, l1),
16033 _ => single_ref_p6_ctx(a, a1, l, l1),
16034 };
16035 for (ref_frame, symbols) in cases {
16036 // Plus the `comp_mode = 0` symbol the writer codes ahead of
16037 // the reference syntax on a `reference_select` frame.
16038 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
16039 if super::reference_select() {
16040 want += b(
16041 &crate::cdf::COMP_MODE
16042 [crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)],
16043 0,
16044 );
16045 }
16046 let got = super::single_ref_bits(ref_frame, &stack);
16047 assert!(
16048 (got - want).abs() < 1e-9,
16049 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
16050 priced {got} bits, writer codes {want}"
16051 );
16052 }
16053 }
16054 }
16055
16056 /// lane-av1tpl2's propagated map, on the two properties every decision
16057 /// under it rests on: a frame the whole lookahead window repeats exactly
16058 /// (uniform texture) leans on every cell alike, so every factor is 1 and
16059 /// the weighting is a no-op; and where the window really does save bits
16060 /// by predicting -- the textured half of a frame whose other half is
16061 /// flat -- the factor FALLS below 1, i.e. that half is coded more
16062 /// distortion-averse than the half nothing gains from.
16063 /// The distortion metric itself (lane-sse): a block the true frame edge
16064 /// cuts through is scored over its INSIDE part only, so a difference that
16065 /// lives entirely in the padding costs nothing and a block wholly past
16066 /// the edge scores zero. Before this, the search ranked modes,
16067 /// transforms and partition trees on samples the display crop throws
16068 /// away -- which lane-b64b had fixed for the 64x64 root alone.
16069 #[test]
16070 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
16071 // A 40x40 true frame on a 64x64 padded coding surface.
16072 let source = vec![10u8; 64 * 64];
16073 let plane = fresh_plane(&source, 64, 64, 40, 40);
16074 let mut reconstruction = vec![10u8; 64 * 64];
16075 // Off by 190 at (50, 50) -- past the true edge in both axes.
16076 reconstruction[50 * 64 + 50] = 200;
16077 assert_eq!(
16078 plane.block_sse(0, 0, 64, &reconstruction),
16079 0.0,
16080 "padding was scored"
16081 );
16082 // Off by 10 at (39, 39) -- the last sample the decoder shows.
16083 reconstruction[39 * 64 + 39] = 20;
16084 assert_eq!(
16085 plane.block_sse(0, 0, 64, &reconstruction),
16086 100.0,
16087 "inside was not scored"
16088 );
16089 // A 16x16 block whose every sample is padding.
16090 let block = vec![200u8; 16 * 16];
16091 assert_eq!(
16092 plane.block_sse(48, 0, 16, &block),
16093 0.0,
16094 "a block past the edge scored"
16095 );
16096 // A 16x16 block the edge cuts: 8 of its columns are inside.
16097 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
16098 }
16099
16100 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
16101 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
16102 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
16103 #[test]
16104 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
16105 let (base, res) = (162u8, 4i32);
16106 let rf = 2.0;
16107 // A superblock the window leans on more than the frame average is
16108 // coded FINER (lower qindex); a slack one coarser; the average one
16109 // exactly at the base.
16110 assert!(
16111 super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base,
16112 "leaned-on SB must go finer"
16113 );
16114 assert!(
16115 super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base,
16116 "idle SB must go coarser"
16117 );
16118 assert_eq!(
16119 super::deltaq_libaom(base, rf, rf, 1.0, res),
16120 base,
16121 "the average SB moves 0"
16122 );
16123 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
16124 let max = ((res * 9 - 1) / res) * res;
16125 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
16126 for k in [0.5f64, 1.0, 1.5] {
16127 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
16128 let d = q - i32::from(base);
16129 assert_eq!(
16130 d % res,
16131 0,
16132 "r={r} k={k}: offset {d} is not a whole {res}-step"
16133 );
16134 assert!(
16135 d.abs() <= max,
16136 "r={r} k={k}: offset {d} past libaom's +-{max}"
16137 );
16138 }
16139 }
16140 // The clamp is REACHED from both ends, so the bound is a real bound
16141 // and not a formula that never gets there.
16142 assert_eq!(
16143 i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base),
16144 -max
16145 );
16146 assert_eq!(
16147 i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base),
16148 max
16149 );
16150 // A stronger `k` never moves less than a weaker one.
16151 let d = |k: f64| {
16152 (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs()
16153 };
16154 assert!(
16155 d(0.5) <= d(1.0) && d(1.0) <= d(1.5),
16156 "strength must be monotone: {} {} {}",
16157 d(0.5),
16158 d(1.0),
16159 d(1.5)
16160 );
16161 // The frame reference is libaom's log-mean: flat in, the same value out.
16162 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
16163 }
16164
16165 /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
16166 /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
16167 /// shipped default, and the multiplier reaches the strength.
16168 #[test]
16169 fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
16170 let d = crate::speed::DQ_LEVEL_K;
16171 assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
16172 assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
16173 // Short and broken fields fall back per SLOT, not per spec.
16174 assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
16175 assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
16176 assert_eq!(super::DqLevel::TopArf as usize, 0);
16177 assert_eq!(super::DqLevel::MidArf as usize, 1);
16178 assert_eq!(super::DqLevel::Leaf as usize, 2);
16179 }
16180
16181 #[test]
16182 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
16183 // Four 64x64 superblocks across: the shipped map forms its ratio per
16184 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
16185 // only ever produce one ratio -- and one ratio, mean-normalised, is
16186 // the flat map, whatever the content underneath it.
16187 let (w, h) = (256usize, 64usize);
16188 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
16189 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
16190 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
16191 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
16192 for (i, &v) in f.iter().enumerate() {
16193 assert!(
16194 (v - 1.0).abs() < 1e-6,
16195 "cell {i} factor {v}, a flat map must move no lambda"
16196 );
16197 }
16198
16199 // Left half textured, right half constant: the window saves bits
16200 // predicting the left half and nothing at all on the right.
16201 let split: Vec<u8> = (0..w * h)
16202 .map(|i| {
16203 if i % w < w / 2 {
16204 ((i * 37) % 251) as u8
16205 } else {
16206 128
16207 }
16208 })
16209 .collect();
16210 let frames: Vec<&[u8]> = vec![&split, &split, &split];
16211 let cells_x = w / 16;
16212 for k in [0.25f64, 0.5, 1.0, 2.0] {
16213 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
16214 for r in 0..h / 16 {
16215 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
16216 assert!(
16217 lean < 1.0,
16218 "k={k} row {r}: leaned-on cell factor {lean} must be < 1"
16219 );
16220 assert!(
16221 idle > 1.0,
16222 "k={k} row {r}: idle cell factor {idle} must be > 1"
16223 );
16224 }
16225 }
16226 }
16227
16228 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
16229 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
16230 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
16231 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
16232 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
16233 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
16234 /// only a quarter of the 16x8 table and read the wrong byte for every
16235 /// block row but the first (silently wrong above-right/below-left
16236 /// availability -- wrong pixels, no error).
16237 #[test]
16238 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
16239 for (bw, bh) in [
16240 (16usize, 8usize),
16241 (8, 16),
16242 (32, 16),
16243 (16, 32),
16244 (64, 32),
16245 (32, 64),
16246 ] {
16247 let (bw_log2, bh_log2) = (
16248 (bw / 4).trailing_zeros() as usize,
16249 (bh / 4).trailing_zeros() as usize,
16250 );
16251 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
16252 for (name, table) in [
16253 ("has_tr", rect_reach_tables(bw, bh).0),
16254 ("has_bl", rect_reach_tables(bw, bh).1),
16255 ] {
16256 assert_eq!(
16257 table.len() * 8,
16258 rows * cols,
16259 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
16260 );
16261 let mut seen = vec![0u32; table.len() * 8];
16262 for blk_row in 0..rows {
16263 for blk_col in 0..cols {
16264 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
16265 assert!(
16266 idx < seen.len(),
16267 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
16268 );
16269 seen[idx] += 1;
16270 }
16271 }
16272 assert!(
16273 seen.iter().all(|&n| n == 1),
16274 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
16275 (row stride is not {cols})"
16276 );
16277 }
16278 }
16279 }
16280 use super::*;
16281 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
16282 use crate::probe::run_with_stdin;
16283 use std::process::{Command, Stdio};
16284
16285 /// Every rectangular shape this decoder codes, at every position a block
16286 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
16287 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
16288 /// (`reconintra.c`) answer, whose bodies are ported below.
16289 ///
16290 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
16291 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
16292 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
16293 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
16294 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
16295 /// oracle's own arrays, so a re-routed or truncated table fails here even
16296 /// where the two rows happen to agree.
16297 ///
16298 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
16299 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
16300 /// callers handle by predicting each transform unit as its own block.
16301 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
16302 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
16303 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
16304 /// (the horizontal shapes, which those partitions never produce).
16305 #[test]
16306 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
16307 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
16308 // it pins the 64 reach explicitly instead of following the process's
16309 // own superblock knob (`for_encoder`), which made it red under
16310 // `EC_AV1_SB128=1` for no defect of the code under test.
16311 let fctx = &crate::decode::FrameCtx::new();
16312 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
16313 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
16314 (4, 8, 64, 9280, 64, 550),
16315 (8, 4, 64, 3712, 64, 9630),
16316 (8, 16, 16, 2352, 16, 134),
16317 (16, 8, 16, 960, 16, 2400),
16318 (16, 32, 4, 620, 4, 32),
16319 (32, 16, 4, 32, 4, 184),
16320 (32, 64, 1, 127, 1, 0),
16321 (64, 32, 1, 19, 1, 34),
16322 (4, 16, 32, 5472, 32, 14),
16323 (16, 4, 32, 960, 32, 6464),
16324 (8, 32, 8, 1400, 8, 2),
16325 (32, 8, 8, 32, 8, 1136),
16326 (16, 64, 2, 382, 2, 0),
16327 (64, 16, 2, 4, 2, 84),
16328 ];
16329 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
16330 /// a block whose transform covers it whole (`row_off == col_off == 0`,
16331 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
16332 /// superblock (`sb_mi_size == 16`).
16333 fn libaom_reach(
16334 bw: usize,
16335 bh: usize,
16336 x: usize,
16337 y: usize,
16338 width: usize,
16339 height: usize,
16340 _fctx: &crate::decode::FrameCtx,
16341 ) -> (bool, bool) {
16342 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
16343 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
16344 let sb_mi_size = 16usize;
16345 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
16346 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
16347 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
16348 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
16349 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
16350 // has_top_right: top_available && right_available, then row_off == 0.
16351 let top_right = if y == 0 || x + bw >= width {
16352 false
16353 } else if blk_row_in_sb == 0 {
16354 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
16355 // `bw_unit < bw_unit`, false for a whole-block transform.)
16356 true
16357 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
16358 false
16359 } else {
16360 bit(tr_table)
16361 };
16362 // has_bottom_left: bottom_available && left_available, col_off == 0.
16363 let bottom_left = if x == 0 || y + bh >= height {
16364 false
16365 } else if blk_col_in_sb == 0 {
16366 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
16367 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
16368 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
16369 false
16370 } else {
16371 bit(bl_table)
16372 };
16373 (top_right, bottom_left)
16374 }
16375 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
16376 let (tr, bl) = rect_reach_tables(bw, bh);
16377 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
16378 assert_eq!(
16379 (tr.len(), sum(tr), bl.len(), sum(bl)),
16380 (tr_len, tr_sum, bl_len, bl_sum),
16381 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
16382 );
16383 // Two superblocks across and down, so the superblock-relative
16384 // position (and not the frame position) is what decides.
16385 for sb_y in [0usize, 64] {
16386 for sb_x in [0usize, 64] {
16387 for y in (sb_y..sb_y + 64).step_by(bh) {
16388 for x in (sb_x..sb_x + 64).step_by(bw) {
16389 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
16390 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
16391 assert_eq!(
16392 (got.above_right, got.below_left),
16393 want,
16394 "{bw}x{bh} at ({x}, {y})"
16395 );
16396 }
16397 }
16398 }
16399 }
16400 }
16401 }
16402
16403 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
16404 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
16405 /// aomenc gate decodes its stream through ffmpeg and is meaningless
16406 /// without it -- turns it into a hard failure. Without this the require
16407 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
16408 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
16409 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
16410 fn have_ffmpeg() -> bool {
16411 let present = Command::new("ffmpeg")
16412 .arg("-version")
16413 .stdout(Stdio::null())
16414 .stderr(Stdio::null())
16415 .status()
16416 .is_ok_and(|s| s.success());
16417 assert!(
16418 present
16419 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
16420 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
16421 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
16422 );
16423 present
16424 }
16425
16426 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
16427 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
16428 fn have_encoder(encoder: &str) -> bool {
16429 Command::new("ffmpeg")
16430 .args(["-hide_banner", "-encoders"])
16431 .stderr(Stdio::null())
16432 .output()
16433 .is_ok_and(|o| {
16434 String::from_utf8_lossy(&o.stdout)
16435 .lines()
16436 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
16437 })
16438 }
16439
16440 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
16441 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
16442 let out = run_with_stdin(
16443 Command::new("ffmpeg").args([
16444 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
16445 ]),
16446 stream,
16447 );
16448 assert!(
16449 out.status.success(),
16450 "ffmpeg refused the stream: {}",
16451 String::from_utf8_lossy(&out.stderr)
16452 );
16453 let (luma, chroma) = (width * height, width * height / 4);
16454 assert_eq!(
16455 out.stdout.len(),
16456 luma + 2 * chroma,
16457 "expected one 4:2:0 frame"
16458 );
16459 Picture {
16460 width,
16461 height,
16462 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
16463 u: out.stdout[luma..luma + chroma]
16464 .iter()
16465 .map(|&v| u16::from(v))
16466 .collect(),
16467 v: out.stdout[luma + chroma..]
16468 .iter()
16469 .map(|&v| u16::from(v))
16470 .collect(),
16471 }
16472 }
16473
16474 /// A picture with something of everything in it: a gradient, an edge, a
16475 /// ripple and a block of flat colour, none of them aligned to the block
16476 /// grid.
16477 /// The in-loop filters actually FIRE and the stream still decodes to
16478 /// exactly what the encoder kept as its reconstruction
16479 /// (gate-blind-to-feature: a filter search that always answered "off"
16480 /// would leave every other test just as green, and the BD gate that
16481 /// would notice is `#[ignore]`d).
16482 ///
16483 /// Run:
16484 /// cargo test -p ec-av1 --release --lib -- \
16485 /// encode::tests::the_filter_search_picks_real_filters
16486 #[test]
16487 fn the_filter_search_picks_real_filters() {
16488 let _knobs = crate::speed::knob_read();
16489 let fctx = &crate::decode::FrameCtx::for_encoder();
16490 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
16491 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
16492 let fired = encoded
16493 .frames
16494 .iter()
16495 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
16496 .count();
16497 assert!(
16498 fired > 0,
16499 "no frame of this sequence chose any in-loop filtering: {:?}",
16500 encoded
16501 .frames
16502 .iter()
16503 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
16504 .collect::<Vec<_>>()
16505 );
16506 // The reconstruction the encoder predicts from is the FILTERED one,
16507 // and it is what a decoder of the stream produces -- byte for byte,
16508 // frame for frame.
16509 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
16510 assert_eq!(decoded.len(), encoded.frames.len());
16511 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
16512 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
16513 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
16514 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
16515 }
16516 }
16517
16518 fn test_card(width: usize, height: usize) -> Picture {
16519 let mut picture = Picture::grey(width, height);
16520 for y in 0..height {
16521 for x in 0..width {
16522 let gradient = x as f64 * 200.0 / width as f64;
16523 let ripple = 30.0
16524 * (x as f64 * std::f64::consts::PI / 23.0).sin()
16525 * (y as f64 * std::f64::consts::PI / 37.0).cos();
16526 let edge = if x > width * 3 / 7 && y > height / 3 {
16527 40.0
16528 } else {
16529 0.0
16530 };
16531 picture.y[y * width + x] =
16532 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
16533 }
16534 }
16535 for y in 0..height / 2 {
16536 for x in 0..width / 2 {
16537 let i = y * width / 2 + x;
16538 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
16539 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
16540 }
16541 }
16542 picture
16543 }
16544
16545 fn psnr(a: &[u16], b: &[u16]) -> f64 {
16546 let squared: f64 = a
16547 .iter()
16548 .zip(b)
16549 .map(|(&x, &y)| {
16550 let d = f64::from(x) - f64::from(y);
16551 d * d
16552 })
16553 .sum();
16554 if squared == 0.0 {
16555 return f64::INFINITY;
16556 }
16557 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
16558 }
16559
16560 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
16561 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
16562 /// frame's new root fires on most superblocks -- and what BOTH decoders
16563 /// produce is the encoder's own reconstruction, sample for sample.
16564 ///
16565 /// The fire count is the `gate-blind-to-feature` guard: without it every
16566 /// assert below passes on a stream that codes no whole superblock at all.
16567 #[test]
16568 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
16569 let _knobs = crate::speed::knob_read();
16570 let fctx = &crate::decode::FrameCtx::for_encoder();
16571 // 4 x 3 superblocks, all of them wholly inside the frame.
16572 let (width, height) = (256usize, 192usize);
16573 let mut picture = Picture::grey(width, height);
16574 for y in 0..height {
16575 for x in 0..width {
16576 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
16577 }
16578 }
16579 for y in 0..height / 2 {
16580 for x in 0..width / 2 {
16581 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
16582 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
16583 }
16584 }
16585 let _ = take_i64_root_hits();
16586 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
16587 let [roots, _offered, _edge] = take_i64_root_hits();
16588 // The counters are process-global, so another test encoding in
16589 // parallel can only ADD to them -- the per-FRAME fact is the mode
16590 // list, which carries one entry per coded block and so exactly 12
16591 // when every superblock was coded as one 64x64 intra block.
16592 assert_eq!(
16593 encoded.modes.len(),
16594 12,
16595 "not every superblock was coded as one 64x64 intra block"
16596 );
16597 assert!(
16598 roots >= 8,
16599 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
16600 );
16601 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
16602
16603 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16604 assert_eq!(ours.len(), 1, "our decoder's frames");
16605 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
16606 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
16607 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
16608
16609 if !have_ffmpeg() {
16610 eprintln!("SKIP the ffmpeg half: no ffmpeg");
16611 return;
16612 }
16613 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16614 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
16615 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
16616 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
16617 }
16618
16619 /// The claim the whole encoder rests on: what a decoder produces is what
16620 /// the encoder said it would, sample for sample, on every plane.
16621 ///
16622 /// Prediction reads the reconstruction, so a single sample of drift
16623 /// anywhere would spread into every block below and to the right of it —
16624 /// which is why this is an equality and not a tolerance.
16625 #[test]
16626 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
16627 let _knobs = crate::speed::knob_read();
16628 let fctx = &crate::decode::FrameCtx::for_encoder();
16629 if !have_ffmpeg() {
16630 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
16631 return;
16632 }
16633 for &(width, height) in &[
16634 (64usize, 64usize),
16635 (96, 64),
16636 (160, 96),
16637 (32, 48),
16638 (248, 152),
16639 ] {
16640 let picture = test_card(width, height);
16641 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16642 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16643 assert_eq!(
16644 decoded.y, encoded.reconstruction.y,
16645 "{width}x{height}: luma"
16646 );
16647 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
16648 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
16649 }
16650 // One q index from each of the four coefficient-CDF contexts
16651 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
16652 let (width, height) = (64usize, 64usize);
16653 let picture = test_card(width, height);
16654 let _ = take_tx_depth_hits();
16655 for &q in &[15u8, 45, 100, 200] {
16656 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16657 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16658 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
16659 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
16660 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
16661 }
16662 // lane-av1tx: the exactness above is only a claim about SPLIT
16663 // transforms if some block actually split one (`gate-blind-to-feature`
16664 // -- with `tx_depth` stuck at 0 every assert here passes on the
16665 // pre-lane stream). The test card's edges split at these four
16666 // quantizers; the counter is per-process (another test encoding in
16667 // parallel can only ADD to it, so this can be masked, never falsely
16668 // failed), so it is read once for the whole q ladder.
16669 let depths = take_tx_depth_hits();
16670 assert!(
16671 depths[1] + depths[2] > 0,
16672 "no block split its transform: depths {depths:?}"
16673 );
16674 }
16675
16676 /// A synthetic screen-content picture -- a few flat colours in a grid of
16677 /// boxes with hard edges and text-like bars, the shape a desktop capture
16678 /// has -- so the palette path is exercised on content it is for.
16679 #[cfg(test)]
16680 fn screen_card(width: usize, height: usize) -> Picture {
16681 const INK: [u16; 4] = [16, 90, 180, 235];
16682 let mut picture = Picture::grey(width, height);
16683 for y in 0..height {
16684 for x in 0..width {
16685 let cell = (x / 24 + y / 24) % 2;
16686 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
16687 picture.y[y * width + x] = INK[cell * 2 + bar];
16688 }
16689 }
16690 // Four chroma colours, not two: a two-colour chroma block only ever
16691 // codes a `PaletteSizeUV` of 2, which leaves
16692 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
16693 // deltas and the neighbour cache flags, exercised only when
16694 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
16695 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
16696 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
16697 for y in 0..height / 2 {
16698 for x in 0..width / 2 {
16699 let cell = (x / 12 + 2 * (y / 12)) % 4;
16700 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
16701 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
16702 }
16703 }
16704 picture
16705 }
16706
16707 /// The lane's own end-to-end check: on screen content the detector fires,
16708 /// blocks really take a palette (fire count, class
16709 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
16710 /// symbol this lane writes -- reconstructs exactly what the encoder did.
16711 /// The film-shaped `test_card` must NOT trip the detector, which is what
16712 /// keeps every non-screen stream byte-identical.
16713 #[test]
16714 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
16715 let _knobs = crate::speed::knob_read();
16716 let fctx = &crate::decode::FrameCtx::for_encoder();
16717 let (width, height) = (192usize, 96usize);
16718 let _ = crate::tile::take_palette_hits();
16719 let picture = screen_card(width, height);
16720 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16721 assert!(
16722 encoded.screen,
16723 "the detector did not fire on screen content -- no palette syntax was coded at all"
16724 );
16725 let hits = crate::tile::take_palette_hits();
16726 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
16727 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
16728 // The chroma half is a claim about the plane-1 syntax only if some
16729 // block really took a chroma palette (`gate-blind-to-feature`): every
16730 // exactness assert below passes on a stream that codes
16731 // `palette_uv_mode == 0` everywhere.
16732 let uv_hits = crate::tile::take_palette_uv_hits();
16733 assert!(
16734 uv_hits[0] > 0,
16735 "no block took a chroma palette: {uv_hits:?}"
16736 );
16737 let uv_cached = crate::tile::take_palette_uv_cache_hits();
16738 eprintln!(
16739 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
16740 uv_hits[0],
16741 &uv_hits[2..]
16742 );
16743 assert!(
16744 uv_cached > 0,
16745 "no chroma base colour came out of the neighbour cache -- \
16746 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
16747 );
16748 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
16749 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
16750 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
16751 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
16752 if !have_ffmpeg() {
16753 eprintln!("SKIP the ffmpeg half: no ffmpeg");
16754 return;
16755 }
16756 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16757 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
16758 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
16759 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
16760 // A whole GOP: the inter frames' own intra blocks carry the palette
16761 // syntax too (the three intra arms of the inter writers), which only
16762 // ffmpeg reading the frames back can prove.
16763 let moved: Vec<Picture> = (0..4)
16764 .map(|f| {
16765 let base = screen_card(width, height);
16766 let mut out = Picture::grey(width, height);
16767 for y in 0..height {
16768 for x in 0..width {
16769 let sx = (x + f * 7) % width;
16770 out.y[y * width + x] = base.y[y * width + sx];
16771 }
16772 }
16773 for y in 0..height / 2 {
16774 for x in 0..width / 2 {
16775 let sx = (x + f * 3) % (width / 2);
16776 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
16777 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
16778 }
16779 }
16780 out
16781 })
16782 .collect();
16783 let _ = crate::tile::take_palette_hits();
16784 let _ = crate::tile::take_palette_uv_hits();
16785 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
16786 let gop_hits = crate::tile::take_palette_hits();
16787 let gop_uv_hits = crate::tile::take_palette_uv_hits();
16788 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
16789 eprintln!(
16790 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
16791 {} chroma palette blocks",
16792 inter_screen, gop_hits[0], gop_uv_hits[0]
16793 );
16794 assert!(
16795 gop_uv_hits[0] > 0,
16796 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
16797 );
16798 assert!(
16799 inter_screen > 0,
16800 "no inter frame set allow_screen_content_tools"
16801 );
16802 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
16803 assert_eq!(
16804 gop_decoded.len(),
16805 gop.frames.len(),
16806 "our decoder: GOP frame count"
16807 );
16808 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
16809 assert_eq!(
16810 ours.y, frame.reconstruction.y,
16811 "our decoder: GOP frame {i} luma"
16812 );
16813 }
16814 if have_ffmpeg() {
16815 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
16816 assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count");
16817 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
16818 assert_eq!(
16819 theirs.y, frame.reconstruction.y,
16820 "ffmpeg: GOP frame {i} luma"
16821 );
16822 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
16823 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
16824 }
16825 }
16826
16827 // The other half of the keep rule: film-shaped content leaves the
16828 // detector (and so the whole sequence header) alone.
16829 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
16830 assert!(
16831 !film.screen,
16832 "the detector fired on the film-shaped test card"
16833 );
16834 }
16835
16836 /// The lane's keep-rule measurement: the gate's own screen capture, one
16837 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
16838 /// Setting the bit forces deblocking, CDEF and loop restoration off for
16839 /// that frame, so the table is exactly the filter loss against the bytes
16840 /// the copied blocks save.
16841 #[test]
16842 #[ignore = "needs the real-library manifest and ffmpeg"]
16843 fn probe_intrabc_key_frame() {
16844 let _knobs = crate::speed::knob_write();
16845 let fctx = &crate::decode::FrameCtx::for_encoder();
16846 // lane-av1clipprobe: the manifest is a real-library file, so it
16847 // resolves through the crate's one fixture root (EC_FIXTURES first)
16848 // and its absence is reported by the one probe instead of an inline
16849 // SKIP that named no path. A file that IS there but unreadable is not
16850 // an absence, so it is a hard error rather than a second silent skip.
16851 let Some(manifest_path) =
16852 crate::library_fixture::require("real-library-manifest.tsv", "probe_intrabc_key_frame")
16853 else {
16854 return;
16855 };
16856 let manifest = std::fs::read_to_string(&manifest_path).unwrap_or_else(|e| {
16857 panic!(
16858 "probe_intrabc_key_frame: {} is present but unreadable ({e})",
16859 manifest_path.display()
16860 )
16861 });
16862 let Some(clip) = manifest
16863 .lines()
16864 .skip(1)
16865 .filter_map(|l| l.split('\t').next())
16866 .find(|p| {
16867 p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
16868 })
16869 else {
16870 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
16871 return;
16872 };
16873 let (width, height) = (1280usize, 768usize);
16874 let picture = clip_frame(clip, "0", width, height);
16875 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
16876 for q in [5u8, 20, 35, 45] {
16877 for on in [false, true] {
16878 force_intrabc(Some(on));
16879 let _ = crate::tile::take_intrabc_hits();
16880 let _ = take_intrabc_search();
16881 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16882 let hits = crate::tile::take_intrabc_hits();
16883 let search = take_intrabc_search();
16884 eprintln!(
16885 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
16886 if encoded.allow_intrabc { "on" } else { "off" },
16887 encoded.stream.len(),
16888 psnr_all(&encoded.reconstruction, &picture),
16889 hits[0],
16890 &hits[1..],
16891 search[0],
16892 search[1],
16893 search[2],
16894 );
16895 }
16896 }
16897 force_intrabc(None);
16898 }
16899
16900 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
16901 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
16902 /// take a block vector (fire count + DV histogram, class
16903 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
16904 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
16905 /// exactly what the encoder did.
16906 #[test]
16907 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
16908 let _knobs = crate::speed::knob_write();
16909 let fctx = &crate::decode::FrameCtx::for_encoder();
16910 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
16911 // superblocks of 64) and tall enough for a source superblock row
16912 // above the blocks that copy from it.
16913 let (width, height) = (512usize, 256usize);
16914 let picture = screen_card(width, height);
16915 let _ = crate::tile::take_intrabc_hits();
16916 // The default is OFF (it measured worse on the real screen capture --
16917 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
16918 // the arm on for its own encode and puts it back straight after.
16919 force_intrabc(Some(true));
16920 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16921 force_intrabc(None);
16922 assert!(
16923 encoded.allow_intrabc,
16924 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
16925 intrabc_source_share() * 100.0
16926 );
16927 let hits = crate::tile::take_intrabc_hits();
16928 eprintln!(
16929 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
16930 hits[0],
16931 &hits[1..],
16932 intrabc_source_share() * 100.0
16933 );
16934 let search = take_intrabc_search();
16935 eprintln!(
16936 "intrabc searches {} found-valid {} won-RD {}",
16937 search[0], search[1], search[2]
16938 );
16939 assert!(
16940 hits[0] > 0,
16941 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
16942 );
16943 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
16944 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
16945 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
16946 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
16947 if !have_ffmpeg() {
16948 eprintln!("SKIP the ffmpeg half: no ffmpeg");
16949 return;
16950 }
16951 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16952 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
16953 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
16954 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
16955 }
16956
16957 /// The minimal repro that isolated the inter-residual desync: a key frame
16958 /// followed by one inter frame whose single superblock carries one
16959 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
16960 /// coefficient, its three sibling blocks all `skip: true`. Before the
16961 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
16962 /// found when processing input") even though every symbol either block
16963 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
16964 /// same coefficient syntax decodes clean on every intra key-frame gate).
16965 #[test]
16966 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
16967 let _knobs = crate::speed::knob_write();
16968 let fctx = &crate::decode::FrameCtx::for_encoder();
16969 if !have_ffmpeg() {
16970 eprintln!(
16971 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
16972 );
16973 return;
16974 }
16975 let (width, height) = (64usize, 64usize);
16976 let picture = Picture::grey(width, height);
16977 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16978
16979 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
16980 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
16981
16982 let residual_block = BlockCoeffs {
16983 luma_tx_types: Vec::new(),
16984 angle_delta_y: 0,
16985 cfl_alphas: None,
16986 filter_intra: None,
16987 luma: vec![Coeff {
16988 row: 0,
16989 col: 0,
16990 level: 4,
16991 }],
16992 u: Vec::new(),
16993 v: Vec::new(),
16994 mode: 0,
16995 uv_mode: 0,
16996 skip: false,
16997 eight: None,
16998 dv: None,
16999 palette: None,
17000 palette_uv: None,
17001 tx_depth: 0,
17002 inter: Some(InterInfo {
17003 ref1: None,
17004 mv1: (0, 0),
17005 ref_frame: crate::mvstack::LAST_FRAME,
17006 mode: InterMode::NearestMv,
17007 mv: (0, 0),
17008 ref_mv_idx: 0,
17009 }),
17010 motion_mode: 0,
17011 };
17012 let skipped_block = BlockCoeffs {
17013 skip: true,
17014 inter: Some(InterInfo {
17015 ref1: None,
17016 mv1: (0, 0),
17017 ref_frame: crate::mvstack::LAST_FRAME,
17018 mode: InterMode::NearestMv,
17019 mv: (0, 0),
17020 ref_mv_idx: 0,
17021 }),
17022 ..BlockCoeffs::default()
17023 };
17024 let blocks = vec![
17025 Quadrant::Whole(residual_block),
17026 Quadrant::Whole(skipped_block.clone()),
17027 Quadrant::Whole(skipped_block.clone()),
17028 Quadrant::Whole(skipped_block),
17029 ];
17030 // lane-av1obmc: the header this tile is decoded under carries
17031 // `is_motion_mode_switchable`, so the writer must be armed with it
17032 // too or the decoder reads a `motion_mode` symbol nobody wrote.
17033 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
17034 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
17035 let tile = crate::tile::sb_coeff_inter_frame_tile(
17036 inter_header.mi_cols,
17037 inter_header.mi_rows,
17038 100,
17039 &blocks,
17040 )
17041 .unwrap();
17042
17043 // `key.stream` is already a temporal delimiter, the sequence header
17044 // and the key frame's own OBU (`encode_key_frame` built it from the
17045 // same `key_frame_headers(width, height, 100)` this test calls), so
17046 // the inter frame's OBU is appended straight onto it rather than
17047 // re-deriving the key frame's tile bytes.
17048 let mut stream = key.stream.clone();
17049 stream.extend_from_slice(&temporal_delimiter());
17050 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
17051
17052 ffmpeg_decode_sequence(&stream, width, height, 2);
17053 }
17054
17055 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
17056 /// frame size an AV1 decoder allocates, not necessarily the render size
17057 /// (see [`a_frame_round_trips_at_its_own_size`]).
17058 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
17059 // Distinct per call, not per process: the test binary runs callers on
17060 // parallel threads, and a shared name lets one test's cleanup delete
17061 // the stream another test's ffprobe is still reading.
17062 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
17063 let path = std::env::temp_dir().join(format!(
17064 "ec-av1-probe-{}-{}.obu",
17065 std::process::id(),
17066 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
17067 ));
17068 let _ = std::fs::remove_file(&path);
17069 std::fs::write(&path, stream).expect("writing the probe stream");
17070 let out = Command::new("ffprobe")
17071 .args([
17072 "-v",
17073 "error",
17074 "-f",
17075 "obu",
17076 "-select_streams",
17077 "v:0",
17078 "-show_entries",
17079 "stream=width,height",
17080 "-of",
17081 "csv=p=0",
17082 ])
17083 .arg(&path)
17084 .output()
17085 .expect("ffprobe failed to run");
17086 let _ = std::fs::remove_file(&path);
17087 assert!(
17088 out.status.success(),
17089 "ffprobe refused the stream: {}",
17090 String::from_utf8_lossy(&out.stderr)
17091 );
17092 let text = String::from_utf8_lossy(&out.stdout);
17093 let mut fields = text.trim().split(',');
17094 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
17095 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
17096 (width, height)
17097 }
17098
17099 /// lane-av1cap: the final filter replay against the capture decode it
17100 /// replaced, at the block-padded and straddling sizes the whole-frame
17101 /// tests cover -- `set_verify_final_replay` makes
17102 /// [`pick_and_apply_filters`] run both on every frame and assert, per
17103 /// frame, that the spliced picture and the two filter stages the
17104 /// restoration search reads are bit-identical over the frame's own crop.
17105 #[test]
17106 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
17107 let _knobs = crate::speed::knob_write();
17108 let fctx = &crate::decode::FrameCtx::for_encoder();
17109 crate::decode::set_verify_final_replay(true);
17110 for &(width, height) in &[
17111 (64usize, 56usize),
17112 (216, 96),
17113 (192, 120),
17114 (640, 352),
17115 (1280, 720),
17116 ] {
17117 eprintln!("--- {width}x{height}");
17118 let picture = test_card(width, height);
17119 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17120 }
17121 crate::decode::set_verify_final_replay(false);
17122 }
17123
17124 /// A key frame at an arbitrary even size round-trips through ffmpeg over
17125 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
17126 /// picture's own size, and what ffmpeg decodes over that same top-left
17127 /// region equals it sample for sample.
17128 ///
17129 /// This does not check that `ffprobe` reports the picture's own size,
17130 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
17131 /// (block-padded) frame size, the same one libaom itself would code for
17132 /// a non-block-aligned picture. `render_width`/`render_height` (which
17133 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
17134 /// decoder is required to crop pixels by, and ffmpeg's does not --
17135 /// checked empirically against ffprobe here and against a real libaom
17136 /// encode separately. So the coded size, not the render size, is what
17137 /// `ffprobe` is asserted to report below.
17138 #[test]
17139 fn a_frame_round_trips_at_its_own_size() {
17140 let _knobs = crate::speed::knob_read();
17141 let fctx = &crate::decode::FrameCtx::for_encoder();
17142 if !have_ffmpeg() {
17143 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
17144 return;
17145 }
17146 // 854x480 is covered separately by
17147 // `an_854x480_picture_round_trips_through_its_padding`, which its own
17148 // doc comment explains was worth keeping as its own test.
17149 for &(width, height) in &[
17150 (1920usize, 1080usize),
17151 (640, 352),
17152 (1280, 720),
17153 (64, 56),
17154 (854, 480),
17155 (216, 96),
17156 (192, 120),
17157 ] {
17158 let picture = test_card(width, height);
17159 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17160 assert_eq!(
17161 (encoded.reconstruction.width, encoded.reconstruction.height),
17162 (width, height),
17163 "{width}x{height}: reconstruction is cropped to the picture's own size"
17164 );
17165 assert_eq!(
17166 ffprobe_size(&encoded.stream),
17167 (width as u32, height as u32),
17168 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
17169 );
17170 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17171 assert_eq!(
17172 decoded.y, encoded.reconstruction.y,
17173 "{width}x{height}: luma"
17174 );
17175 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
17176 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
17177 }
17178 }
17179
17180 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
17181 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
17182 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
17183 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
17184 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
17185 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
17186 /// col`) -- different bits of an 8-byte table, one true, one false. The
17187 /// stride libaom indexes by is fixed at its compile-time maximum
17188 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
17189 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
17190 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
17191 /// row/col position within the (correctly 64-relative) superblock stayed
17192 /// right, only the table's own row stride was wrong. Fixed in
17193 /// `Reach::table_stride`; not an arithmetic-coder desync (an
17194 /// EC_RNG-per-symbol trace against the same debug decoder found the
17195 /// bitstream byte-for-byte identical to libaom's across all 51188
17196 /// symbols of this frame before this bug was found).
17197 ///
17198 /// Since the frame header started writing the true (unpadded) display
17199 /// size into `frame_width`/`frame_height` rather than the padded coded
17200 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
17201 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
17202 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
17203 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
17204 /// the header's own size before output).
17205 #[test]
17206 fn an_854x480_picture_round_trips_through_its_padding() {
17207 let _knobs = crate::speed::knob_read();
17208 let fctx = &crate::decode::FrameCtx::for_encoder();
17209 if !have_ffmpeg() {
17210 return;
17211 }
17212 let (width, height) = (854usize, 480usize);
17213 let picture = test_card(width, height);
17214 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17215 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17216 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
17217 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
17218 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
17219 }
17220
17221 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
17222 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
17223 /// superblock, both partition tables:
17224 ///
17225 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
17226 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
17227 /// wiring the TU sites onto it changes no existing stream;
17228 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
17229 /// NULL in libaom because that lookup never happens, and reading a
17230 /// 4x4 row out of the three-row vert tables is what crashed a real
17231 /// `--enable-tx-size-search=1` stream (r2);
17232 /// 3. and it must be the BLOCK's vert answer where the two tables
17233 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
17234 /// row 1, column 0 reads its above-right samples from the 8x8 to its
17235 /// upper right, which a vertical AB partition codes AFTER it
17236 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
17237 #[test]
17238 fn of_tu_follows_the_block_row_including_under_vert_ab() {
17239 let fctx = &crate::decode::FrameCtx::for_encoder();
17240 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
17241 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
17242 // above-right answer is the BLOCK's, which is the whole reason a unit
17243 // asks the block instead of looking itself up (the
17244 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
17245 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
17246 assert_eq!(
17247 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
17248 plain.above_right,
17249 "ordinary table: the top-right TX4 unit takes the block's row"
17250 );
17251 let guard = Reach::vert_ab_partition();
17252 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
17253 assert_eq!(
17254 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
17255 vert.above_right,
17256 "vert AB: the unit follows the vert row the block just picked"
17257 );
17258 assert_ne!(
17259 plain.above_right, vert.above_right,
17260 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
17261 );
17262 drop(guard);
17263 }
17264
17265 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
17266 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
17267 /// reconintra.c`), for every 16x16 and 32x32 block position across three
17268 /// superblocks square -- interior and every superblock edge (top row,
17269 /// left column, right column, bottom row) both sizes reach. Written to
17270 /// catch the class the `table_stride` bug was: an index stride silently
17271 /// wrong for one block size while looking plausible for the other.
17272 #[test]
17273 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
17274 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
17275 // it pins the 64 reach explicitly instead of following the process's
17276 // own superblock knob (`for_encoder`), which made it red under
17277 // `EC_AV1_SB128=1` for no defect of the code under test.
17278 let fctx = &crate::decode::FrameCtx::new();
17279 // Transcribed from has_top_right/has_bottom_left's row_off==0,
17280 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
17281 // 128px reference grid) pinned as libaom pins it, independent of the
17282 // 64px superblock this crate actually codes.
17283 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
17284 if y == 0 || x + side >= width {
17285 return false;
17286 }
17287 let (row, col, per_side) = (
17288 (y % SUPERBLOCK) / side,
17289 (x % SUPERBLOCK) / side,
17290 SUPERBLOCK / side,
17291 );
17292 if row == 0 {
17293 return true;
17294 }
17295 if col + 1 == per_side {
17296 return false;
17297 }
17298 let stride = 128 / side;
17299 let index = row * stride + col;
17300 let table = if side == BLOCK {
17301 [95u8, 87].to_vec()
17302 } else {
17303 vec![255, 85, 119, 85, 127, 85, 119, 85]
17304 };
17305 (table[index / 8] >> (index % 8)) & 1 != 0
17306 }
17307
17308 fn libaom_bottom_left(
17309 side: usize,
17310 x: usize,
17311 y: usize,
17312 height: usize,
17313 _fctx: &crate::decode::FrameCtx,
17314 ) -> bool {
17315 if x == 0 || y + side >= height {
17316 return false;
17317 }
17318 let (row, col, per_side) = (
17319 (y % SUPERBLOCK) / side,
17320 (x % SUPERBLOCK) / side,
17321 SUPERBLOCK / side,
17322 );
17323 if col == 0 {
17324 return row * side + side < SUPERBLOCK;
17325 }
17326 if row + 1 == per_side {
17327 return false;
17328 }
17329 let stride = 128 / side;
17330 let index = row * stride + col;
17331 let table = if side == BLOCK {
17332 [4u8, 4].to_vec()
17333 } else {
17334 vec![84, 16, 84, 0, 84, 16, 84, 0]
17335 };
17336 (table[index / 8] >> (index % 8)) & 1 != 0
17337 }
17338
17339 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
17340 for side in [16usize, BLOCK] {
17341 for y in (0..height).step_by(side) {
17342 for x in (0..width).step_by(side) {
17343 let reach = Reach::of(side, x, y, width, height, fctx);
17344 assert_eq!(
17345 reach.above_right,
17346 libaom_top_right(side, x, y, width, height),
17347 "side={side} x={x} y={y}: above_right"
17348 );
17349 assert_eq!(
17350 reach.below_left,
17351 libaom_bottom_left(side, x, y, height, fctx),
17352 "side={side} x={x} y={y}: below_left"
17353 );
17354 }
17355 }
17356 }
17357 }
17358
17359 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
17360 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
17361 /// column inside the superblock) may read the below-left samples the
17362 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
17363 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
17364 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
17365 /// stream that partitions that small first hits the still-refused
17366 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
17367 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
17368 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
17369 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
17370 /// pixels -- lane-palette2 r12: the square multi-TU path used the
17371 /// standalone-block tables instead of this rule and granted a 16x16
17372 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
17373 #[test]
17374 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
17375 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
17376 // *_count_unit = tx size / 4.
17377 fn libaom_tr(
17378 bw: usize,
17379 bh: usize,
17380 col_off: usize,
17381 row_off: usize,
17382 tx: usize,
17383 blk: bool,
17384 ) -> bool {
17385 let (plane_bw_unit, count) = (bw / 4, tx / 4);
17386 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
17387 let _ = bh;
17388 if row_off_u > 0 {
17389 col_off_u + count < plane_bw_unit
17390 } else if col_off_u + count < plane_bw_unit {
17391 true
17392 } else {
17393 blk
17394 }
17395 }
17396 fn libaom_bl(
17397 bw: usize,
17398 bh: usize,
17399 col_off: usize,
17400 row_off: usize,
17401 tx: usize,
17402 blk: bool,
17403 ) -> bool {
17404 let (plane_bh_unit, count) = (bh / 4, tx / 4);
17405 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
17406 let _ = bw;
17407 if col_off_u > 0 {
17408 false
17409 } else if row_off_u + count < plane_bh_unit {
17410 true
17411 } else {
17412 blk
17413 }
17414 }
17415 for &(bw, bh) in &[
17416 (8, 8),
17417 (16, 16),
17418 (32, 32),
17419 (64, 64),
17420 (16, 8),
17421 (8, 16),
17422 (32, 16),
17423 (16, 32),
17424 (64, 32),
17425 (32, 64),
17426 ] {
17427 for &tx in &[4usize, 8, 16, 32] {
17428 if tx > bw.min(bh) {
17429 continue;
17430 }
17431 for row_off in (0..bh).step_by(tx) {
17432 for col_off in (0..bw).step_by(tx) {
17433 for &blk in &[
17434 Reach {
17435 above_right: false,
17436 below_left: false,
17437 },
17438 Reach {
17439 above_right: true,
17440 below_left: true,
17441 },
17442 ] {
17443 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
17444 assert_eq!(
17445 got.above_right,
17446 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
17447 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
17448 );
17449 assert_eq!(
17450 got.below_left,
17451 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
17452 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
17453 );
17454 }
17455 }
17456 }
17457 }
17458 }
17459 }
17460
17461 #[test]
17462 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
17463 let fctx = &crate::decode::FrameCtx::for_encoder();
17464 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
17465 // Interior superblock, so neither the frame edge nor the col == 0 /
17466 // last-row early returns answer instead of the table.
17467 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
17468 let mut flipped = 0;
17469 for row in 0..8 {
17470 for col in 1..8 {
17471 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
17472 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
17473 let vert = {
17474 let _guard = Reach::vert_ab_partition();
17475 Reach::of(8, x, y, width, height, fctx).below_left
17476 };
17477 // The TR square of a VERT_A/_B sits at an even row, odd
17478 // column; every other slot must be untouched by the guard.
17479 if row % 2 == 0 && col % 2 == 1 {
17480 assert!(!raster, "raster below_left at row={row} col={col}");
17481 assert!(vert, "vert below_left at row={row} col={col}");
17482 flipped += 1;
17483 } else {
17484 assert_eq!(raster, vert, "guard moved row={row} col={col}");
17485 }
17486 }
17487 }
17488 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
17489 // The guard is scoped: it must not leak past its own block.
17490 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
17491 }
17492
17493 /// An odd width or height is refused by name, not by however the padder
17494 /// or the block coder would happen to fail on it.
17495 #[test]
17496 fn odd_dimensions_are_refused() {
17497 let _knobs = crate::speed::knob_read();
17498 let fctx = &crate::decode::FrameCtx::for_encoder();
17499 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
17500 let picture = Picture::grey(width, height);
17501 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
17502 .expect_err(&format!("{width}x{height} is odd and must be refused"));
17503 assert!(
17504 err.to_string().contains("even"),
17505 "{width}x{height}: error was {err}"
17506 );
17507 }
17508 }
17509
17510 /// A sequence at a size that is not a multiple of the block grid decodes
17511 /// to the right frame count and the right size for every frame,
17512 /// including the inter frames whose reference is the previous frame's
17513 /// own (padded) reconstruction.
17514 #[test]
17515 fn sequence_round_trips_at_a_non_multiple_size() {
17516 let _knobs = crate::speed::knob_read();
17517 let fctx = &crate::decode::FrameCtx::for_encoder();
17518 if !have_ffmpeg() {
17519 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
17520 return;
17521 }
17522 let (width, height) = (160usize, 96usize);
17523 let pictures: Vec<Picture> = (0..3)
17524 .map(|i| panned_test_card(width, height, i * 3))
17525 .collect();
17526 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17527 assert_eq!(encoded.frames.len(), 3);
17528 for (i, frame) in encoded.frames.iter().enumerate() {
17529 assert_eq!(
17530 (frame.reconstruction.width, frame.reconstruction.height),
17531 (width, height),
17532 "frame {i}: reconstruction size"
17533 );
17534 }
17535 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
17536 // true (display) size a sequence's frames share, not the padded one.
17537 assert_eq!(
17538 ffprobe_size(&encoded.stream),
17539 (width as u32, height as u32),
17540 "sequence: ffprobe reports the true (display) size"
17541 );
17542 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
17543 assert_eq!(decoded.len(), 3, "decoded frame count");
17544 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17545 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17546 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17547 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17548 }
17549 }
17550
17551 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
17552 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
17553 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
17554 /// `pos + side_mi / 2 < bound` boundary), which is the case
17555 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
17556 /// refusing. A key frame alone already covered this size; this proves the
17557 /// inter tile writer's parity with it across a real multi-frame export.
17558 #[test]
17559 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
17560 let _knobs = crate::speed::knob_read();
17561 let fctx = &crate::decode::FrameCtx::for_encoder();
17562 if !have_ffmpeg() {
17563 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
17564 return;
17565 }
17566 let (width, height) = (1280usize, 720usize);
17567 let pictures: Vec<Picture> = (0..3)
17568 .map(|i| panned_test_card(width, height, i * 3))
17569 .collect();
17570 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17571 assert_eq!(encoded.frames.len(), 3);
17572 for (i, frame) in encoded.frames.iter().enumerate() {
17573 assert_eq!(
17574 (frame.reconstruction.width, frame.reconstruction.height),
17575 (width, height),
17576 "frame {i}: reconstruction size"
17577 );
17578 }
17579 assert_eq!(
17580 ffprobe_size(&encoded.stream),
17581 (width as u32, height as u32),
17582 "ffprobe reports the true (display) 1280x720 size"
17583 );
17584 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
17585 assert_eq!(decoded.len(), 3, "decoded frame count");
17586 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17587 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17588 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17589 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17590 }
17591 }
17592
17593 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
17594 /// leaf's own half (`has_half` at the SUB level) itself straddles the
17595 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
17596 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
17597 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
17598 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
17599 /// straddling-16x16 branch), so an inter frame no longer refuses this
17600 /// size either. This only proves the encoder does not error out -- see
17601 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
17602 /// decoder-clean proof (a 3-frame sequence, so the inter path is
17603 /// actually exercised).
17604 #[test]
17605 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
17606 let _knobs = crate::speed::knob_read();
17607 let fctx = &crate::decode::FrameCtx::for_encoder();
17608 let (width, height) = (640usize, 360usize);
17609 let picture = Picture::grey(width, height);
17610 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
17611 .expect("key frame now codes the mod-32==8 straddle");
17612
17613 // `encode_sequence`'s second frame is the inter path: same size, now
17614 // wired the same way.
17615 let pictures = vec![picture.clone(), picture];
17616 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
17617 .expect("inter frame now codes the mod-32==8 straddle too");
17618 }
17619
17620 /// The r15 fix at production size: three 640x360 key frames (inter is
17621 /// still refused at this size, per the test above, so this stands in for
17622 /// the charter's "3-frame sequence" using three independent key frames of
17623 /// shifted content), each proven decoder-clean through ffmpeg rather than
17624 /// only encoder-clean.
17625 #[test]
17626 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
17627 let _knobs = crate::speed::knob_read();
17628 let fctx = &crate::decode::FrameCtx::for_encoder();
17629 if !have_ffmpeg() {
17630 eprintln!(
17631 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
17632 no ffmpeg"
17633 );
17634 return;
17635 }
17636 let (width, height) = (640usize, 360usize);
17637 for shift in [0i64, 7, 19] {
17638 let picture = panned_test_card(width, height, shift);
17639 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17640 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17641 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
17642 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
17643 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
17644 }
17645 }
17646
17647 /// The 640x360 straddle class, but through the inter path an actual
17648 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
17649 /// proves the leaf-8 inter stream this round wires up is not just
17650 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
17651 #[test]
17652 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
17653 let _knobs = crate::speed::knob_read();
17654 let fctx = &crate::decode::FrameCtx::for_encoder();
17655 if !have_ffmpeg() {
17656 eprintln!(
17657 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
17658 );
17659 return;
17660 }
17661 let (width, height) = (640usize, 360usize);
17662 let pictures: Vec<Picture> = (0..4)
17663 .map(|i| panned_test_card(width, height, i * 3))
17664 .collect();
17665 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17666 assert_eq!(encoded.frames.len(), 4);
17667 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
17668 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
17669 }
17670 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
17671 assert_eq!(decoded.len(), 4, "decoded frame count");
17672 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17673 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17674 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17675 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17676 }
17677 }
17678
17679 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
17680 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
17681 let out = Command::new("ffmpeg")
17682 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
17683 .args(["-vf", &format!("scale={width}:{height}")])
17684 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
17685 .output()
17686 .expect("ffmpeg failed to run");
17687 assert!(
17688 out.status.success(),
17689 "ffmpeg: {}",
17690 String::from_utf8_lossy(&out.stderr)
17691 );
17692 let (luma, chroma) = (width * height, width * height / 4);
17693 assert_eq!(
17694 out.stdout.len(),
17695 luma + 2 * chroma,
17696 "expected one 4:2:0 frame"
17697 );
17698 Picture {
17699 width,
17700 height,
17701 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
17702 u: out.stdout[luma..luma + chroma]
17703 .iter()
17704 .map(|&v| u16::from(v))
17705 .collect(),
17706 v: out.stdout[luma + chroma..]
17707 .iter()
17708 .map(|&v| u16::from(v))
17709 .collect(),
17710 }
17711 }
17712
17713 /// Prints what the mode search saves over DC prediction alone, for the
17714 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
17715 /// weight the search puts on rate can be swept.
17716 #[test]
17717 #[ignore = "a sweep, not a gate"]
17718 fn probe_lambda() {
17719 let _knobs = crate::speed::knob_read();
17720 let fctx = &crate::decode::FrameCtx::for_encoder();
17721 let mut pictures = vec![
17722 ("test card".to_string(), test_card(160, 96)),
17723 ("stripes".to_string(), stripes(160, 96, true)),
17724 ];
17725 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
17726 for entry in clips.split(':').filter(|e| !e.is_empty()) {
17727 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
17728 let name = path.rsplit('/').next().unwrap_or(path).to_string();
17729 pictures.push((name, clip_frame(path, skip, 640, 352)));
17730 }
17731 }
17732 for (name, picture) in pictures {
17733 let dc = ladder(&picture, &[DC_PRED], fctx);
17734 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
17735 println!(
17736 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
17737 bd_rate(&dc, &searched) * 100.0,
17738 10f64.powf(searched[1].1),
17739 searched[1].0,
17740 10f64.powf(dc[1].1),
17741 dc[1].0,
17742 );
17743 }
17744 }
17745
17746 /// Prints the whole mode-search ladder, so two builds of the search can be
17747 /// compared against each other rather than each against its own baseline.
17748 #[test]
17749 #[ignore = "a sweep, not a gate"]
17750 fn probe_ladder() {
17751 let _knobs = crate::speed::knob_read();
17752 let fctx = &crate::decode::FrameCtx::for_encoder();
17753 for (name, picture) in sweep_pictures() {
17754 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
17755 let points = all
17756 .iter()
17757 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
17758 .collect::<Vec<_>>()
17759 .join(" ");
17760 println!("ladder {name}: {points}");
17761 }
17762 }
17763
17764 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
17765 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
17766 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
17767 #[test]
17768 // ROBUST-RED on this tree, and the red is in the MEASURE, not the codec:
17769 // the `stripes` picture codes LOSSLESSLY at q110/90/70, so both ladders
17770 // come back as three identical `(inf, 1.8260748027008264)` points and
17771 // `bd_rate` has an empty trapezoid to integrate, which panics with
17772 // "the two ladders have to overlap in PSNR". Row 1 (`test card`) still
17773 // prints its number before the panic. Point `EC_AV1_CLIPS` at a real lossy
17774 // clip, or read only row 1.
17775 #[ignore = "a sweep, not a gate; PANICS on its own lossless synthetic rows (stripes is lossless at q110/90/70, so bd_rate has no PSNR overlap) -- point EC_AV1_CLIPS at a lossy clip"]
17776 fn probe_split() {
17777 let _knobs = crate::speed::knob_read();
17778 let fctx = &crate::decode::FrameCtx::for_encoder();
17779 for (name, picture) in sweep_pictures() {
17780 let ladder = |split: bool| {
17781 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
17782 .iter()
17783 .map(|&q| {
17784 let encoded = encode_key_frame_inner(
17785 &picture,
17786 q,
17787 0.5,
17788 &KEY_FRAME_MODES,
17789 split,
17790 (picture.width, picture.height),
17791 unspecified_color_config(),
17792 fctx,
17793 )
17794 .unwrap();
17795 (
17796 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
17797 (encoded.stream.len() as f64).log10(),
17798 )
17799 })
17800 .collect();
17801 points.sort_by(|a, b| a.0.total_cmp(&b.0));
17802 points
17803 };
17804 let (whole, split) = (ladder(false), ladder(true));
17805 let blocks = encode_key_frame_inner(
17806 &picture,
17807 90,
17808 0.5,
17809 &KEY_FRAME_MODES,
17810 true,
17811 (picture.width, picture.height),
17812 unspecified_color_config(),
17813 fctx,
17814 )
17815 .unwrap()
17816 .modes
17817 .len();
17818 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
17819 println!(
17820 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
17821 bd_rate(&whole, &split) * 100.0
17822 );
17823 }
17824 }
17825
17826 /// A striped picture, running one way or the other. The stripes are what
17827 /// separates a vertical predictor from a horizontal one: a mode search
17828 /// reading a transposed edge would pick the wrong one of the pair, which no
17829 /// symmetric picture would show.
17830 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
17831 let mut picture = Picture::grey(width, height);
17832 for y in 0..height {
17833 for x in 0..width {
17834 let along = if vertical { x } else { y };
17835 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
17836 }
17837 }
17838 picture
17839 }
17840
17841 /// Where two planes first disagree, and by how much: a mismatch reported as
17842 /// a position says which block and which sample of it went wrong, which a
17843 /// pair of thousand-sample arrays does not. A length difference counts as a
17844 /// disagreement: `zip` stops at the shorter plane, so a short one would
17845 /// otherwise compare exact over the prefix the two share.
17846 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
17847 if let Some(i) = ours.iter().zip(theirs).position(|(a, b)| a != b) {
17848 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
17849 return Some(format!(
17850 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
17851 i % width,
17852 i / width,
17853 ours[i],
17854 theirs[i]
17855 ));
17856 }
17857 if ours.len() != theirs.len() {
17858 return Some(format!(
17859 "no sample in the shared prefix differs, but ours is {} samples and theirs is {}",
17860 ours.len(),
17861 theirs.len()
17862 ));
17863 }
17864 None
17865 }
17866
17867 /// Every mode the encoder offers has to predict what the decoder predicts,
17868 /// not just the ones a particular picture happens to choose: each is forced
17869 /// over a whole picture and the reconstruction gated against ffmpeg.
17870 #[test]
17871 fn every_mode_decodes_to_what_the_encoder_predicted() {
17872 let _knobs = crate::speed::knob_write();
17873 let fctx = &crate::decode::FrameCtx::for_encoder();
17874 if !have_ffmpeg() {
17875 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
17876 return;
17877 }
17878 // A mode ablation measures the MODE search: a filter-intra block is
17879 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
17880 // "the encoder coded something else" check for a reason that is not
17881 // about the mode search at all.
17882 force_filter_intra(Some(false));
17883 // 128 wide is a whole number of superblocks and 160 is not: the last
17884 // superblock of a 160-wide row is half a one, whose blocks have no
17885 // above-right samples inside the frame at all.
17886 for (width, height) in [(128, 96), (160, 96)] {
17887 let picture = test_card(width, height);
17888 for mode in KEY_FRAME_MODES {
17889 let encoded =
17890 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx)
17891 .unwrap();
17892 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17893 for (plane, ours, theirs, stride) in [
17894 ("luma", &encoded.reconstruction.y, &decoded.y, width),
17895 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
17896 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
17897 ] {
17898 assert!(
17899 first_difference(ours, theirs, stride).is_none(),
17900 "{width}x{height} mode {mode}, {plane}: {}",
17901 first_difference(ours, theirs, stride).unwrap()
17902 );
17903 }
17904 assert!(
17905 encoded.modes.iter().all(|&m| m == mode),
17906 "mode {mode}: the encoder coded something else"
17907 );
17908 }
17909 }
17910 }
17911
17912 /// The search has to follow the picture: vertical stripes are cheapest
17913 /// predicted from the row above, horizontal ones from the column to the
17914 /// left. Reading the edges the other way round would swap the two answers
17915 /// while leaving every fidelity gate intact.
17916 #[test]
17917 fn the_search_picks_the_direction_the_picture_runs() {
17918 let _knobs = crate::speed::knob_write();
17919 let fctx = &crate::decode::FrameCtx::for_encoder();
17920 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
17921 // a filter-intra block is coded `DC_PRED` whatever mode the arm
17922 // offers, and these stripes are SCREEN content, where the filter arm
17923 // now searches its own transform depth (lane-fitu) and wins outright
17924 // -- which says nothing about the mode search this gate measures.
17925 force_filter_intra(Some(false));
17926 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
17927 let picture = stripes(128, 96, vertical);
17928 // Only the pair, because on stripes a third mode predicts exactly
17929 // what the right one of the pair does -- PAETH reads the corner and
17930 // the left column, which a striped picture makes equal -- and the
17931 // tie then goes to whichever is cheaper to name, which is not what
17932 // this gate is about.
17933 let encoded =
17934 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx)
17935 .unwrap();
17936 // The first block of the picture has neither neighbour, so it
17937 // cannot tell the modes apart; every other one can.
17938 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
17939 assert!(
17940 picked * 2 > encoded.modes.len() - 1,
17941 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
17942 encoded.modes.len() - 1,
17943 encoded.modes
17944 );
17945 }
17946 }
17947
17948 /// What the search is for: the same picture, at the same quantizer, coded
17949 /// smaller and more faithfully than DC alone can manage.
17950 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
17951 /// between the two rate-distortion curves in log-rate against PSNR, as a
17952 /// fraction of the reference's rate. Negative means the second curve costs
17953 /// less for the same picture.
17954 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
17955 let low = reference[0].0.max(other[0].0);
17956 let high = reference[reference.len() - 1]
17957 .0
17958 .min(other[other.len() - 1].0);
17959 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
17960 // the non-directional one on the synthetic diagonals -- every point
17961 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
17962 // to integrate over any more. A curve that dominates that way has
17963 // saved everything the measure can express (the
17964 // `instrument-at-bound` class: the answer is at the instrument's own
17965 // edge, not undefined), so name it rather than panicking; anything
17966 // less clean than strict dominance still is.
17967 if high <= low {
17968 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
17969 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
17970 let dominates =
17971 other[0].0 > reference[reference.len() - 1].0 && other_hi_rate <= ref_lo_rate;
17972 assert!(
17973 dominates,
17974 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
17975 );
17976 return -1.0;
17977 }
17978 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
17979 let i = curve
17980 .windows(2)
17981 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
17982 .unwrap_or(0);
17983 let (x0, y0) = curve[i];
17984 let (x1, y1) = curve[i + 1];
17985 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
17986 };
17987 let steps = 64;
17988 let mut area = 0.0;
17989 for step in 0..steps {
17990 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
17991 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
17992 }
17993 10f64.powf(area / f64::from(steps)) - 1.0
17994 }
17995
17996 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
17997 /// fidelity.
17998 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
17999 // A mode ablation measures the MODE search: the palette would code
18000 // these synthetic two-colour pictures losslessly under every arm and
18001 // leave nothing to compare (see [`force_screen`]).
18002 force_screen(Some(false));
18003 // Same reason, for the filter-intra candidate: it wins blocks under
18004 // BOTH arms of a mode ablation and so cancels the difference the
18005 // ablation measures (class `gate-recipe-confound`).
18006 force_filter_intra(Some(false));
18007 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
18008 .iter()
18009 .map(|&q| {
18010 let encoded =
18011 encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
18012 (
18013 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
18014 (encoded.stream.len() as f64).log10(),
18015 )
18016 })
18017 .collect();
18018 points.sort_by(|a, b| a.0.total_cmp(&b.0));
18019 points
18020 }
18021
18022 /// What the search is for: the same pictures cost less to code at the same
18023 /// fidelity than DC prediction alone can manage. A picture that runs one
18024 /// way saves far more than a busy one, which is the shape a working
18025 /// directional pair has.
18026 #[test]
18027 fn the_search_beats_dc_alone() {
18028 let _knobs = crate::speed::knob_read();
18029 let fctx = &crate::decode::FrameCtx::for_encoder();
18030 for (name, picture, want) in [
18031 ("test card", test_card(160, 96), -0.05),
18032 ("stripes", stripes(160, 96, true), -0.40),
18033 ] {
18034 let saved = bd_rate(
18035 &ladder(&picture, &[DC_PRED], fctx),
18036 &ladder(&picture, &NON_DIRECTIONAL, fctx),
18037 );
18038 assert!(
18039 saved < want,
18040 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
18041 saved * 100.0,
18042 -want * 100.0
18043 );
18044 }
18045 }
18046
18047 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
18048 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
18049 fn sweep_pictures() -> Vec<(String, Picture)> {
18050 let mut pictures = vec![
18051 ("test card".to_string(), test_card(160, 96)),
18052 ("stripes".to_string(), stripes(160, 96, true)),
18053 ("diagonal".to_string(), diagonal(160, 96, true)),
18054 ];
18055 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
18056 for entry in clips.split(':').filter(|e| !e.is_empty()) {
18057 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
18058 let name = path.rsplit('/').next().unwrap_or(path).to_string();
18059 pictures.push((name, clip_frame(path, skip, 640, 352)));
18060 }
18061 }
18062 pictures
18063 }
18064
18065 /// What the six directional modes are worth, per picture, at whatever
18066 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
18067 /// no further, and how often the search picks one.
18068 #[test]
18069 #[ignore = "a sweep, not a gate"]
18070 fn probe_directional() {
18071 let _knobs = crate::speed::knob_write();
18072 let fctx = &crate::decode::FrameCtx::for_encoder();
18073 for (name, picture) in sweep_pictures() {
18074 let dc = ladder(&picture, &[DC_PRED], fctx);
18075 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
18076 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
18077 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
18078 let directional = encoded
18079 .modes
18080 .iter()
18081 .filter(|&&m| (3..=8).contains(&m))
18082 .count();
18083 // A picture whose ladders sit at different fidelities altogether
18084 // has no BD-rate to report -- see the flat-sample-window class.
18085 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
18086 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
18087 };
18088 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
18089 if overlap(a, b) {
18090 format!("{:+.2}%", bd_rate(a, b) * 100.0)
18091 } else {
18092 "no overlap".to_string()
18093 }
18094 };
18095 println!(
18096 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
18097 against(&flat, &all),
18098 against(&dc, &all),
18099 encoded.modes.len(),
18100 );
18101 }
18102 }
18103
18104 /// A picture whose stripes run along a diagonal, one way or the other.
18105 /// This is to the directional modes what [`stripes`] is to the vertical and
18106 /// horizontal pair: a predictor that walked the edge in the wrong direction
18107 /// would answer the two pictures the same way round.
18108 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
18109 let mut picture = Picture::grey(width, height);
18110 for y in 0..height {
18111 for x in 0..width {
18112 let along = if down_right { x + height - y } else { x + y };
18113 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
18114 }
18115 }
18116 picture
18117 }
18118
18119 /// The mode picked by the most blocks of a picture, ignoring the first
18120 /// block, which has no neighbours to tell the modes apart with.
18121 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
18122 // A mode ablation measures the MODE search: the palette would code
18123 // these synthetic two-colour pictures losslessly under every arm and
18124 // leave nothing to compare (see [`force_screen`]).
18125 force_screen(Some(false));
18126 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
18127 let blocks = &encoded.modes[1..];
18128 let mut counts = [0usize; 13];
18129 for &mode in blocks {
18130 counts[usize::from(mode)] += 1;
18131 }
18132 let (mode, count) = counts
18133 .iter()
18134 .enumerate()
18135 .max_by_key(|&(_, count)| *count)
18136 .expect("thirteen modes");
18137 (mode as u8, *count, blocks.len())
18138 }
18139
18140 /// The search has to follow a diagonal the way it runs: stripes down and to
18141 /// the right are cheapest predicted at 135 degrees, stripes down and to the
18142 /// left at 45. A walk that stepped the wrong way along the edge, or read
18143 /// the above row where it should read the left column, would swap these.
18144 #[test]
18145 fn the_search_picks_the_diagonal_the_picture_runs() {
18146 let _knobs = crate::speed::knob_write();
18147 let fctx = &crate::decode::FrameCtx::for_encoder();
18148 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
18149 let picture = diagonal(160, 96, down_right);
18150 let (mode, count, blocks) = favourite_mode(&picture, fctx);
18151 assert_eq!(
18152 mode, want,
18153 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
18154 );
18155 }
18156 }
18157
18158 /// What the directional modes are for: a picture that runs along a diagonal
18159 /// costs far less to code with them than the seven that read only their own
18160 /// edges can manage, and a picture that runs no particular way costs no
18161 /// more. The second half is the one that bites: a mode set the search
18162 /// cannot price is a mode set that loses rate on content that does not want
18163 /// it, which is what costing the mode symbol is for.
18164 #[test]
18165 fn the_diagonals_beat_the_modes_that_read_no_further() {
18166 let _knobs = crate::speed::knob_read();
18167 let fctx = &crate::decode::FrameCtx::for_encoder();
18168 for (name, picture, want) in [
18169 ("down-right", diagonal(160, 96, true), -0.20),
18170 ("down-left", diagonal(160, 96, false), -0.20),
18171 ("test card", test_card(160, 96), 0.01),
18172 ] {
18173 let saved = bd_rate(
18174 &ladder(&picture, &NON_DIRECTIONAL, fctx),
18175 &ladder(&picture, &KEY_FRAME_MODES, fctx),
18176 );
18177 assert!(
18178 saved < want,
18179 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
18180 saved * 100.0,
18181 -want * 100.0
18182 );
18183 }
18184 }
18185
18186 /// A mode the encoder cannot predict must be refused rather than coded as
18187 /// something else, and a search with nothing to choose from likewise.
18188 #[test]
18189 fn a_mode_the_encoder_cannot_predict_is_refused() {
18190 let _knobs = crate::speed::knob_read();
18191 let fctx = &crate::decode::FrameCtx::for_encoder();
18192 let picture = test_card(64, 64);
18193 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
18194 .unwrap_err()
18195 .to_string();
18196 assert!(
18197 message.contains("intra mode 13"),
18198 "the refusal must name the mode, got {message}"
18199 );
18200 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
18201 }
18202
18203 /// The picture that comes back is the picture that went in, to within the
18204 /// quantizer. A prediction that read the wrong neighbours, or a block
18205 /// written into the wrong place, would still decode to what the encoder
18206 /// reconstructed — it is this gate that says the reconstruction is of the
18207 /// right picture.
18208 #[test]
18209 fn the_encoded_picture_is_the_one_that_went_in() {
18210 let _knobs = crate::speed::knob_read();
18211 let fctx = &crate::decode::FrameCtx::for_encoder();
18212 let picture = test_card(160, 96);
18213 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18214 let luma = psnr(&encoded.reconstruction.y, &picture.y);
18215 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
18216 for (plane, (got, want)) in [
18217 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
18218 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
18219 ]
18220 .iter()
18221 .enumerate()
18222 {
18223 let chroma = psnr(got, want);
18224 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
18225 }
18226 }
18227
18228 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
18229 /// does the opposite. Both are monotone, which is what a rate-distortion
18230 /// loop above this will assume.
18231 #[test]
18232 fn fidelity_and_rate_move_with_the_quantizer() {
18233 let _knobs = crate::speed::knob_read();
18234 let fctx = &crate::decode::FrameCtx::for_encoder();
18235 let picture = test_card(128, 128);
18236 let mut previous: Option<(usize, f64)> = None;
18237 for &q in &[70u8, 90, 110] {
18238 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18239 let quality = psnr(&encoded.reconstruction.y, &picture.y);
18240 if let Some((bytes, better)) = previous {
18241 assert!(
18242 encoded.stream.len() < bytes,
18243 "q {q}: {} bytes",
18244 encoded.stream.len()
18245 );
18246 assert!(quality < better, "q {q}: PSNR {quality}");
18247 }
18248 previous = Some((encoded.stream.len(), quality));
18249 }
18250
18251 // The deadzone half of this claim lives in
18252 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
18253 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
18254 // every zeroing, the deadzone no longer moves a coded stream
18255 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
18256 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
18257 // job, not a quantiser defect.
18258
18259 // Bytes must not jump up across a q-context boundary: a wrong CDF
18260 // table for the far side would show up as a rate discontinuity here,
18261 // even though a coarser quantizer always codes no more than a finer
18262 // one on the same picture.
18263 //
18264 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
18265 // chroma searches its own mode, a coarser quantizer can pick a
18266 // *different* uv_mode on a block whose modes now cost nearly the
18267 // same, and the search prices that symbol against the static default
18268 // CDF while the writer codes it against an adapted one -- 311 -> 319
18269 // bytes at q 120->121 on this picture. The table this gate is really
18270 // watching would move the rate by far more than the mode churn does.
18271 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
18272 // same block can also change transform DEPTH between two neighbouring
18273 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
18274 // symbol is priced off the static CDF row 0 for the same reason the
18275 // uv_mode one is.
18276 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
18277 // path is pricing through the adapting CDF state (what
18278 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
18279 // drift of), after which the exact bound comes back.
18280 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
18281 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx)
18282 .unwrap()
18283 .stream
18284 .len();
18285 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx)
18286 .unwrap()
18287 .stream
18288 .len();
18289 assert!(
18290 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
18291 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
18292 );
18293 }
18294 }
18295
18296 /// A flat picture is a flat stream: every block predicts its neighbours'
18297 /// average, which is the picture's own value, and codes nothing.
18298 #[test]
18299 fn a_flat_picture_costs_almost_nothing() {
18300 let _knobs = crate::speed::knob_read();
18301 let fctx = &crate::decode::FrameCtx::for_encoder();
18302 let mut picture = Picture::grey(128, 128);
18303 picture.y.fill(97);
18304 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18305 // The first block has no neighbour and predicts 128, so it carries a
18306 // DC; every block after it predicts 97 and carries nothing.
18307 assert!(
18308 encoded.stream.len() < 100,
18309 "{} bytes for a flat picture",
18310 encoded.stream.len()
18311 );
18312 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
18313 assert_eq!(s, 97, "sample {i} of a flat picture");
18314 }
18315 }
18316
18317 /// The sizes the encoder refuses, refused for a reason rather than by
18318 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
18319 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
18320 /// lands past the halfway point of whichever block it falls in, so
18321 /// `PARTITION_NONE` or a single gathered split flag still says everything
18322 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
18323 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
18324 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
18325 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
18326 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
18327 /// refusal here claimed otherwise and was wrong; see
18328 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
18329 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
18330 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
18331 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
18332 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
18333 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
18334 /// still refused is a malformed picture.
18335 #[test]
18336 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
18337 let _knobs = crate::speed::knob_read();
18338 let fctx = &crate::decode::FrameCtx::for_encoder();
18339 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
18340 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
18341 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
18342 .expect("36 luma columns still round up to an even MiCols");
18343
18344 let mut short = Picture::grey(64, 64);
18345 short.u.truncate(10);
18346 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
18347 }
18348
18349 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
18350 /// column half only (`has_half` false on cols, true on rows) -- exactly
18351 /// the single-axis straddle lane-av1-rect r7 wires through
18352 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
18353 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
18354 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
18355 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
18356 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
18357 /// `partition_context_lookup` entry this writer ever produces (no 4x4
18358 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
18359 /// leaf regardless of neighbour state -- our writer already agreed with
18360 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
18361 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
18362 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
18363 /// it does not regress the gate. r11 tell-for-tell traced two further,
18364 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
18365 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
18366 /// leaves, when the second leaf's true above (or left) neighbour is the
18367 /// first leaf itself -- fixed by threading the first leaf's mode into the
18368 /// second leaf's context, mi-precise, like `record_mi` already does for
18369 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
18370 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
18371 /// `reduced_tx_set` is false), but this crate's key frames set
18372 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
18373 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
18374 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
18375 /// symbol bits to desync everything after it. Fixed with a new
18376 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
18377 /// eset/size slot). Both fixes are provably correct against libaom
18378 /// source and each closed part of the gap (leaf0's `eob` went from a
18379 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
18380 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
18381 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
18382 /// (do not reuse r11's committed logs, which predate its own fixes) and
18383 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
18384 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
18385 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
18386 /// every other `write_block` caller at 16x16 and up already passes
18387 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
18388 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
18389 /// different amount of arithmetic range and derailed everything after
18390 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
18391 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
18392 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
18393 /// never updating those coarse arrays itself -- so a *second* straddling
18394 /// 16x16 quadrant stacked above or left of the first (never covered by
18395 /// r11's same-call `prev_leaf` override, which only threads state
18396 /// between the two leaves of one shared quadrant) read whatever stale
18397 /// mode sat in that slot before either leaf ran. Fixed by writing the
18398 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
18399 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
18400 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
18401 /// offset of a single unit; fixing (3)+(4) together still leaves a
18402 /// residual divergence one leaf further in -- the decoder now reads
18403 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
18404 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
18405 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
18406 /// desyncs the stream by exactly the width of one earlier symbol -- not
18407 /// yet isolated to a single named symbol. r15 found the last bug: the
18408 /// header fix from r14 explained the rng skew fully, and the remaining
18409 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
18410 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
18411 /// loop, once per leaf, so the first leaf's write clobbered the true
18412 /// external neighbour mode the second leaf of the *same* straddling
18413 /// quadrant still needed for its non-adjacency axis (a column-straddle
18414 /// case: two leaves share one `outer_at` column index, so leaf 1's
18415 /// write to `left_mode[r]` overwrote the real western neighbour before
18416 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
18417 /// doing it once, after the whole leaf loop, from the last (bottom/
18418 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
18419 #[test]
18420 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
18421 let _knobs = crate::speed::knob_read();
18422 let fctx = &crate::decode::FrameCtx::for_encoder();
18423 if !have_ffmpeg() {
18424 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
18425 return;
18426 }
18427 let (width, height) = (40usize, 32usize);
18428 let picture = test_card(width, height);
18429 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18430 assert_eq!(
18431 (encoded.reconstruction.width, encoded.reconstruction.height),
18432 (width, height)
18433 );
18434 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
18435 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
18436 }
18437 let decoded = ffmpeg_decode(&encoded.stream, width, height);
18438 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
18439 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
18440 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
18441 }
18442
18443 /// A frame of real video, rather than a picture built to be easy.
18444 ///
18445 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
18446 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
18447 /// encoder's reconstruction has to survive the same equality gate as the
18448 /// synthetic pictures — real video reaches contexts a test card does not.
18449 #[test]
18450 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
18451 let _knobs = crate::speed::knob_read();
18452 let fctx = &crate::decode::FrameCtx::for_encoder();
18453 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
18454 eprintln!(
18455 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
18456 set EC_AV1_CLIP to a clip"
18457 );
18458 return;
18459 };
18460 if !have_ffmpeg() {
18461 eprintln!(
18462 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
18463 );
18464 return;
18465 }
18466 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
18467 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
18468 // test quick while still spanning many superblocks.
18469 let (width, height) = (640usize, 352usize);
18470 let picture = clip_frame(&clip, &skip, width, height);
18471
18472 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18473 let decoded = ffmpeg_decode(&encoded.stream, width, height);
18474 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
18475 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
18476 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
18477 eprintln!(
18478 "{} bytes, luma PSNR {:.2} dB",
18479 encoded.stream.len(),
18480 psnr(&decoded.y, &picture.y)
18481 );
18482 }
18483
18484 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
18485 /// sequence of these is a translation a motion search can actually find
18486 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
18487 /// inter frame's rate against the key frame's is measuring the same
18488 /// picture moving, not two different pictures.
18489 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
18490 let mut picture = Picture::grey(width, height);
18491 for y in 0..height {
18492 for x in 0..width {
18493 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
18494 let gradient = sx * 200.0 / width as f64;
18495 let ripple = 30.0
18496 * (sx * std::f64::consts::PI / 23.0).sin()
18497 * (y as f64 * std::f64::consts::PI / 37.0).cos();
18498 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
18499 40.0
18500 } else {
18501 0.0
18502 };
18503 picture.y[y * width + x] =
18504 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
18505 }
18506 }
18507 for y in 0..height / 2 {
18508 for x in 0..width / 2 {
18509 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
18510 let i = y * width / 2 + x;
18511 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
18512 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
18513 }
18514 }
18515 picture
18516 }
18517
18518 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
18519 fn ffmpeg_decode_sequence(
18520 stream: &[u8],
18521 width: usize,
18522 height: usize,
18523 frames: usize,
18524 ) -> Vec<Picture> {
18525 let out = run_with_stdin(
18526 Command::new("ffmpeg").args([
18527 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
18528 ]),
18529 stream,
18530 );
18531 assert!(
18532 out.status.success(),
18533 "ffmpeg refused the stream: {}",
18534 String::from_utf8_lossy(&out.stderr)
18535 );
18536 let (luma, chroma) = (width * height, width * height / 4);
18537 let frame_bytes = luma + 2 * chroma;
18538 assert_eq!(
18539 out.stdout.len(),
18540 frame_bytes * frames,
18541 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
18542 String::from_utf8_lossy(&out.stderr)
18543 );
18544 (0..frames)
18545 .map(|i| {
18546 let base = i * frame_bytes;
18547 Picture {
18548 width,
18549 height,
18550 y: out.stdout[base..base + luma]
18551 .iter()
18552 .map(|&v| u16::from(v))
18553 .collect(),
18554 u: out.stdout[base + luma..base + luma + chroma]
18555 .iter()
18556 .map(|&v| u16::from(v))
18557 .collect(),
18558 v: out.stdout[base + luma + chroma..base + frame_bytes]
18559 .iter()
18560 .map(|&v| u16::from(v))
18561 .collect(),
18562 }
18563 })
18564 .collect()
18565 }
18566
18567 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
18568 /// makes for a key frame, extended down the reference chain: each inter
18569 /// frame's reconstruction predicts from the previous frame's own decoded
18570 /// reconstruction, so a single sample of drift anywhere would propagate
18571 /// into every frame after it -- which is why every frame is checked, not
18572 /// just the last one, and why this is an equality and not a tolerance.
18573 #[test]
18574 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
18575 let _knobs = crate::speed::knob_read();
18576 let fctx = &crate::decode::FrameCtx::for_encoder();
18577 if !have_ffmpeg() {
18578 eprintln!(
18579 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
18580 );
18581 return;
18582 }
18583 let (width, height) = (128usize, 64usize);
18584 let pictures: Vec<Picture> = (0..5)
18585 .map(|i| panned_test_card(width, height, i * 3))
18586 .collect();
18587 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18588 assert_eq!(encoded.frames.len(), 5);
18589
18590 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
18591 assert_eq!(
18592 encoded.frames.len(),
18593 decoded.len(),
18594 "frame count: ours vs ffmpeg"
18595 );
18596 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18597 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
18598 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
18599 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
18600 }
18601
18602 eprintln!("frame bytes luma PSNR (dB) inter share");
18603 for (i, frame) in encoded.frames.iter().enumerate() {
18604 eprintln!(
18605 "{i:5} {:5} {:14.2} {:11.2}",
18606 frame.stream.len(),
18607 psnr(&frame.reconstruction.y, &pictures[i].y),
18608 frame.inter_block_share
18609 );
18610 }
18611 }
18612
18613 /// The same sequence through OUR OWN decoder, sample-exact against the
18614 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
18615 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
18616 /// divergence point at all, while our decoder can be traced symbol by
18617 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
18618 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
18619 /// names the first differing frame, plane and position.
18620 /// lane-sb128b: the writer used to price a `NEWMV` residual against
18621 /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
18622 /// write-time stack could not carry, while the drl symbols signalled the
18623 /// clamped index -- so the decoder derived a DIFFERENT motion vector with
18624 /// the entropy stream still in sync, and the drift only surfaced frames
18625 /// later as a drl desync (on film B, as the encoder's own trial decode
18626 /// refusing a reference slot).
18627 ///
18628 /// The clamp needs a stack that shrinks between search and write, which
18629 /// is what a 128x128 superblock's visit order does; the counter is the
18630 /// point (class `gate-blind-to-feature`): a green round trip on a clip
18631 /// that never clamps proves nothing.
18632 ///
18633 /// `#[ignore]`: [`force_sb128`] moves a process-global.
18634 ///
18635 /// The drl-clamp cell this gate's counter used to gate is no longer gated
18636 /// here: it is covered by
18637 /// [`every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`],
18638 /// which enumerates the pricer's offer set against the writer's rule (see
18639 /// its doc). The clamp needs a stack that shrinks between search and
18640 /// write, which is what a 128x128 superblock's visit order would do -- but
18641 /// the pricer never offers an index this tree's `write_drl_idx` cannot
18642 /// signal, so no clip can provoke it (lane-av1recipehunt: 153 attempts, 0;
18643 /// widening the pricer to `0..5` fires the counter immediately, reverting
18644 /// silences it). `drl_clamp_hits` is kept as the tripwire for that fix.
18645
18646 /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
18647 /// and one motion vector where the four 64x64 roots below spend four of
18648 /// each (cen3's L1). The counter is the gate on the fixture (class
18649 /// `gate-blind-to-feature`): a green round trip on a clip that never
18650 /// codes a 128x128 block proves nothing. RED before the search existed
18651 /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
18652 /// root by construction).
18653 ///
18654 /// Both readers: our own decoder sample-exact against the encoder's
18655 /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
18656 /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
18657 ///
18658 /// `#[ignore]`: [`force_sb128`] moves a process-global.
18659 ///
18660 /// cargo test -p ec-av1 --release --lib -- --ignored \
18661 /// a_128_superblock_clip_whose_root_search --nocapture
18662 #[test]
18663 #[ignore = "sets the process-global superblock size: run it alone"]
18664 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
18665 let _knobs = crate::speed::knob_write();
18666 if !have_ffmpeg() {
18667 eprintln!("SKIP: no ffmpeg");
18668 return;
18669 }
18670 force_sb128(true);
18671 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
18672 std::fs::create_dir_all(&dir).unwrap();
18673 let clip = dir.join("smpte-1280x768.y4m");
18674 // A slow horizontal pan over a still pattern: whole 128x128 regions
18675 // share one motion vector, which is exactly what a 128 root can code
18676 // as one block and four 64 roots cannot.
18677 let ok = Command::new("ffmpeg")
18678 .args(["-v", "error", "-y", "-f", "lavfi"])
18679 .args(["-i", "smptebars=size=1600x768:rate=24"])
18680 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
18681 .args(["-pix_fmt", "yuv420p"])
18682 .arg(&clip)
18683 .status()
18684 .expect("ffmpeg failed to run")
18685 .success();
18686 assert!(ok, "ffmpeg could not write the synthetic clip");
18687 let (width, height) = (1280usize, 768usize);
18688 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
18689 let _ = take_b128_none_hits();
18690 let _ = crate::tile::take_sb128_none_hits();
18691 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
18692 let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
18693 eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
18694 assert!(
18695 coded > 0,
18696 "no 128x128 block was coded on this clip, so it cannot witness the root search",
18697 );
18698 assert_eq!(
18699 won, coded,
18700 "every 128x128 root the search took must be coded as one"
18701 );
18702 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18703 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18704 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18705 let recon = &frame.reconstruction;
18706 for (plane, got, want) in [
18707 ("luma", &dec.y, &recon.y),
18708 ("U", &dec.u, &recon.u),
18709 ("V", &dec.v, &recon.v),
18710 ] {
18711 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18712 assert_eq!(
18713 differ,
18714 0,
18715 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18716 own reconstruction",
18717 got.len()
18718 );
18719 assert_eq!(
18720 got.len(),
18721 want.len(),
18722 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
18723 got.len(),
18724 want.len()
18725 );
18726 }
18727 }
18728 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18729 assert_eq!(
18730 encoded.frames.len(),
18731 ff.len(),
18732 "frame count: ours vs ffmpeg"
18733 );
18734 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18735 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
18736 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
18737 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
18738 }
18739 }
18740
18741 /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
18742 /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
18743 /// same pan the skip-only witness above uses, with the arm FORCED
18744 /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
18745 /// about once per frame, which witnesses the shape but not every context
18746 /// it reads, and forcing codes all 420 roots of the clip through it. RED
18747 /// before this lane by construction (`write_inter_block_128` refused
18748 /// every non-skip 128 block, so no such block existed to decode), and RED
18749 /// again on the first draft of the writer, whose neighbour band recorded
18750 /// `skip = true` for a block that carries a residual -- the next root's
18751 /// `skip` symbol then took CDF row 1 where the reader takes row 0.
18752 ///
18753 /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces
18754 /// the skip arm's cost unconditionally (that is what makes the writer see
18755 /// the residual), and the cost model moved under it since lane-b128r --
18756 /// lane-rectdq made every non-skipped root pay its delta_q group and the
18757 /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root
18758 /// lost its partition at ALL 420 roots and the writer coded none. q=60
18759 /// puts 52 written blocks back on this clip; the `coded > 0` assert below
18760 /// is the guard that catches the next such drift.
18761 ///
18762 /// cargo test -p ec-av1 --release --lib -- --ignored \
18763 /// a_128_root_block_with_a_real_residual --nocapture
18764 #[test]
18765 #[ignore = "sets the process-global superblock size: run it alone"]
18766 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
18767 let _knobs = crate::speed::knob_write();
18768 if !have_ffmpeg() {
18769 eprintln!("SKIP: no ffmpeg");
18770 return;
18771 }
18772 force_sb128(true);
18773 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
18774 std::fs::create_dir_all(&dir).unwrap();
18775 let clip = dir.join("smpte-pan-1280x768.y4m");
18776 let ok = Command::new("ffmpeg")
18777 .args(["-v", "error", "-y", "-f", "lavfi"])
18778 .args(["-i", "smptebars=size=1600x768:rate=24"])
18779 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
18780 .args(["-pix_fmt", "yuv420p"])
18781 .arg(&clip)
18782 .status()
18783 .expect("ffmpeg failed to run")
18784 .success();
18785 assert!(ok, "ffmpeg could not write the synthetic clip");
18786 let (width, height) = (1280usize, 768usize);
18787 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
18788 let _ = take_b128_residual_hits();
18789 let _ = crate::tile::take_sb128_residual_hits();
18790 force_b128_residual(true);
18791 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
18792 let (won, coded) = (
18793 take_b128_residual_hits(),
18794 crate::tile::take_sb128_residual_hits(),
18795 );
18796 eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
18797 assert!(
18798 coded > 0,
18799 "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
18800 );
18801 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18802 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18803 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18804 let recon = &frame.reconstruction;
18805 for (plane, got, want) in [
18806 ("luma", &dec.y, &recon.y),
18807 ("U", &dec.u, &recon.u),
18808 ("V", &dec.v, &recon.v),
18809 ] {
18810 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18811 assert_eq!(
18812 differ,
18813 0,
18814 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18815 own reconstruction",
18816 got.len()
18817 );
18818 assert_eq!(
18819 got.len(),
18820 want.len(),
18821 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
18822 got.len(),
18823 want.len()
18824 );
18825 }
18826 }
18827 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18828 assert_eq!(
18829 encoded.frames.len(),
18830 ff.len(),
18831 "frame count: ours vs ffmpeg"
18832 );
18833 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18834 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
18835 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
18836 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
18837 }
18838 }
18839
18840 /// lane-edge128: a 128x128 root block WITH a residual on a clip whose
18841 /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec
18842 /// 5.11.56) codes ONE literal for the block that first reaches a unit and
18843 /// copies it over every unit the block SPANS, so the four units of a 128
18844 /// root share one index -- while the encoder's CDEF search prices a
18845 /// preset per unit and its filter replay applied all four. Only the first
18846 /// reached the stream, so every decoder filtered the other three with the
18847 /// origin's strengths and the encoder's reconstruction (the picture the
18848 /// next frame predicts from) was a filter apart from what a decoder
18849 /// produces. RED before this lane on the native BD gate's bars 2160p row
18850 /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples,
18851 /// the rows above the 128 superblock's own edge); the stream itself was
18852 /// always right -- ffmpeg and our own decoder agreed with each other and
18853 /// disagreed with the encoder.
18854 ///
18855 /// `take_cdef_covered_units` is the gate on the fixture (class
18856 /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair
18857 /// for the whole frame codes no literal at all and witnesses nothing.
18858 ///
18859 /// cargo test -p ec-av1 --release --lib -- --ignored \
18860 /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture
18861 #[test]
18862 #[ignore = "sets the process-global superblock size: run it alone"]
18863 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
18864 let _knobs = crate::speed::knob_write();
18865 if !have_ffmpeg() {
18866 eprintln!("SKIP: no ffmpeg");
18867 return;
18868 }
18869 force_sb128(true);
18870 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
18871 std::fs::create_dir_all(&dir).unwrap();
18872 let clip = dir.join("testsrc2-1280x768.y4m");
18873 // Detailed synthetic content: its CDEF search spends more than one
18874 // strength pair, which is what puts a `cdef_idx` literal in the tile.
18875 let ok = Command::new("ffmpeg")
18876 .args(["-v", "error", "-y", "-f", "lavfi"])
18877 .args(["-i", "testsrc2=size=1280x768:rate=24"])
18878 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
18879 .arg(&clip)
18880 .status()
18881 .expect("ffmpeg failed to run")
18882 .success();
18883 assert!(ok, "ffmpeg could not write the synthetic clip");
18884 let (width, height) = (1280usize, 768usize);
18885 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
18886 force_b128_root(true);
18887 force_b128_residual(true);
18888 let _ = crate::tile::take_sb128_residual_hits();
18889 let _ = crate::filter_search::take_cdef_covered_units();
18890 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
18891 let coded = crate::tile::take_sb128_residual_hits();
18892 let covered = crate::filter_search::take_cdef_covered_units();
18893 eprintln!(
18894 "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
18895 another unit's literal: {covered}"
18896 );
18897 assert!(
18898 coded > 0,
18899 "no 128x128 block carried a residual on this clip"
18900 );
18901 assert!(
18902 covered > 0,
18903 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
18904 cannot witness the rule",
18905 );
18906 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18907 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18908 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18909 for (plane, got, want) in [
18910 ("luma", &dec.y, &frame.reconstruction.y),
18911 ("U", &dec.u, &frame.reconstruction.u),
18912 ("V", &dec.v, &frame.reconstruction.v),
18913 ] {
18914 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18915 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
18916 assert_eq!(
18917 got.len(),
18918 want.len(),
18919 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
18920 got.len(),
18921 want.len()
18922 );
18923 }
18924 }
18925 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18926 assert_eq!(
18927 encoded.frames.len(),
18928 ff.len(),
18929 "frame count: ours vs ffmpeg"
18930 );
18931 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18932 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
18933 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
18934 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
18935 }
18936 }
18937
18938 /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
18939 /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
18940 /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
18941 /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
18942 /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
18943 /// rect partition with [`force_b128_rect`]) so every inter root of the
18944 /// clip goes through it; the `coded > 0` assert is the guard that catches
18945 /// the next fixture drift (the whole-128 twin of this witness went RED
18946 /// twice that way).
18947 ///
18948 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
18949 /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
18950 #[test]
18951 #[ignore = "sets the process-global superblock size: run it alone"]
18952 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
18953 let _knobs = crate::speed::knob_write();
18954 if !have_ffmpeg() {
18955 eprintln!("SKIP: no ffmpeg");
18956 return;
18957 }
18958 force_sb128(true);
18959 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
18960 std::fs::create_dir_all(&dir).unwrap();
18961 let clip = dir.join("smpte-pan-1280x768.y4m");
18962 let ok = Command::new("ffmpeg")
18963 .args(["-v", "error", "-y", "-f", "lavfi"])
18964 .args(["-i", "smptebars=size=1600x768:rate=24"])
18965 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
18966 .args(["-pix_fmt", "yuv420p"])
18967 .arg(&clip)
18968 .status()
18969 .expect("ffmpeg failed to run")
18970 .success();
18971 assert!(ok, "ffmpeg could not write the synthetic clip");
18972 let (width, height) = (1280usize, 768usize);
18973 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
18974 force_b128_rect(1);
18975 force_b128_rectres(true);
18976 let _ = take_b128_rectres_hits();
18977 let _ = crate::tile::take_sb128_rectres_hits();
18978 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
18979 let (won, coded) = (
18980 take_b128_rectres_hits(),
18981 crate::tile::take_sb128_rectres_hits(),
18982 );
18983 eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
18984 assert!(
18985 coded > 0,
18986 "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
18987 );
18988 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18989 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18990 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18991 let recon = &frame.reconstruction;
18992 for (plane, got, want) in [
18993 ("luma", &dec.y, &recon.y),
18994 ("U", &dec.u, &recon.u),
18995 ("V", &dec.v, &recon.v),
18996 ] {
18997 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18998 assert_eq!(
18999 differ,
19000 0,
19001 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
19002 own reconstruction",
19003 got.len()
19004 );
19005 assert_eq!(
19006 got.len(),
19007 want.len(),
19008 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19009 got.len(),
19010 want.len()
19011 );
19012 }
19013 }
19014 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19015 assert_eq!(
19016 encoded.frames.len(),
19017 ff.len(),
19018 "frame count: ours vs ffmpeg"
19019 );
19020 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19021 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19022 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19023 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19024 }
19025 }
19026
19027 /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
19028 /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
19029 /// the two 64x64 squares through the one-chunk arm (the shape libaom's
19030 /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
19031 /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
19032 /// reference picture the GOP has not produced yet, which refuses before
19033 /// any AB root is coded.
19034 ///
19035 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
19036 /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
19037 #[test]
19038 #[ignore = "sets the process-global superblock size: run it alone"]
19039 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
19040 let _knobs = crate::speed::knob_write();
19041 if !have_ffmpeg() {
19042 eprintln!("SKIP: no ffmpeg");
19043 return;
19044 }
19045 force_sb128(true);
19046 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
19047 std::fs::create_dir_all(&dir).unwrap();
19048 let clip = dir.join("testsrc2-1280x768.y4m");
19049 let ok = Command::new("ffmpeg")
19050 .args(["-v", "error", "-y", "-f", "lavfi"])
19051 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19052 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19053 .arg(&clip)
19054 .status()
19055 .expect("ffmpeg failed to run")
19056 .success();
19057 assert!(ok, "ffmpeg could not write the synthetic clip");
19058 let (width, height) = (1280usize, 768usize);
19059 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19060 force_b128_ab(4);
19061 force_b128_rectres(true);
19062 let _ = take_b128_rectres_hits();
19063 let _ = crate::tile::take_sb128_rectres_hits();
19064 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
19065 let (won, coded) = (
19066 take_b128_rectres_hits(),
19067 crate::tile::take_sb128_rectres_hits(),
19068 );
19069 eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
19070 assert!(
19071 coded > 0,
19072 "no AB piece carried a residual on this clip, so it cannot witness the arm",
19073 );
19074 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19075 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19076 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19077 let recon = &frame.reconstruction;
19078 for (plane, got, want) in [
19079 ("luma", &dec.y, &recon.y),
19080 ("U", &dec.u, &recon.u),
19081 ("V", &dec.v, &recon.v),
19082 ] {
19083 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19084 assert_eq!(
19085 differ,
19086 0,
19087 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
19088 own reconstruction",
19089 got.len()
19090 );
19091 assert_eq!(
19092 got.len(),
19093 want.len(),
19094 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19095 got.len(),
19096 want.len()
19097 );
19098 }
19099 }
19100 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19101 assert_eq!(
19102 encoded.frames.len(),
19103 ff.len(),
19104 "frame count: ours vs ffmpeg"
19105 );
19106 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19107 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19108 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19109 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19110 }
19111 }
19112
19113 /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
19114 /// half WITH a residual under a clip whose CDEF search codes a
19115 /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
19116 /// and the decoder stamps BOTH units it spans with it, so the owner map
19117 /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
19118 /// collapse the pair -- exactly the bug class that broke bars 2160p at
19119 /// the whole-128 root. RED before this lane by construction: no rect
19120 /// piece could carry a residual, so no such literal existed.
19121 ///
19122 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
19123 /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
19124 #[test]
19125 #[ignore = "sets the process-global superblock size: run it alone"]
19126 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
19127 let _knobs = crate::speed::knob_write();
19128 if !have_ffmpeg() {
19129 eprintln!("SKIP: no ffmpeg");
19130 return;
19131 }
19132 force_sb128(true);
19133 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
19134 std::fs::create_dir_all(&dir).unwrap();
19135 let clip = dir.join("testsrc2-1280x768.y4m");
19136 // Detailed synthetic content: its CDEF search spends more than one
19137 // strength pair, which is what puts a `cdef_idx` literal in the tile.
19138 let ok = Command::new("ffmpeg")
19139 .args(["-v", "error", "-y", "-f", "lavfi"])
19140 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19141 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19142 .arg(&clip)
19143 .status()
19144 .expect("ffmpeg failed to run")
19145 .success();
19146 assert!(ok, "ffmpeg could not write the synthetic clip");
19147 let (width, height) = (1280usize, 768usize);
19148 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19149 force_b128_rect(1);
19150 force_b128_rectres(true);
19151 let _ = crate::tile::take_sb128_rectres_hits();
19152 let _ = crate::filter_search::take_cdef_covered_units();
19153 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
19154 let coded = crate::tile::take_sb128_rectres_hits();
19155 let covered = crate::filter_search::take_cdef_covered_units();
19156 eprintln!(
19157 "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
19158 another unit's literal: {covered}"
19159 );
19160 assert!(coded > 0, "no 128x64 half carried a residual on this clip");
19161 assert!(
19162 covered > 0,
19163 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
19164 cannot witness the rule",
19165 );
19166 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19167 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19168 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19169 for (plane, got, want) in [
19170 ("luma", &dec.y, &frame.reconstruction.y),
19171 ("U", &dec.u, &frame.reconstruction.u),
19172 ("V", &dec.v, &frame.reconstruction.v),
19173 ] {
19174 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19175 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
19176 assert_eq!(
19177 got.len(),
19178 want.len(),
19179 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19180 got.len(),
19181 want.len()
19182 );
19183 }
19184 }
19185 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19186 assert_eq!(
19187 encoded.frames.len(),
19188 ff.len(),
19189 "frame count: ours vs ffmpeg"
19190 );
19191 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19192 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19193 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19194 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19195 }
19196 }
19197
19198 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
19199 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
19200 /// `write_compound_block` chain every smaller compound block takes, at a
19201 /// window it had never been exercised at. RED before this lane: the
19202 /// search passed an empty compound list at the 128 root, so the count was
19203 /// 0 and no such block existed to decode.
19204 ///
19205 /// cargo test -p ec-av1 --release --lib -- --ignored \
19206 /// a_128_root_compound_block --nocapture
19207 #[test]
19208 #[ignore = "sets the process-global superblock size: run it alone"]
19209 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
19210 let _knobs = crate::speed::knob_write();
19211 if !have_ffmpeg() {
19212 eprintln!("SKIP: no ffmpeg");
19213 return;
19214 }
19215 force_sb128(true);
19216 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
19217 std::fs::create_dir_all(&dir).unwrap();
19218 let clip = dir.join("testsrc2-1280x768.y4m");
19219 // Moving objects that occlude each other: a pan is coded by one
19220 // reference outright, and a compound pair only pays where the two
19221 // references disagree.
19222 let ok = Command::new("ffmpeg")
19223 .args(["-v", "error", "-y", "-f", "lavfi"])
19224 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19225 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19226 .arg(&clip)
19227 .status()
19228 .expect("ffmpeg failed to run")
19229 .success();
19230 assert!(ok, "ffmpeg could not write the synthetic clip");
19231 let (width, height) = (1280usize, 768usize);
19232 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19233 // The compound candidate wins the 128 block's own search on this pan
19234 // but the root then loses to its four cells, so the root is forced
19235 // (the residual arm is left at its default, off).
19236 force_b128_root(true);
19237 let _ = take_b128_compound_hits();
19238 let _ = crate::tile::take_sb128_compound_hits();
19239 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19240 let (won, coded) = (
19241 take_b128_compound_hits(),
19242 crate::tile::take_sb128_compound_hits(),
19243 );
19244 eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
19245 assert!(
19246 coded > 0,
19247 "no compound 128x128 block was coded on this clip"
19248 );
19249 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19250 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19251 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19252 for (plane, got, want) in [
19253 ("luma", &dec.y, &frame.reconstruction.y),
19254 ("U", &dec.u, &frame.reconstruction.u),
19255 ("V", &dec.v, &frame.reconstruction.v),
19256 ] {
19257 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19258 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
19259 assert_eq!(
19260 got.len(),
19261 want.len(),
19262 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19263 got.len(),
19264 want.len()
19265 );
19266 }
19267 }
19268 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19269 assert_eq!(
19270 encoded.frames.len(),
19271 ff.len(),
19272 "frame count: ours vs ffmpeg"
19273 );
19274 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19275 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19276 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19277 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19278 }
19279 }
19280
19281 /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
19282 /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
19283 /// square. Three passes over one `testsrc2` clip:
19284 ///
19285 /// * HORZ forced at every root ([`force_b128_rect`]), so every context
19286 /// the 128x64 shape reads is exercised rather than the handful the RD
19287 /// would pick;
19288 /// * VERT forced the same way;
19289 /// * UNFORCED, which is the count the gate rows are read against -- the
19290 /// same clip with the RD free to choose among NONE / HORZ / VERT /
19291 /// four superblocks.
19292 ///
19293 /// Each pass is sample-exact against the encoder's own reconstruction
19294 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
19295 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
19296 /// before this lane by construction: `write_sb128_root` could only name
19297 /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
19298 ///
19299 /// cargo test -p ec-av1 --release --lib -- --ignored \
19300 /// a_128_root_horz_and_vert --nocapture
19301 #[test]
19302 #[ignore = "sets the process-global superblock size: run it alone"]
19303 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
19304 let _knobs = crate::speed::knob_write();
19305 if !have_ffmpeg() {
19306 eprintln!("SKIP: no ffmpeg");
19307 return;
19308 }
19309 force_sb128(true);
19310 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
19311 std::fs::create_dir_all(&dir).unwrap();
19312 let clip = dir.join("testsrc2-1280x768.y4m");
19313 let ok = Command::new("ffmpeg")
19314 .args(["-v", "error", "-y", "-f", "lavfi"])
19315 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19316 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19317 .arg(&clip)
19318 .status()
19319 .expect("ffmpeg failed to run")
19320 .success();
19321 assert!(ok, "ffmpeg could not write the synthetic clip");
19322 let (width, height) = (1280usize, 768usize);
19323 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19324 let mut unforced = (0usize, 0usize);
19325 for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
19326 force_b128_rect(force);
19327 let _ = take_b128_horz_hits();
19328 let _ = take_b128_vert_hits();
19329 let _ = crate::tile::take_sb128_horz_hits();
19330 let _ = crate::tile::take_sb128_vert_hits();
19331 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19332 let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
19333 let (coded_h, coded_v) = (
19334 crate::tile::take_sb128_horz_hits(),
19335 crate::tile::take_sb128_vert_hits(),
19336 );
19337 eprintln!(
19338 "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
19339 {coded_h} 128x64 + {coded_v} 64x128 halves"
19340 );
19341 match force {
19342 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
19343 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
19344 // The unforced count is REPORTED, not asserted: it is the
19345 // number the gate is read against, and a zero here would be
19346 // an RD result, not a defect (the forced passes already prove
19347 // the writer and the reader agree on the shape).
19348 _ => unforced = (won_h, won_v),
19349 }
19350 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19351 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
19352 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19353 for (plane, got, want) in [
19354 ("luma", &dec.y, &frame.reconstruction.y),
19355 ("U", &dec.u, &frame.reconstruction.u),
19356 ("V", &dec.v, &frame.reconstruction.v),
19357 ] {
19358 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19359 assert_eq!(
19360 differ, 0,
19361 "{label} frame {i}: {plane} -- {differ} samples differ"
19362 );
19363 assert_eq!(
19364 got.len(),
19365 want.len(),
19366 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
19367 got.len(),
19368 want.len()
19369 );
19370 }
19371 }
19372 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19373 assert_eq!(
19374 encoded.frames.len(),
19375 ff.len(),
19376 "{label}: frame count: ours vs ffmpeg"
19377 );
19378 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19379 assert_eq!(
19380 dec.y, frame.reconstruction.y,
19381 "{label} frame {i}: ffmpeg luma"
19382 );
19383 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
19384 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
19385 }
19386 }
19387 force_b128_rect(0);
19388 eprintln!(
19389 "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
19390 unforced.0, unforced.1
19391 );
19392 }
19393
19394 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
19395 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
19396 /// Five passes over the same `testsrc2` clip
19397 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
19398 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
19399 /// context and every visit order the shape reads is exercised rather than
19400 /// the handful the RD would pick, and then an UNFORCED pass whose
19401 /// per-shape count is REPORTED (it is the number the gate rows are read
19402 /// against).
19403 ///
19404 /// Each pass is sample-exact against the encoder's own reconstruction
19405 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
19406 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
19407 /// before this lane by construction: `write_sb128_root` could only name
19408 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
19409 ///
19410 /// cargo test -p ec-av1 --release --lib -- --ignored \
19411 /// a_128_root_ab_shapes --nocapture
19412 #[test]
19413 #[ignore = "sets the process-global superblock size: run it alone"]
19414 fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
19415 let _knobs = crate::speed::knob_write();
19416 if !have_ffmpeg() {
19417 eprintln!("SKIP: no ffmpeg");
19418 return;
19419 }
19420 force_sb128(true);
19421 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
19422 std::fs::create_dir_all(&dir).unwrap();
19423 let clip = dir.join("testsrc2-1280x768.y4m");
19424 let ok = Command::new("ffmpeg")
19425 .args(["-v", "error", "-y", "-f", "lavfi"])
19426 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19427 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19428 .arg(&clip)
19429 .status()
19430 .expect("ffmpeg failed to run")
19431 .success();
19432 assert!(ok, "ffmpeg could not write the synthetic clip");
19433 let (width, height) = (1280usize, 768usize);
19434 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19435 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
19436 let mut unforced = [0usize; 4];
19437 for force in [4u8, 5, 6, 7, 0] {
19438 force_b128_ab(force);
19439 let label = if force == 0 {
19440 "unforced"
19441 } else {
19442 names[usize::from(force) - 4]
19443 };
19444 let _ = take_b128_ab_hits();
19445 let _ = crate::tile::take_sb128_ab_hits();
19446 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19447 let won = take_b128_ab_hits();
19448 let coded = crate::tile::take_sb128_ab_hits();
19449 eprintln!(
19450 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
19451 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
19452 );
19453 if force == 0 {
19454 // The unforced counts are REPORTED, not asserted: a zero here
19455 // would be an RD result, not a defect (the four forced passes
19456 // already prove the writer and the reader agree on the shape).
19457 unforced = won;
19458 } else {
19459 let i = usize::from(force) - 4;
19460 assert!(
19461 coded[i] > 0,
19462 "no {label} root was coded with {label} forced"
19463 );
19464 }
19465 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19466 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
19467 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19468 for (plane, got, want) in [
19469 ("luma", &dec.y, &frame.reconstruction.y),
19470 ("U", &dec.u, &frame.reconstruction.u),
19471 ("V", &dec.v, &frame.reconstruction.v),
19472 ] {
19473 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19474 assert_eq!(
19475 differ, 0,
19476 "{label} frame {i}: {plane} -- {differ} samples differ"
19477 );
19478 assert_eq!(
19479 got.len(),
19480 want.len(),
19481 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
19482 got.len(),
19483 want.len()
19484 );
19485 }
19486 }
19487 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19488 assert_eq!(
19489 encoded.frames.len(),
19490 ff.len(),
19491 "{label}: frame count: ours vs ffmpeg"
19492 );
19493 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19494 assert_eq!(
19495 dec.y, frame.reconstruction.y,
19496 "{label} frame {i}: ffmpeg luma"
19497 );
19498 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
19499 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
19500 }
19501 }
19502 force_b128_ab(0);
19503 eprintln!(
19504 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
19505 unforced[0], unforced[1], unforced[2], unforced[3],
19506 );
19507 }
19508
19509 #[test]
19510 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
19511 let _knobs = crate::speed::knob_read();
19512 let fctx = &crate::decode::FrameCtx::for_encoder();
19513 // 256x128, not the 128x64 this started at: once a leaf could search
19514 // its second reference (lane-av1comp4) the small card's every
19515 // eligible block went to a compound winner, which commits its flat
19516 // transform, and the split below stopped firing on content that
19517 // still splits at every larger size ([[gate-blind-to-feature]] --
19518 // the guard is right, the fixture had shrunk under it).
19519 let (width, height) = (256usize, 128usize);
19520 let pictures: Vec<Picture> = (0..5)
19521 .map(|i| panned_test_card(width, height, i * 3))
19522 .collect();
19523 let _ = take_inter_tx_split_hits();
19524 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19525 let raw = take_inter_tx_split_hits();
19526 // Summed over the four block classes the census keys on (leaf/32x32 x
19527 // single/compound): this assert is about the split firing at all.
19528 let split = [
19529 raw.iter().step_by(2).sum::<usize>(),
19530 raw.iter().skip(1).step_by(2).sum::<usize>(),
19531 ];
19532 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
19533 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
19534 // content splits -- a green round trip in which the split never fires
19535 // would prove only the flat path.
19536 if tx_select() && tx_select_inter() {
19537 assert!(split[1] > 0, "the inter var-tx split never fired");
19538 }
19539 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19540 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19541 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19542 let recon = &frame.reconstruction;
19543 for (plane, got, want, stride) in [
19544 ("luma", &dec.y, &recon.y, width),
19545 ("U", &dec.u, &recon.u, width / 2),
19546 ("V", &dec.v, &recon.v, width / 2),
19547 ] {
19548 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
19549 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
19550 panic!(
19551 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
19552 reconstruction {} ({} of {} samples differ)",
19553 at % stride,
19554 at / stride,
19555 got[at],
19556 want[at],
19557 got.iter().zip(want).filter(|(a, b)| a != b).count(),
19558 got.len(),
19559 );
19560 }
19561 }
19562 }
19563 }
19564
19565 /// The rate term the mode search ranks every decision by has to be the
19566 /// rate the writer then spends. The search prices a block's coefficients
19567 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
19568 /// against the default CDFs a tile starts from and the contexts of a
19569 /// block whose neighbours coded nothing -- while the tile writer codes
19570 /// them against a state that has been adapting all frame (the
19571 /// price-the-narrowing class). This measures that drift: the sum of what
19572 /// the search paid for the coefficients it kept, against the bytes the
19573 /// writer actually emitted for the whole tile (which also carries the
19574 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
19575 /// expected to be the larger of the two).
19576 #[test]
19577 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
19578 let _knobs = crate::speed::knob_read();
19579 let fctx = &crate::decode::FrameCtx::for_encoder();
19580 let (width, height) = (256usize, 128usize);
19581 let pictures: Vec<Picture> = (0..5)
19582 .map(|i| panned_test_card(width, height, i * 2))
19583 .collect();
19584 let _ = take_predicted_bits();
19585 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19586 let predicted = take_predicted_bits();
19587 assert_eq!(predicted.len(), encoded.frames.len());
19588
19589 eprintln!("frame predicted bits written bits drift");
19590 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
19591 // defect this gate exists to catch), a positive one is the written
19592 // side carrying syntax the coefficient sum leaves out -- and since
19593 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
19594 // on that side, so the two directions no longer share a bound.
19595 let mut worst_over: f64 = 0.0;
19596 let mut worst_under: f64 = 0.0;
19597 // The census is per CODED frame, so it is zipped in coding order --
19598 // which is not display order under a pyramid.
19599 let coded: Vec<&Encoded> = encoded
19600 .coding_order
19601 .iter()
19602 .map(|&i| &encoded.frames[i])
19603 .collect();
19604 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
19605 let written = frame.tile.len() as f64 * 8.0;
19606 let drift = (written - bits) / written;
19607 worst_over = worst_over.max(-drift);
19608 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
19609 // all (150-250 bits of tile, nearly all of it partition/mode/mv
19610 // syntax the coefficient sum never counts), so its ratio measures
19611 // that floor rather than any drift. Frames under 512 written bits
19612 // are left out of the under-price bound for that reason; the
19613 // over-price bound -- the defect direction, where the search pays
19614 // MORE than the writer -- still covers every frame.
19615 if written >= 512.0 {
19616 worst_under = worst_under.max(drift);
19617 }
19618 eprintln!(
19619 "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
19620 drift * 100.0
19621 );
19622 }
19623 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
19624 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
19625 // over-prices every frame but the last (its sum EXCLUDES the
19626 // partition/mode/skip/mv syntax the written side carries, so the true
19627 // coefficient over-price is larger still): the writer's CDFs adapt to
19628 // the content while the search's stay at the defaults. The bound is
19629 // set just above the worst measured point -- a widening drift is the
19630 // thing this gate exists to catch.
19631 assert!(
19632 worst_over <= 0.16,
19633 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
19634 worst_over * 100.0
19635 );
19636 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
19637 // the worst inter frame, where nearly every block now codes an MV
19638 // residual and a reference the coefficient sum never counts. Re-measured
19639 // at +29.6% once the encoder's grid published compound blocks properly
19640 // (compound share 8.8% -> 11.5%): a compound block carries a second
19641 // reference tree, a compound mode symbol and -- for the half-new modes
19642 // -- an MV residual, none of which the coefficient sum counts.
19643 // lane-av1txbits: pricing against the tables the frame's writer really
19644 // starts from collapses the over-price above to nothing, so the whole
19645 // remaining gap is the syntax the coefficient sum leaves out. That is
19646 // the default on a non-screen frame since lane-av1price2 (this
19647 // fixture is one), and it reads +32.6% here.
19648 // lane-av1obmc: every eligible single-reference inter block now also
19649 // carries a `motion_mode` symbol the coefficient sum never counts,
19650 // and an OBMC block carries the more expensive of the two values --
19651 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
19652 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
19653 // decisions, so this bound and the byte pins above FAIL BY DESIGN
19654 // under it; the default path (no motion_mode syntax at all) is the
19655 // one they are measured on.
19656 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
19657 // coding pyramid now, so the five frames are a key frame, a hidden
19658 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
19659 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
19660 // near-empty leaves below it. Both bounds stand where they were.
19661 // lane-av1rejudge: local warp is ON by default now, so every eligible
19662 // single-reference block carries that same `motion_mode` symbol (a
19663 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
19664 // +34.9% here, one point past the OBMC reading above. The bound moves
19665 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
19666 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
19667 // symbol and one or two magnitude symbols, none of which the
19668 // coefficient sum counts either -- +36.9% here against the same
19669 // fixture's +34.9% with `EC_AV1_CFL=0`.
19670 // ... and a directional block whose `angle_delta_y` is no longer
19671 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
19672 assert!(
19673 worst_under <= 0.40,
19674 "the writer spent {:.2}% more than the search priced -- more than \
19675 the mode/mv syntax outside the coefficient sum explains",
19676 worst_under * 100.0
19677 );
19678 }
19679
19680 /// The census behind step (1) of the pricer lane: for every transform
19681 /// block the writer really codes, what the search priced those levels at
19682 /// against what the writer spent on them, split by table set and non-zero
19683 /// count. One average hides the interesting part -- the classes the
19684 /// estimate is systematically wrong about (all-zero blocks, the
19685 /// one-coefficient blocks the inter search lives on) -- so the split is
19686 /// printed and only the total is asserted on.
19687 #[test]
19688 fn pricer_error_census_by_block_class() {
19689 let _knobs = crate::speed::knob_read();
19690 let fctx = &crate::decode::FrameCtx::for_encoder();
19691 let (width, height) = (256usize, 128usize);
19692 let pictures: Vec<Picture> = (0..5)
19693 .map(|i| panned_test_card(width, height, i * 2))
19694 .collect();
19695 crate::tile::pricer_census_on();
19696 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19697 let rows = crate::tile::take_pricer_census();
19698 assert!(!rows.is_empty(), "the census saw no transform block");
19699
19700 println!("| set | nz | blocks | priced bits | written bits | error |");
19701 println!("|---|---|---|---|---|---|");
19702 let (mut priced_all, mut written_all) = (0.0, 0.0);
19703 for ((set, bucket), (blocks, priced, written)) in &rows {
19704 priced_all += priced;
19705 written_all += written;
19706 println!(
19707 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
19708 crate::tile::census_bucket_label(*bucket),
19709 if *written > 0.0 {
19710 (priced - written) / written * 100.0
19711 } else {
19712 0.0
19713 }
19714 );
19715 }
19716 println!(
19717 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
19718 rows.values().map(|r| r.0).sum::<u64>(),
19719 (priced_all - written_all) / written_all * 100.0
19720 );
19721 assert!(written_all > 0.0);
19722 }
19723
19724 /// Step (2) of the pricer lane: the same census, but on the REAL clips
19725 /// the BD gate scores -- one film clip and the screen capture -- so the
19726 /// question the film/screen split raises can be answered from data. Real
19727 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
19728 /// the screen capture larger, and the census says why: on a screen
19729 /// capture the frame's own starting tables are the tables of a frame that
19730 /// coded PALETTE and long runs of zero blocks, so they are far from the
19731 /// tables the writer ends the frame with; the pricer error does not fall
19732 /// the way it does on film.
19733 ///
19734 /// Not a gate -- it prints. Run it once per mode:
19735 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
19736 /// --ignored pricer_error_census_on_clips --nocapture
19737 #[test]
19738 #[ignore = "reads the real library, needs ffmpeg"]
19739 fn pricer_error_census_on_clips() {
19740 let _knobs = crate::speed::knob_write();
19741 if !have_ffmpeg() {
19742 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
19743 return;
19744 }
19745 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first),
19746 // so this probe reads the same tree the preflight validates. Its
19747 // `assert!(!clips.is_empty())` below was already a hard failure, so no
19748 // skip shape changes here — only the root does.
19749 let fixtures = crate::library_fixture::root();
19750 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
19751 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
19752 if film.exists() {
19753 clips.push(("film 1080p".to_string(), film));
19754 }
19755 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
19756 && let Some(p) = manifest
19757 .lines()
19758 .skip(1)
19759 .filter_map(|l| l.split('\t').next())
19760 .find(|p| {
19761 p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
19762 })
19763 {
19764 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
19765 }
19766 assert!(!clips.is_empty(), "no source clip available");
19767 let (width, height, frames) = (640usize, 384usize, 6usize);
19768 for (name, path) in &clips {
19769 let fctx = &crate::decode::FrameCtx::for_encoder();
19770 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
19771 SCREEN_FRAMES.iter().for_each(|c| {
19772 c.store(0, std::sync::atomic::Ordering::Relaxed);
19773 });
19774 let _ = crate::tile::take_pricing_hits();
19775 crate::tile::pricer_census_on();
19776 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
19777 let rows = crate::tile::take_pricer_census();
19778 let (price_default, price_real) = crate::tile::take_pricing_hits();
19779 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
19780 println!(
19781 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
19782 {screen_on}, pricer armings default={price_default} real={price_real}"
19783 );
19784 println!("| set | nz | blocks | priced bits | written bits | error |");
19785 println!("|---|---|---|---|---|---|");
19786 let (mut priced_all, mut written_all) = (0.0, 0.0);
19787 for ((set, bucket), (blocks, priced, written)) in &rows {
19788 priced_all += priced;
19789 written_all += written;
19790 println!(
19791 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
19792 crate::tile::census_bucket_label(*bucket),
19793 if *written > 0.0 {
19794 (priced - written) / written * 100.0
19795 } else {
19796 0.0
19797 }
19798 );
19799 }
19800 println!(
19801 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
19802 rows.values().map(|r| r.0).sum::<u64>(),
19803 (priced_all - written_all) / written_all * 100.0
19804 );
19805 assert!(
19806 written_all > 0.0,
19807 "{name}: the census saw no transform block"
19808 );
19809 }
19810 }
19811
19812 /// Low motion has to actually buy something: at least one inter frame of
19813 /// a panning sequence has to cost fewer bytes than the key frame that
19814 /// starts it, and the inter-block share it prints has to be non-zero --
19815 /// a search that never picks an inter mode would still pass a rate gate
19816 /// on a picture with no motion in it (the class this repo calls
19817 /// gate-blind-to-feature), so the share is printed even though it is not
19818 /// asserted on beyond being reachable at all.
19819 #[test]
19820 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
19821 let _knobs = crate::speed::knob_read();
19822 let fctx = &crate::decode::FrameCtx::for_encoder();
19823 let (width, height) = (256usize, 128usize);
19824 let pictures: Vec<Picture> = (0..5)
19825 .map(|i| panned_test_card(width, height, i * 2))
19826 .collect();
19827 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19828
19829 let key_bytes = encoded.frames[0].stream.len();
19830 eprintln!("frame bytes inter share");
19831 for (i, frame) in encoded.frames.iter().enumerate() {
19832 eprintln!(
19833 "{i:5} {:5} {:11.2}",
19834 frame.stream.len(),
19835 frame.inter_block_share
19836 );
19837 }
19838 assert!(
19839 encoded.frames[1..]
19840 .iter()
19841 .any(|f| f.stream.len() < key_bytes),
19842 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
19843 );
19844 assert!(
19845 encoded.frames[1..]
19846 .iter()
19847 .any(|f| f.inter_block_share > 0.0),
19848 "no inter frame coded a single inter block -- the search never fired"
19849 );
19850 }
19851
19852 /// A manual perf probe, not a gate: prints where a key frame's and an
19853 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
19854 /// measures before it optimizes rather than guessing. Run with
19855 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
19856 #[test]
19857 #[ignore = "a perf probe, not a gate"]
19858 fn stage_timing_breakdown() {
19859 let _knobs = crate::speed::knob_read();
19860 let fctx = &crate::decode::FrameCtx::for_encoder();
19861 use std::time::Instant;
19862
19863 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
19864 let picture = test_card(width, height);
19865
19866 let t = Instant::now();
19867 let dc_only =
19868 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
19869 let dc_only_t = t.elapsed();
19870
19871 let t = Instant::now();
19872 let non_directional =
19873 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx)
19874 .unwrap();
19875 let non_directional_t = t.elapsed();
19876
19877 let t = Instant::now();
19878 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
19879 let all_modes_t = t.elapsed();
19880
19881 eprintln!(
19882 "\n=== key frame {width}x{height} ===\n\
19883 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
19884 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
19885 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
19886 dc_only.stream.len(),
19887 non_directional.stream.len(),
19888 all_modes.stream.len(),
19889 );
19890
19891 // One inter frame predicting off the key frame's own
19892 // reconstruction, the (256, 256)-padded surface encode_sequence
19893 // itself would hand encode_inter_frame.
19894 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
19895 let padded_pic = picture.padded_to(SUPERBLOCK);
19896 let t = Instant::now();
19897 let inter = encode_inter_frame(
19898 &padded_pic,
19899 &padded_ref,
19900 100,
19901 0.5,
19902 1,
19903 flat_order_hints(1, 0, false),
19904 (width, height),
19905 None,
19906 None,
19907 None,
19908 None,
19909 fctx,
19910 None,
19911 &[],
19912 )
19913 .unwrap();
19914 let inter_t = t.elapsed();
19915 eprintln!(
19916 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
19917 {:.2})",
19918 inter.stream.len(),
19919 inter.inter_block_share
19920 );
19921 }
19922
19923 // Isolated per-call cost of the trial pipeline's own stages, at both
19924 // transform sizes the search runs, averaged over enough calls to
19925 // rise above `Instant::now`'s own noise.
19926 for side in [16usize, 32] {
19927 const N: u32 = 20_000;
19928 let residual: Vec<i32> = (0..side * side)
19929 .map(|i| ((i * 37 % 61) as i32) - 30)
19930 .collect();
19931
19932 let t = Instant::now();
19933 let mut levels = Vec::new();
19934 for _ in 0..N {
19935 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
19936 }
19937 let forward_t = t.elapsed() / N;
19938
19939 let t = Instant::now();
19940 for _ in 0..N {
19941 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
19942 }
19943 let inverse_t = t.elapsed() / N;
19944
19945 let set = if side == 32 {
19946 crate::cdf_state::TxbSet::Luma32
19947 } else {
19948 crate::cdf_state::TxbSet::Luma16
19949 };
19950 let t = Instant::now();
19951 for _ in 0..N {
19952 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
19953 }
19954 let entropy_t = t.elapsed() / N;
19955
19956 let above = vec![128u8; side * 2];
19957 let left = vec![128u8; side * 2];
19958 let mut prediction = vec![0u8; side * side];
19959 let t = Instant::now();
19960 for _ in 0..N {
19961 intra_predict_u8(
19962 D45_PRED,
19963 0,
19964 Some(&above),
19965 Some(&left),
19966 Some(128),
19967 side,
19968 side,
19969 false,
19970 false,
19971 &mut prediction,
19972 fctx,
19973 );
19974 }
19975 let predict_t = t.elapsed() / N;
19976
19977 eprintln!(
19978 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
19979 predict (1 directional mode): {predict_t:>9.2?}\n\
19980 forward_and_quantize: {forward_t:>9.2?}\n\
19981 dequant_and_inverse: {inverse_t:>9.2?}\n\
19982 coeff_bits: {entropy_t:>9.2?}"
19983 );
19984 }
19985 }
19986
19987 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
19988 /// plus what is left over once buckets 0/2/3 are subtracted.
19989 ///
19990 /// lane-av1probes: the two search-shaped buckets OVERLAP and the old
19991 /// print denied it. Bucket 0 is not "the motion search": `stage_since(0,
19992 /// ..)` fires only after `find_best_new_mv` and the global-MV search
19993 /// (`encode.rs:11959`, `:12080`), so it is the NEWMV/GLOBAL sub-search
19994 /// alone. Bucket 1 is EVERY `crate::mc::predict` call, from the search's
19995 /// candidates *and* from a committed inter block's final prediction --
19996 /// and that final prediction runs OUTSIDE any bucket-0 region. So bucket 1
19997 /// is neither inside bucket 0 nor smaller than it, and a print that shows
19998 /// it as "motion search (of which interpolation ...)" necessarily shows
19999 /// a sub-number bigger than its parent. Measured: bucket 0 = 17.82 ms,
20000 /// bucket 1 = 148.63 ms.
20001 ///
20002 /// Which number is real: BOTH timers are right; only the old ARITHMETIC
20003 /// was wrong. Bucket 1 is now printed as its own top-level row, the
20004 /// overlap is stated, and the residual is labelled for what it is -- it
20005 /// absorbs the committed block's own interpolation, so it is not a pure
20006 /// "13-mode intra candidate loop" figure either.
20007 ///
20008 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
20009 #[test]
20010 #[ignore = "a perf probe, not a gate"]
20011 fn stage_timing_breakdown_inter() {
20012 let _knobs = crate::speed::knob_read();
20013 let fctx = &crate::decode::FrameCtx::for_encoder();
20014 use std::time::Instant;
20015
20016 let (width, height) = (1280usize, 720);
20017 let picture = test_card(width, height);
20018 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
20019 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
20020 let padded_pic = picture.padded_to(SUPERBLOCK);
20021
20022 stage_reset();
20023 let t = Instant::now();
20024 let inter = encode_inter_frame(
20025 &padded_pic,
20026 &padded_ref,
20027 100,
20028 0.5,
20029 1,
20030 flat_order_hints(1, 0, false),
20031 (width, height),
20032 None,
20033 None,
20034 None,
20035 None,
20036 fctx,
20037 None,
20038 &[],
20039 )
20040 .unwrap();
20041 let total_t = t.elapsed();
20042 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
20043 // Buckets 0 and 2 and 3 are disjoint and additive. Bucket 1 (every
20044 // `mc::predict` call) is NOT added: it overlaps bucket 0 wherever a
20045 // search candidate calls predict, and it also covers the committed
20046 // block's final prediction, which no other bucket times. Adding it
20047 // would double-count the overlap; leaving it out puts the committed
20048 // prediction (and the intra candidate loop, RD glue, and the symbol
20049 // lookups outside `coeff_bits`) into the residual, which is what the
20050 // residual has always been.
20051 let accounted = motion_search + transform_quant + entropy;
20052 let other = total_t.saturating_sub(accounted);
20053 let overlap = interpolation.saturating_sub(motion_search);
20054
20055 eprintln!(
20056 "\n=== inter frame {width}x{height}, one frame ===\n\
20057 total: {total_t:>9.2?} ({} bytes)\n\
20058 NEWMV/GLOBAL sub-search (bucket 0): {motion_search:>9.2?}\n\
20059 transform + quantize (bucket 2): {transform_quant:>9.2?}\n\
20060 coeff_bits, entropy pricing (bucket 3): {entropy:>9.2?}\n\
20061 buckets 0+2+3 accounted: {accounted:>9.2?}\n\
20062 \n\
20063 OVERLAPPING, not additive: every mc::predict call (bucket 1) {interpolation:>9.2?}\n\
20064 \x20 -- of which {overlap:>9.2?} is OUTSIDE bucket 0 (a committed\n\
20065 \x20 inter block's final prediction, which no bucket above times)\n\
20066 \x20 and the rest is the search candidates' interpolation, already\n\
20067 \x20 inside bucket 0. It is deliberately NOT added to the total.\n\
20068 \n\
20069 residual (13-mode intra candidate loop, the committed block's\n\
20070 \x20 interpolation above, NEARESTMV's own predict, RD glue): {other:>9.2?}",
20071 inter.stream.len(),
20072 );
20073 }
20074
20075 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
20076 /// frames (a dark/flat one, a detailed one, a normal film one) at two
20077 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
20078 /// None`, the baseline this same build produces without
20079 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
20080 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
20081 /// go in the lane report, which is where "ship as default" is decided --
20082 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
20083 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
20084 #[test]
20085 // The three clip paths are HARD-CODED ABSOLUTES under /home/user, not
20086 // env-driven: off this workstation every row prints `SKIP <label>: <path>
20087 // not present on this machine` and the run exits 0 with no numbers. It is
20088 // a local-run probe; there is no fleet-host configuration that makes it
20089 // measure anything.
20090 #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
20091 fn prune_k_quality_sweep() {
20092 let _knobs = crate::speed::knob_read();
20093 let fctx = &crate::decode::FrameCtx::for_encoder();
20094 if !have_ffmpeg() {
20095 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
20096 return;
20097 }
20098 let (width, height) = (640usize, 352usize);
20099 let frames: &[(&str, &str, &str)] = &[
20100 // (label, clip, seek) -- a near-black scene, a busy one, and an
20101 // ordinary film frame, each from a different real file.
20102 (
20103 "dark/flat",
20104 "/home/user/Videos/reela.mp4",
20105 "3",
20106 ),
20107 (
20108 "detailed",
20109 "/home/user/Downloads/reelb.mkv",
20110 "1200",
20111 ),
20112 (
20113 "film",
20114 "/home/user/Videos/Films/reelc.mkv",
20115 "600",
20116 ),
20117 ];
20118 for &(label, clip, skip) in frames {
20119 if !std::path::Path::new(clip).exists() {
20120 eprintln!("SKIP {label}: {clip} not present on this machine");
20121 continue;
20122 }
20123 let picture = clip_frame(clip, skip, width, height);
20124 for &q in &[60u8, 150] {
20125 // SAFETY (not literally unsafe, just process-global): this is
20126 // a single-threaded #[ignore] probe, run by hand, never
20127 // alongside other tests that read Search::top_k.
20128 set_test_top_k_override(None);
20129 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
20130 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
20131 eprint!(
20132 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
20133 baseline.stream.len(),
20134 baseline_psnr
20135 );
20136 for &k in &[3usize, 4, 6] {
20137 set_test_top_k_override(Some(k));
20138 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
20139 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
20140 eprint!(
20141 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
20142 pruned.stream.len(),
20143 pruned_psnr,
20144 pruned_psnr - baseline_psnr
20145 );
20146 }
20147 eprintln!();
20148 }
20149 }
20150 set_test_top_k_override(None);
20151 }
20152
20153 /// Two consecutive decoded frames from one clip, for an inter-frame
20154 /// sweep -- [`clip_frame`] alone only ever gives one.
20155 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
20156 let out = Command::new("ffmpeg")
20157 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
20158 .args(["-vf", &format!("scale={width}:{height}")])
20159 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
20160 .output()
20161 .expect("ffmpeg failed to run");
20162 assert!(
20163 out.status.success(),
20164 "ffmpeg: {}",
20165 String::from_utf8_lossy(&out.stderr)
20166 );
20167 let (luma, chroma) = (width * height, width * height / 4);
20168 let frame_len = luma + 2 * chroma;
20169 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
20170 std::array::from_fn(|i| {
20171 let bytes = &out.stdout[i * frame_len..][..frame_len];
20172 Picture {
20173 width,
20174 height,
20175 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
20176 u: bytes[luma..luma + chroma]
20177 .iter()
20178 .map(|&v| u16::from(v))
20179 .collect(),
20180 v: bytes[luma + chroma..]
20181 .iter()
20182 .map(|&v| u16::from(v))
20183 .collect(),
20184 }
20185 })
20186 }
20187
20188 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
20189 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
20190 /// then one inter frame off it (`search_inter_block`'s own intra
20191 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
20192 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
20193 /// padding step complicates the comparison. Prints bytes and luma PSNR
20194 /// for the inter frame alone, unpruned vs each `K`.
20195 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
20196 #[test]
20197 // Same hard-coded /home/user clip paths as `prune_k_quality_sweep`;
20198 // off this workstation it SKIPs all three rows and prints nothing.
20199 #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
20200 fn prune_k_quality_sweep_inter() {
20201 let _knobs = crate::speed::knob_read();
20202 let fctx = &crate::decode::FrameCtx::for_encoder();
20203 if !have_ffmpeg() {
20204 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
20205 return;
20206 }
20207 let (width, height) = (1280usize, 704usize);
20208 let frames: &[(&str, &str, &str)] = &[
20209 (
20210 "dark/flat",
20211 "/home/user/Videos/reela.mp4",
20212 "3",
20213 ),
20214 (
20215 "detailed",
20216 "/home/user/Downloads/reelb.mkv",
20217 "1200",
20218 ),
20219 (
20220 "film",
20221 "/home/user/Videos/Films/reelc.mkv",
20222 "600",
20223 ),
20224 ];
20225 for &(label, clip, skip) in frames {
20226 if !std::path::Path::new(clip).exists() {
20227 eprintln!("SKIP {label}: {clip} not present on this machine");
20228 continue;
20229 }
20230 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
20231 for &q in &[60u8, 150] {
20232 // SAFETY (not literally unsafe, just process-global): a
20233 // single-threaded #[ignore] probe, run by hand, never
20234 // alongside other tests that read Search::top_k.
20235 set_test_top_k_override_inter(None);
20236 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
20237 let baseline = encode_inter_frame(
20238 &inter_source,
20239 &key.reconstruction,
20240 q,
20241 0.5,
20242 1,
20243 flat_order_hints(1, 0, false),
20244 (width, height),
20245 None,
20246 None,
20247 None,
20248 None,
20249 fctx,
20250 None,
20251 &[],
20252 )
20253 .unwrap();
20254 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
20255 eprint!(
20256 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
20257 baseline.stream.len(),
20258 baseline_psnr
20259 );
20260 for &k in &[3usize, 4, 6] {
20261 set_test_top_k_override_inter(Some(k));
20262 let pruned = encode_inter_frame(
20263 &inter_source,
20264 &key.reconstruction,
20265 q,
20266 0.5,
20267 1,
20268 flat_order_hints(1, 0, false),
20269 (width, height),
20270 None,
20271 None,
20272 None,
20273 None,
20274 fctx,
20275 None,
20276 &[],
20277 )
20278 .unwrap();
20279 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
20280 eprint!(
20281 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
20282 pruned.stream.len(),
20283 pruned_psnr,
20284 pruned_psnr - baseline_psnr
20285 );
20286 }
20287 eprintln!();
20288 }
20289 }
20290 set_test_top_k_override_inter(None);
20291 }
20292
20293 /// `frames` consecutive pictures out of a real clip, scaled to a whole
20294 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
20295 /// to an arbitrary count for the fixture regression gate below.
20296 fn clip_frames(
20297 clip: &str,
20298 skip: &str,
20299 width: usize,
20300 height: usize,
20301 frames: usize,
20302 ) -> Vec<Picture> {
20303 clip_frames_vf(
20304 clip,
20305 skip,
20306 &format!("scale={width}:{height}"),
20307 width,
20308 height,
20309 frames,
20310 )
20311 }
20312
20313 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
20314 /// for a native-resolution CROP instead of a downscale (the downscale is
20315 /// what destroys a screen capture's exact repeats -- class
20316 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
20317 fn clip_frames_vf(
20318 clip: &str,
20319 skip: &str,
20320 vf: &str,
20321 width: usize,
20322 height: usize,
20323 frames: usize,
20324 ) -> Vec<Picture> {
20325 // ONE definition of the gate's loader recipe, shared with
20326 // `examples/enc_probe` so the instrument cannot arm a different source
20327 // than the gate it reports on (class `instrument disagrees with the
20328 // gate`; lane-probe).
20329 crate::probe::source(clip, skip, vf, width, height, frames)
20330 }
20331
20332 /// The standing regression gate on real content: 12 frames of a real
20333 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
20334 /// this crate's own input regardless of its own source codec), encoded
20335 /// as an AV1 GOP and checked against three numeric floors so a
20336 /// compatibility or quality regression fails the suite instead of
20337 /// waiting for a downstream repo's gate to catch it (as happened for a
20338 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
20339 /// refusal, both caught only that way).
20340 ///
20341 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
20342 /// that geometry is already covered elsewhere), chosen only so encode
20343 /// time and gate numbers are not muddied by an edge-block class this
20344 /// test is not about.
20345 ///
20346 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
20347 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
20348 /// below carry a margin off those measured numbers (PSNR floor =
20349 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
20350 #[test]
20351 fn real_clip_encodes_within_its_quality_and_size_budget() {
20352 let _knobs = crate::speed::knob_read();
20353 let fctx = &crate::decode::FrameCtx::for_encoder();
20354 if !have_ffmpeg() {
20355 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
20356 return;
20357 }
20358 // lane-av1clipprobe: the clip's absence was a bare `clip.exists()`
20359 // -> SKIP with no env escape, so this gate reported green on a tree
20360 // with no root `fixtures/`. The probe prints that one line (naming the
20361 // resolved path) and fails under the require envs.
20362 let Some(clip) = crate::library_fixture::require(
20363 "video/h264-1080p-23.976-8bit.mp4",
20364 "real_clip_encodes_within_its_quality_and_size_budget",
20365 ) else {
20366 return;
20367 };
20368 let (width, height, frame_count) = (640usize, 384usize, 12usize);
20369 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
20370 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
20371 assert_eq!(encoded.frames.len(), frame_count);
20372
20373 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
20374 // stream and hands back every frame -- a stream a downstream
20375 // decoder refuses is the exact class of regression this gate
20376 // exists for.
20377 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
20378 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
20379
20380 // Gate 2: quality vs the source did not silently collapse.
20381 let mean_psnr: f64 = decoded
20382 .iter()
20383 .zip(&source)
20384 .map(|(d, s)| psnr(&d.y, &s.y))
20385 .sum::<f64>()
20386 / frame_count as f64;
20387 assert!(
20388 mean_psnr >= 44.91,
20389 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
20390 );
20391
20392 // Gate 3: the stream did not silently bloat.
20393 assert!(
20394 encoded.stream.len() <= 80_340,
20395 "stream grew to {} bytes, over the 80340-byte ceiling",
20396 encoded.stream.len()
20397 );
20398 }
20399
20400 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
20401 /// straddle size: 640x384 is exact on both axes (32-aligned), so
20402 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
20403 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
20404 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
20405 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
20406 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
20407 /// card; this one is the real-clip gate, same three floors.
20408 ///
20409 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
20410 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
20411 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
20412 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
20413 #[test]
20414 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
20415 let _knobs = crate::speed::knob_read();
20416 let fctx = &crate::decode::FrameCtx::for_encoder();
20417 if !have_ffmpeg() {
20418 eprintln!(
20419 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
20420 no ffmpeg"
20421 );
20422 return;
20423 }
20424 // lane-av1clipprobe: see the sibling gate above -- the bare
20425 // `clip.exists()` -> SKIP had no env escape.
20426 let Some(clip) = crate::library_fixture::require(
20427 "video/h264-1080p-23.976-8bit.mp4",
20428 "real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size",
20429 ) else {
20430 return;
20431 };
20432 let (width, height, frame_count) = (704usize, 400usize, 8usize);
20433 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
20434 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
20435 assert_eq!(encoded.frames.len(), frame_count);
20436
20437 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
20438 // stream and hands back every frame.
20439 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
20440 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
20441
20442 // Gate 2: quality vs the source did not silently collapse.
20443 let mean_psnr: f64 = decoded
20444 .iter()
20445 .zip(&source)
20446 .map(|(d, s)| psnr(&d.y, &s.y))
20447 .sum::<f64>()
20448 / frame_count as f64;
20449 assert!(
20450 mean_psnr >= 44.98,
20451 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
20452 );
20453
20454 // Gate 3: the stream did not silently bloat.
20455 assert!(
20456 encoded.stream.len() <= 62_703,
20457 "stream grew to {} bytes, over the 62703-byte ceiling",
20458 encoded.stream.len()
20459 );
20460 }
20461
20462 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
20463 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
20464 /// facade -- timed end to end, so the edith export-time projection is a
20465 /// real number rather than a guess from the isolated key/inter numbers
20466 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
20467 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
20468 #[test]
20469 #[ignore = "a perf probe, not a gate"]
20470 fn sequence_bench_sanity() {
20471 let _knobs = crate::speed::knob_read();
20472 let fctx = &crate::decode::FrameCtx::for_encoder();
20473 use std::time::Instant;
20474 let (width, height) = (1280usize, 720usize);
20475 let pictures: Vec<Picture> = (0..24)
20476 .map(|i| panned_test_card(width, height, i * 3))
20477 .collect();
20478 let t = Instant::now();
20479 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
20480 let elapsed = t.elapsed();
20481 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
20482 eprintln!(
20483 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
20484 elapsed / 24
20485 );
20486 }
20487
20488 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
20489 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
20490 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
20491 /// -- --ignored --nocapture`.
20492 #[test]
20493 #[ignore = "a calibration probe, not a gate"]
20494 fn calibration_sweep_base_q_idx() {
20495 let _knobs = crate::speed::knob_read();
20496 let fctx = &crate::decode::FrameCtx::for_encoder();
20497 if !have_ffmpeg() {
20498 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
20499 return;
20500 }
20501 let (width, height, frames) = (640usize, 384usize, 12usize);
20502 for clip in [
20503 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
20504 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
20505 ] {
20506 // lane-av1clipprobe: the crate's one fixture root and its one
20507 // presence probe -- the bare `path.exists()` -> SKIP -> `continue`
20508 // had no env escape, and with every clip absent the sweep looped
20509 // zero times and passed.
20510 let Some(path) = crate::library_fixture::require(
20511 &format!("video/{clip}"),
20512 &format!("calibration_sweep_base_q_idx: {clip}"),
20513 ) else {
20514 continue;
20515 };
20516 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
20517 eprintln!("--- {clip} ---");
20518 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
20519 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
20520 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
20521 let mean_psnr: f64 = decoded
20522 .iter()
20523 .zip(&source)
20524 .map(|(d, s)| psnr(&d.y, &s.y))
20525 .sum::<f64>()
20526 / frames as f64;
20527 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
20528 eprintln!(
20529 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
20530 encoded.stream.len()
20531 );
20532 }
20533 }
20534 }
20535
20536 // -----------------------------------------------------------------------
20537 // The encoder's standing BD-rate baseline against libaom and rav1e.
20538 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
20539 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
20540 // agreeing with our encoder proves nothing about the bitstream.
20541 // -----------------------------------------------------------------------
20542
20543 /// All-plane PSNR of a decoded picture against its source, on the same
20544 /// 8-bit scale [`psnr`] uses.
20545 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
20546 let cat = |p: &Picture| {
20547 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
20548 v.extend_from_slice(&p.y);
20549 v.extend_from_slice(&p.u);
20550 v.extend_from_slice(&p.v);
20551 v
20552 };
20553 psnr(&cat(decoded), &cat(source))
20554 }
20555
20556 /// The pictures back as the planar 8-bit bytes an encoder reads.
20557 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
20558 let mut raw = Vec::new();
20559 for p in source {
20560 for plane in [&p.y, &p.u, &p.v] {
20561 raw.extend(plane.iter().map(|&s| s as u8));
20562 }
20563 }
20564 raw
20565 }
20566
20567 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
20568 /// through ffmpeg: one point per entry of `points`, each a quality flag
20569 /// set. Returns the ladder ordered by fidelity and the total encode wall
20570 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
20571 /// so both curves are measured by the same decoder.
20572 fn external_ladder(
20573 source: &[Picture],
20574 width: usize,
20575 height: usize,
20576 encoder: &str,
20577 points: &[Vec<String>],
20578 ) -> (Vec<(f64, f64)>, f64) {
20579 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
20580 let dir = std::env::temp_dir();
20581 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
20582 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
20583 let mut ladder = Vec::new();
20584 let mut wall = 0.0;
20585 for (i, params) in points.iter().enumerate() {
20586 let obu = dir.join(format!(
20587 "ec-av1-bd-{}-{encoder}-{i}.obu",
20588 std::process::id()
20589 ));
20590 let start = std::time::Instant::now();
20591 let out = Command::new("ffmpeg")
20592 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
20593 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
20594 .arg(&raw_path)
20595 .args(["-an", "-threads", "1"])
20596 .args(["-g", &source.len().to_string(), "-c:v", encoder])
20597 .args(params)
20598 .args(["-f", "obu"])
20599 .arg(&obu)
20600 .output()
20601 .expect("ffmpeg failed to run");
20602 wall += start.elapsed().as_secs_f64();
20603 assert!(
20604 out.status.success(),
20605 "{encoder} {params:?}: {}",
20606 String::from_utf8_lossy(&out.stderr)
20607 );
20608 let stream = std::fs::read(&obu).expect("reference stream");
20609 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
20610 // lane-dkey: every reference point must also decode through OUR
20611 // decoder, sample-exact against ffmpeg's decode of the same bytes.
20612 // A BD table computed off streams we cannot read is a table about
20613 // an encoder we cannot check; this is the assertion that would
20614 // have caught the `force_integer_mv` defect (its stream decoded to
20615 // 25 dB garbage while this gate stayed green) and the crf-5 key
20616 // frame desync. A failure names the encoder, the point's flags and
20617 // the first differing frame/plane/sample.
20618 // lane-dpm1: a failing reference point is COLLECTED, not panicked
20619 // on, so one run still prints the whole BD table and names every
20620 // bad point instead of stopping at the first. The collection is
20621 // asserted empty by [`assert_ladder_decodes`] at the end of each
20622 // gate.
20623 match crate::stream::decode_stream(&stream) {
20624 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
20625 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
20626 ours.len(),
20627 decoded.len(),
20628 )),
20629 Ok(ours) => {
20630 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
20631 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
20632 note_ladder_failure(format!(
20633 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
20634 decoder decoded {got}, ffmpeg {want}"
20635 ));
20636 break;
20637 }
20638 }
20639 }
20640 Err(e) => note_ladder_failure(format!(
20641 "{encoder} {params:?}: our decoder refused the stream ({e})"
20642 )),
20643 }
20644 let mean: f64 = decoded
20645 .iter()
20646 .zip(source)
20647 .map(|(d, s)| psnr_all(d, s))
20648 .sum::<f64>()
20649 / source.len() as f64;
20650 ladder.push((mean, (stream.len() as f64).log10()));
20651 let _ = std::fs::remove_file(&obu);
20652 }
20653 let _ = std::fs::remove_file(&raw_path);
20654 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
20655 (ladder, wall)
20656 }
20657
20658 /// Every reference ladder point that did not decode sample-exactly
20659 /// through our own decoder, collected across a whole gate run so the BD
20660 /// table still prints and EVERY bad point is named
20661 /// (`encoder params frame plane sample`) instead of only the first.
20662 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
20663
20664 fn note_ladder_failure(msg: String) {
20665 eprintln!("LADDER DECODE FAILURE: {msg}");
20666 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
20667 }
20668
20669 /// Fail the gate at its END on everything [`external_ladder`] collected.
20670 fn assert_ladder_decodes() {
20671 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
20672 assert!(
20673 failures.is_empty(),
20674 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
20675 failures.len(),
20676 failures.join("\n"),
20677 );
20678 }
20679
20680 /// First differing sample between two pictures, as
20681 /// `(plane, index, left, right)` -- so a gate failure names the plane and
20682 /// the sample instead of just "differs". A length difference counts as a
20683 /// mismatch of that plane at the first index past the shorter one.
20684 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
20685 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
20686 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
20687 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
20688 }
20689 if l.len() != r.len() {
20690 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
20691 }
20692 }
20693 None
20694 }
20695
20696 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
20697 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
20698 /// stream is decoded twice -- by ffmpeg and by our own
20699 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
20700 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
20701 /// in Y, U and V over every shown frame in display order. That is itself
20702 /// a gate: it proves the bitstream says what the encoder thinks, in the
20703 /// only two decoders that read it.
20704 fn our_ladder(
20705 name: &str,
20706 source: &[Picture],
20707 width: usize,
20708 height: usize,
20709 fctx: &crate::decode::FrameCtx,
20710 ) -> (Vec<(f64, f64)>, f64) {
20711 let mut ladder = Vec::new();
20712 let mut wall = 0.0;
20713 for &q in &[150u8, 120, 90, 60] {
20714 let start = std::time::Instant::now();
20715 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
20716 // the gate has to be able to re-sweep it. 0.5 is the shipped one
20717 // (`crate::encoder::DEADZONE`).
20718 let deadzone = std::env::var("EC_AV1_DEADZONE")
20719 .ok()
20720 .and_then(|v| v.parse().ok())
20721 .unwrap_or(0.5);
20722 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
20723 wall += start.elapsed().as_secs_f64();
20724 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
20725 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
20726 assert_eq!(
20727 ours.len(),
20728 source.len(),
20729 "{name} q={q}: our decoder's display-order frame count"
20730 );
20731 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
20732 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
20733 panic!(
20734 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
20735 {got}, the encoder reconstructed {want}"
20736 );
20737 }
20738 }
20739 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
20740 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
20741 panic!(
20742 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
20743 {got}, the encoder reconstructed {want}"
20744 );
20745 }
20746 }
20747 let per_frame: Vec<f64> = decoded
20748 .iter()
20749 .zip(source)
20750 .map(|(d, s)| psnr_all(d, s))
20751 .collect();
20752 // lane-txrd: does a tool's loss start at the FIRST inter frame
20753 // (a local mispricing) or grow down the GOP (propagation into
20754 // the reference chain)? One line per q point answers it.
20755 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
20756 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
20757 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
20758 // lane-txrd: per PLANE, because an all-plane mean hides a
20759 // collapse in one of them (class `metric blind to a plane`).
20760 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
20761 let v: Vec<String> = decoded
20762 .iter()
20763 .zip(source)
20764 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
20765 .collect();
20766 v.join(" ")
20767 };
20768 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
20769 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
20770 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
20771 }
20772 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
20773 ladder.push((mean, (encoded.stream.len() as f64).log10()));
20774 }
20775 // What this clip asked for and what the content gate left it coding
20776 // under: a screen clip requests a pyramid and codes flat, and that
20777 // difference is what keeps its row identical to the flat baseline
20778 // (class `gate-blind-to-feature`).
20779 eprintln!(
20780 "{name}: sequence, pyramid requested {:?} effective {:?}",
20781 crate::encoder::Pyramid::from_env(),
20782 last_sequence_pyramid(),
20783 );
20784 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
20785 (ladder, wall)
20786 }
20787
20788 /// [`our_ladder`] through the streaming facade — the surface the editor's
20789 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
20790 /// each stream is also reordered (hidden `ALTREF` first,
20791 /// `show_existing_frame` last per group) and each level is coded at its
20792 /// own quantizer offset; without one it is the flat ladder, which
20793 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
20794 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
20795 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
20796 /// the whole ladder how many frames and how many bytes it spent, and the
20797 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
20798 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
20799 /// flat path, so a requested pyramid can come back `None` here.
20800 fn our_ladder_facade(
20801 name: &str,
20802 source: &[Picture],
20803 width: usize,
20804 height: usize,
20805 pyramid: Option<crate::encoder::Pyramid>,
20806 ) -> (
20807 Vec<(f64, f64)>,
20808 f64,
20809 [usize; 4],
20810 [usize; 4],
20811 Option<crate::encoder::Pyramid>,
20812 ) {
20813 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
20814 let slot = |l: Level| match l {
20815 Level::Key => 0,
20816 Level::Arf => 1,
20817 Level::Leaf => 2,
20818 Level::ShowExisting => 3,
20819 };
20820 let mut ladder = Vec::new();
20821 let mut wall = 0.0;
20822 let mut effective = None;
20823 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
20824 for &q in &[150u8, 120, 90, 60] {
20825 let config = EncoderConfig {
20826 width,
20827 height,
20828 base_q_idx: q,
20829 gop: source.len(),
20830 colour: Colour::Unspecified,
20831 tile_cols_log2: 0,
20832 tile_rows_log2: 0,
20833 };
20834 let start = std::time::Instant::now();
20835 let mut enc = match pyramid {
20836 None => Av1Encoder::new(config).unwrap(),
20837 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
20838 };
20839 let mut packets = Vec::new();
20840 for picture in source {
20841 packets.extend(enc.encode_frames(picture).unwrap());
20842 }
20843 packets.extend(enc.flush().unwrap());
20844 wall += start.elapsed().as_secs_f64();
20845 effective = enc.pyramid();
20846 let mut stream = Vec::new();
20847 for p in &packets {
20848 counts[slot(p.level)] += 1;
20849 bytes[slot(p.level)] += p.data.len();
20850 stream.extend_from_slice(&p.data);
20851 }
20852 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
20853 // correct if the DISPLAY-order output still has one frame per
20854 // source picture, in the right order -- checked against our own
20855 // decoder as well as ffmpeg's, both below.
20856 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
20857 assert_eq!(
20858 ours.len(),
20859 source.len(),
20860 "{name} q={q}: our display-order count"
20861 );
20862 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
20863 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
20864 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
20865 panic!(
20866 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
20867 decoded {got}, our decoder decoded {want}"
20868 );
20869 }
20870 }
20871 let mean: f64 = decoded
20872 .iter()
20873 .zip(source)
20874 .map(|(d, s)| psnr_all(d, s))
20875 .sum::<f64>()
20876 / source.len() as f64;
20877 ladder.push((mean, (stream.len() as f64).log10()));
20878 }
20879 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
20880 (ladder, wall, counts, bytes, effective)
20881 }
20882
20883 /// Byte-exactness gate for encoder work that is meant to change only
20884 /// how long the encoder takes.
20885 ///
20886 /// The BD gate above measures quality, which a speed lane can move by a
20887 /// hair without failing anything; this pins the streams themselves.
20888 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
20889 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
20890 /// in the tile) and again on lane-av1mv's merge of it: an extra
20891 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
20892 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
20893 /// prices coefficients against the tables the frame's writer really
20894 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
20895 /// decision change the BD gate judges. Re-pinned again on
20896 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
20897 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
20898 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
20899 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
20900 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
20901 /// by default ([`warp_on`], a sequence/frame header bit and a new
20902 /// motion_mode symbol on eligible blocks) and
20903 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
20904 /// every inter frame's superblocks now code at their own lambda
20905 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
20906 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
20907 /// and the two var-tx depth searches ([`tx32_depth_search`],
20908 /// [`compound_var_tx`]) are on by default, all three re-judged on the
20909 /// native gate's real film rows.
20910 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
20911 /// every block whose chroma takes it codes a different mode symbol, two
20912 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
20913 /// restores the previous streams. Re-pinned again in the same lane once
20914 /// directional luma winners searched their `angle_delta_y`
20915 /// (`EC_AV1_ANGLE=0` restores that half).
20916 #[test]
20917 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
20918 // These are DEFAULT-PRESET pins: a speed preset switches search levers
20919 // off, so it legitimately moves every byte. Encode at speed 0 whatever
20920 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
20921 let _knobs = crate::speed::knob_write();
20922 let was = crate::speed::speed();
20923 crate::speed::set_speed(0);
20924 if !have_ffmpeg() {
20925 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
20926 return;
20927 }
20928 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
20929 // so a tree with no root `fixtures/` reported this gate green having
20930 // compared nothing at all.
20931 let Some(clip) = crate::library_fixture::require(
20932 "video/h264-1080p-23.976-8bit.mp4",
20933 "the_encoders_own_streams_are_byte_identical_to_their_pins",
20934 ) else {
20935 return;
20936 };
20937 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
20938 // FNV-1a over the stream: a witness that every coded bit is where it
20939 // was, which a byte count alone is not.
20940 let fnv = |b: &[u8]| {
20941 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
20942 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
20943 })
20944 };
20945 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
20946 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
20947 // of 4, its leaves at q+8 and a `show_existing_frame` header per
20948 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
20949 // four frames; four pictures is one short mini-GOP, which is the
20950 // shape that pays least (the ARF's own quality has no later group to
20951 // carry it), so this is not the BD gate's number.
20952 // Re-taken again on lane-av1cfl: the chroma search offers
20953 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
20954 // so every block taking either codes different syntax and different
20955 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
20956 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
20957 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
20958 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
20959 // so these four pictures code as one truncated group -- a hidden
20960 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
20961 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
20962 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
20963 // Re-taken on lane-fintra: the sequence header sets
20964 // `enable_filter_intra`, so every DC_PRED intra block of at most
20965 // 32x32 without a luma palette carries a `use_filter_intra` flag and
20966 // the blocks that take one code a filter-intra mode, a different
20967 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
20968 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
20969 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
20970 // (default pyramid `8:-32:16`, one truncated group of 8 with its
20971 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
20972 // root can code a REAL residual now (one TX_64X64 luma transform and
20973 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
20974 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
20975 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
20976 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
20977 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
20978 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
20979 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
20980 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
20981 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
20982 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
20983 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
20984 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
20985 // these four pictures -- offers every superblock a 64x64 intra root
20986 // now. `EC_AV1_I64=0` restores 8557 / 33345.
20987 // Re-taken on lane-pricer: the inter RD search prices a single
20988 // reference through the tree and the neighbour contexts the writer
20989 // really codes it with, so every inter picture's reference decisions
20990 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
20991 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
20992 // for `skip`/`is_inter` and for the whole compound reference tree, so
20993 // every inter block's cost -- and with it the skip and reference
20994 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
20995 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
20996 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
20997 // single and compound are priced against the same syntax -- 8311 ->
20998 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
20999 // Re-taken on lane-newmv: the motion search charges its own rate term
21000 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
21001 // and each subpel stage re-runs from its own winner
21002 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
21003 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
21004 // and 33014 -> 33090 at q=60.
21005 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
21006 // from libaom's objective tpl mapping, so every inter picture's
21007 // quantizer grid -- and every decision priced against it -- moved
21008 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
21009 // at the merge of both lanes.
21010 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
21011 // per-superblock `delta_qindex` at 1.5x the preset's strength
21012 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
21013 // grids -- and every decision priced against them -- moved:
21014 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
21015 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
21016 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
21017 // pixels -- and the leaves that predict from them -- moved:
21018 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
21019 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
21020 // the shipped stream did not move.
21021 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
21022 // picture is coded in 128x128 superblocks now, the inter ones
21023 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
21024 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
21025 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
21026 // by default, on top of the ARF temporal filter).
21027 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
21028 // candidates the 64 root already did ([`b128_compound`]), so every
21029 // inter frame that carries `reference_select` codes different blocks
21030 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
21031 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
21032 // Re-taken on lane-arftf: that filter's strength swept on the deciding
21033 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
21034 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
21035 // 33017 at q=60 (the same LENGTH, different bytes).
21036 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
21037 // lane-rlclamp onto the 128 compound default.
21038 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
21039 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
21040 // so every inter frame whose RD takes one codes a different partition
21041 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
21042 // quantizer the rect cut never wins its own comparison on this clip.
21043 // `EC_AV1_B128HV=0` restores 8290 exactly.
21044 let pins: [(u8, usize, u64); 2] = [
21045 (150, 8291, 0x1f00bb0eb099a27f),
21046 (60, 33227, 0x57ee6b1f8eacd881),
21047 ];
21048 let coded: Vec<(u8, usize, u64)> = pins
21049 .iter()
21050 .map(|&(q, _, _)| {
21051 let e = encode_sequence(&source, q, 0.5).unwrap();
21052 (q, e.stream.len(), fnv(&e.stream))
21053 })
21054 .collect();
21055 crate::speed::set_speed(was);
21056 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
21057 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
21058 }
21059 }
21060
21061 /// A ladder is only a ladder if both axes rise together.
21062 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
21063 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
21064 for w in ladder.windows(2) {
21065 assert!(
21066 w[1].0 > w[0].0 && w[1].1 > w[0].1,
21067 "{name}: not monotone, {ladder:?}"
21068 );
21069 }
21070 }
21071
21072 /// The sweep behind [`screen_content`]'s constants
21073 /// (`unswept-decision-constants`), on the SAME five clips
21074 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
21075 /// same native crop: for each colour bound N the share of 16x16 luma
21076 /// blocks with 2..=N distinct colours, and the share of those whose
21077 /// per-pixel variance also clears a floor V -- libaom's
21078 /// `av1_set_screen_content_options` counts the variance-cleared blocks
21079 /// too (its `counts_2`, which gates intrabc), and without that term a
21080 /// smooth dark film frame reads as screen content.
21081 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
21082 #[test]
21083 #[ignore = "reads the real library"]
21084 fn probe_screen_detect() {
21085 let _knobs = crate::speed::knob_read();
21086 if !have_ffmpeg() {
21087 eprintln!("SKIP probe_screen_detect: no ffmpeg");
21088 return;
21089 }
21090 let limits = [4usize, 8, 16, 32, 64, 128];
21091 let floors = [0u64, 4, 16, 64, 256];
21092 // The census of one clip at one size: mean share, over the frames, of
21093 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
21094 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
21095 let mut acc = [[0f64; 5]; 6];
21096 for picture in frames {
21097 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
21098 let mut hit = [[0usize; 5]; 6];
21099 let mut blocks = 0usize;
21100 for by in (0..ch).step_by(16) {
21101 for bx in (0..cw).step_by(16) {
21102 let mut seen = [false; 256];
21103 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
21104 for row in 0..16 {
21105 for col in 0..16 {
21106 let v = y[(by + row) * cw + bx + col];
21107 sum += u64::from(v);
21108 sq += u64::from(v) * u64::from(v);
21109 if !seen[usize::from(v)] {
21110 seen[usize::from(v)] = true;
21111 colors += 1;
21112 }
21113 }
21114 }
21115 let var = (sq - sum * sum / 256) / 256;
21116 blocks += 1;
21117 for (li, &limit) in limits.iter().enumerate() {
21118 if colors > 1 && colors <= limit {
21119 for (fi, &floor) in floors.iter().enumerate() {
21120 hit[li][fi] += usize::from(var > floor);
21121 }
21122 }
21123 }
21124 }
21125 }
21126 for li in 0..6 {
21127 for fi in 0..5 {
21128 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
21129 }
21130 }
21131 }
21132 let n = frames.len().max(1) as f64;
21133 eprintln!(
21134 "{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:",
21135 frames.len()
21136 );
21137 eprintln!(
21138 " N \\ V |{}",
21139 floors.iter().map(|f| format!("{f:>8}")).collect::<String>()
21140 );
21141 for (li, &limit) in limits.iter().enumerate() {
21142 eprintln!(
21143 " {limit:>5} |{}",
21144 (0..5)
21145 .map(|fi| format!("{:>7.1}%", acc[li][fi] / n))
21146 .collect::<String>()
21147 );
21148 }
21149 };
21150 for (name, path, seek) in native_gate_clips() {
21151 let Some((nw, nh)) = probe_dims(&path) else {
21152 eprintln!("SKIP {name}: ffprobe gave no size");
21153 continue;
21154 };
21155 let cw = nw.min(1920) / 128 * 128;
21156 let ch = nh.min(1024) / 128 * 128;
21157 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21158 let frames = clip_frames_vf(
21159 &path,
21160 &seek,
21161 &format!("crop={cw}:{ch}:{x}:{y0}"),
21162 cw,
21163 ch,
21164 12,
21165 );
21166 census(&name, &frames, cw, ch);
21167 // The 640x384 gate scales instead of cropping, and the scaling
21168 // changes the census (bars smooth out): the constants have to
21169 // separate at BOTH sizes.
21170 let small = clip_frames(&path, &seek, 640, 384, 12);
21171 census(&name, &small, 640, 384);
21172 }
21173 }
21174
21175 /// The detector against the WHOLE real library (class
21176 /// `unswept-decision-constants`, user rule "his data is the gate"):
21177 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
21178 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
21179 /// duration, four frames each, 8-bit 4:2:0, at native size or a
21180 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
21181 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
21182 /// Prints per file and offset the share of qualifying 16x16 blocks, the
21183 /// [`screen_content`] verdict and a content hint (mean luma, luma
21184 /// standard deviation, inter MAD), then sweeps the colour bound against
21185 /// the variance floor over the whole library: for each (N, V) the worst
21186 /// (highest) share among the camera/film rows against the best (lowest)
21187 /// among the screen-recording rows, so the rule with the widest gap can
21188 /// be read off. Rows carry the manifest index, codec and size only --
21189 /// no titles, no home paths.
21190 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
21191 #[test]
21192 #[ignore = "reads the real library"]
21193 fn probe_screen_library() {
21194 let _knobs = crate::speed::knob_read();
21195 if !have_ffmpeg() {
21196 eprintln!("SKIP probe_screen_library: no ffmpeg");
21197 return;
21198 }
21199 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
21200 let fixtures = crate::library_fixture::root();
21201 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
21202 else {
21203 eprintln!("SKIP probe_screen_library: no real-library manifest");
21204 return;
21205 };
21206 let limits = [4usize, 8, 16, 32, 64];
21207 let floors = [0u64, 4, 8, 16, 32, 64, 128];
21208 // Whatever ffmpeg gave us, without the exact-count assertion the
21209 // gate loaders make: a seek near the end of a clip returns fewer
21210 // frames, and that is a row to print, not a panic.
21211 let decode =
21212 |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
21213 let out = Command::new("ffmpeg")
21214 .args(["-v", "error", "-ss", seek, "-i", clip])
21215 .args(["-frames:v", &n.to_string()])
21216 .args(["-vf", vf])
21217 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
21218 .output();
21219 let Ok(out) = out else { return Vec::new() };
21220 if !out.status.success() {
21221 return Vec::new();
21222 }
21223 let (luma, chroma) = (w * h, w * h / 4);
21224 let frame_len = luma + 2 * chroma;
21225 (0..out.stdout.len() / frame_len)
21226 .map(|i| {
21227 let b = &out.stdout[i * frame_len..][..frame_len];
21228 Picture {
21229 width: w,
21230 height: h,
21231 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
21232 u: b[luma..luma + chroma]
21233 .iter()
21234 .map(|&v| u16::from(v))
21235 .collect(),
21236 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
21237 }
21238 })
21239 .collect()
21240 };
21241 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
21242 // variance > V, for every (N, V) of the sweep grid, over one frame.
21243 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
21244 let mut hit = [[0usize; 7]; 5];
21245 let mut blocks = 0usize;
21246 for by in (0..h).step_by(16) {
21247 for bx in (0..w).step_by(16) {
21248 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
21249 let mut seen = [false; 256];
21250 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
21251 for row in 0..bh {
21252 for col in 0..bw {
21253 let v = y[(by + row) * w + bx + col];
21254 sum += u64::from(v);
21255 sq += u64::from(v) * u64::from(v);
21256 if !seen[usize::from(v)] {
21257 seen[usize::from(v)] = true;
21258 colors += 1;
21259 }
21260 }
21261 }
21262 let n = (bh * bw) as u64;
21263 let var = (sq - sum * sum / n) / n;
21264 blocks += 1;
21265 for (li, &limit) in limits.iter().enumerate() {
21266 if colors > 1 && colors <= limit {
21267 for (fi, &floor) in floors.iter().enumerate() {
21268 hit[li][fi] += usize::from(var > floor);
21269 }
21270 }
21271 }
21272 }
21273 }
21274 let mut out = [[0f64; 7]; 5];
21275 for li in 0..5 {
21276 for fi in 0..7 {
21277 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
21278 }
21279 }
21280 out
21281 };
21282 // (index, label, path, duration, screen-by-its-own-content). The
21283 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
21284 // are desktop recordings; everything else in this library is camera
21285 // or film material.
21286 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
21287 for (label, file) in [
21288 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
21289 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
21290 ] {
21291 let path = fixtures.join("video").join(file);
21292 if path.exists() {
21293 rows.push((
21294 "fx".into(),
21295 label.into(),
21296 path.to_str().unwrap().into(),
21297 10.0,
21298 false,
21299 ));
21300 }
21301 }
21302 for (i, line) in manifest.lines().skip(1).enumerate() {
21303 let f: Vec<&str> = line.split('\t').collect();
21304 if f.len() < 10 {
21305 continue;
21306 }
21307 let (path, codec) = (f[0], f[2]);
21308 if codec == "-" || codec.is_empty() {
21309 continue;
21310 }
21311 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
21312 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
21313 continue;
21314 };
21315 if !std::path::Path::new(path).exists() {
21316 eprintln!("SKIP {}: file is gone", i + 1);
21317 continue;
21318 }
21319 let name = path.rsplit('/').next().unwrap_or(path);
21320 let is_capture = path.contains("/OBS/")
21321 || (name.len() > 19
21322 && name.as_bytes()[4] == b'-'
21323 && name.as_bytes()[7] == b'-'
21324 && name.as_bytes()[10] == b' '
21325 && name.as_bytes()[13] == b'-');
21326 rows.push((
21327 format!("{}", i + 1),
21328 format!("{codec} {w}x{h}"),
21329 path.to_string(),
21330 f[8].parse::<f64>().unwrap_or(0.0),
21331 is_capture,
21332 ));
21333 }
21334 // Per (N, V): the worst camera/film row and the best screen row, so
21335 // the separation of the whole library is one subtraction.
21336 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
21337 eprintln!(
21338 "| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |"
21339 );
21340 for (idx, label, path, dur, is_capture) in &rows {
21341 let Some((nw, nh)) = probe_dims(path) else {
21342 eprintln!("SKIP {idx}: ffprobe gave no size");
21343 continue;
21344 };
21345 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
21346 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21347 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
21348 let mut file_grid = [[0f64; 7]; 5];
21349 let mut file_frames = 0usize;
21350 for pct in [10u32, 50, 90] {
21351 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
21352 let frames = decode(path, &seek, &vf, cw, ch, 4);
21353 if frames.is_empty() {
21354 eprintln!(
21355 "| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |",
21356 if *is_capture { "screen" } else { "camera" }
21357 );
21358 continue;
21359 }
21360 let (mut share, mut yes, mut mean, mut sd, mut mad) =
21361 (0f64, 0usize, 0f64, 0f64, 0f64);
21362 let mut prev: Option<Vec<u8>> = None;
21363 for picture in &frames {
21364 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
21365 let grid = census(&y, cw, ch);
21366 for li in 0..5 {
21367 for fi in 0..7 {
21368 file_grid[li][fi] += grid[li][fi];
21369 }
21370 }
21371 file_frames += 1;
21372 // The shipped rule is (16 colours, var > 16): grid row 2,
21373 // floor 16 is column 3.
21374 share += grid[2][3];
21375 yes += usize::from(screen_content(&y, cw, cw, ch));
21376 let n = y.len() as f64;
21377 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
21378 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
21379 mean += sum / n;
21380 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
21381 if let Some(p) = &prev {
21382 mad += p
21383 .iter()
21384 .zip(&y)
21385 .map(|(&a, &b)| f64::from(a.abs_diff(b)))
21386 .sum::<f64>()
21387 / n;
21388 }
21389 prev = Some(y);
21390 }
21391 let f = frames.len() as f64;
21392 eprintln!(
21393 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
21394 if *is_capture { "screen" } else { "camera" },
21395 share / f,
21396 if yes * 2 > frames.len() {
21397 "SCREEN"
21398 } else {
21399 "camera"
21400 },
21401 frames.len(),
21402 mean / f,
21403 sd / f,
21404 mad / (f - 1.0).max(1.0),
21405 );
21406 }
21407 if file_frames == 0 {
21408 continue;
21409 }
21410 for li in 0..5 {
21411 for fi in 0..7 {
21412 let s = file_grid[li][fi] / file_frames as f64;
21413 match is_capture {
21414 true => scr_min[li][fi] = scr_min[li][fi].min(s),
21415 false => cam_max[li][fi] = cam_max[li][fi].max(s),
21416 }
21417 }
21418 }
21419 }
21420 eprintln!(
21421 "sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):"
21422 );
21423 eprintln!(
21424 " N \\ V |{}",
21425 floors
21426 .iter()
21427 .map(|f| format!("{:>18}", format!("V>{f}")))
21428 .collect::<String>()
21429 );
21430 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
21431 for (li, &limit) in limits.iter().enumerate() {
21432 let mut row = String::new();
21433 for fi in 0..7 {
21434 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
21435 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
21436 if s - c > best {
21437 best = s - c;
21438 best_rule = (limit, floors[fi]);
21439 }
21440 }
21441 eprintln!(" {limit:>5} |{row}");
21442 }
21443 // The threshold sits at the midpoint of the widest gap; the shipped
21444 // constant is its reciprocal in whole parts of the frame.
21445 let (li, fi) = (
21446 limits.iter().position(|&l| l == best_rule.0).unwrap(),
21447 floors.iter().position(|&f| f == best_rule.1).unwrap(),
21448 );
21449 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
21450 eprintln!(
21451 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
21452 best_rule.0,
21453 best_rule.1,
21454 best,
21455 cam_max[li][fi],
21456 scr_min[li][fi],
21457 mid,
21458 (100.0 / mid.max(0.1)).round() as usize,
21459 );
21460 }
21461
21462 /// The missing instrument: what this encoder costs against libaom and
21463 /// rav1e at matched fidelity, and how long it takes to get there.
21464 ///
21465 /// Recipe, identical on all three sides: 12 consecutive frames of each
21466 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
21467 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
21468 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
21469 /// it by default), 4:2:0 8-bit in and out. Reference points:
21470 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
21471 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
21472 /// tile_cols=1:tile_rows=1:threads=1`
21473 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
21474 /// ffmpeg-decoded frames of each encoder's own stream.
21475 ///
21476 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
21477 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
21478 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
21479 /// four encodes of that ladder together):
21480 ///
21481 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
21482 /// |---|---|---|---|---|
21483 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
21484 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
21485 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
21486 ///
21487 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
21488 /// the encoder takes -- every stream it writes is byte-identical, so the
21489 /// BD columns are this box's own re-run of the same recipe rather than a
21490 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
21491 /// rav1e). What moved is the wall of the four encodes:
21492 ///
21493 /// | clip | wall ours before | after | instructions:u before -> after |
21494 /// |---|---|---|---|
21495 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
21496 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
21497 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
21498 ///
21499 /// Three exact steps, none of which touches a coded bit: the coefficient
21500 /// rate pricer stopped rebuilding every CDF table per candidate
21501 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
21502 /// tile once per candidate (`decode::FilterReplay`), and the forward
21503 /// transform stopped transforming the all-zero residual that 70% of its
21504 /// calls carry.
21505 ///
21506 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
21507 ///
21508 /// | step | 1080p | 2160p | screen |
21509 /// |---|---|---|---|
21510 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
21511 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
21512 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
21513 ///
21514 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
21515 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
21516 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
21517 /// -- all three decided on the REAL film rows of
21518 /// [`bd_rate_screen_native`], which this downscaled recipe does not
21519 /// carry:
21520 ///
21521 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
21522 /// |---|---|---|---|
21523 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
21524 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
21525 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
21526 ///
21527 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
21528 /// DEFAULT of the sequence path this gate codes through -- the bars are
21529 /// non-screen so they take it, the capture is gated flat:
21530 ///
21531 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
21532 /// |---|---|---|---|---|
21533 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
21534 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
21535 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
21536 ///
21537 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
21538 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
21539 /// facade arm -- which is what "one mini-GOP driver, two entry points"
21540 /// means here. This downscaled recipe HATES the pyramid (as it hates
21541 /// every knob the real film rows of `bd_rate_screen_native` keep, which
21542 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
21543 /// above. The capture's row is the flat row to the byte in both runs --
21544 /// that equality IS the content gate.
21545 ///
21546 /// Loop restoration is NOT in yet: it is the one filter whose parameters
21547 /// are per restoration UNIT inside the tile payload, so it needs both
21548 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
21549 /// buffer to solve against -- neither of which this frame-header-level
21550 /// search reaches.
21551 ///
21552 /// The baseline it replaced, before an inter frame's blocks chose their
21553 /// own partition, was +501.4/+504.4/+440.9 against libaom and
21554 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
21555 ///
21556 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
21557 /// fidelity, while spending far more time than either (the partition
21558 /// search's own cost, uncut: see the two intra-pruning variants measured
21559 /// and rejected in the lane report). No
21560 /// threshold is asserted yet -- this run sets the baseline; the gate
21561 /// asserts four monotone points per ladder, and at EVERY ladder point of
21562 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
21563 /// `crate::stream::decode_stream` -- and asserts the encoder's
21564 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
21565 /// and V over every shown frame in display order. A failure names the
21566 /// clip, the q, the frame, the plane and the first differing sample.
21567 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
21568 /// which exposes no per-packet reconstruction, so that path asserts the
21569 /// two decoders against each other on all three planes.)
21570 ///
21571 /// Run:
21572 /// cargo test -p ec-av1 --release --lib -- --ignored \
21573 /// bd_rate_vs_libaom_and_rav1e --nocapture
21574 #[test]
21575 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
21576 fn bd_rate_vs_libaom_and_rav1e() {
21577 let _knobs = crate::speed::knob_write();
21578 if !have_ffmpeg() {
21579 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
21580 return;
21581 }
21582 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
21583 let fixtures = crate::library_fixture::root();
21584 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
21585 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
21586 // rows for real content (the real rows live in the native gate).
21587 for (label, name) in [
21588 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
21589 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
21590 ] {
21591 // lane-av1clipprobe: the one probe, so a missing clip is RED under
21592 // the require envs instead of a drop-with-no-escape.
21593 if let Some(path) = crate::library_fixture::require(
21594 &format!("video/{name}"),
21595 &format!("bd_rate_vs_libaom_and_rav1e: {label}"),
21596 ) {
21597 clips.push((label.to_string(), path));
21598 }
21599 }
21600 // Screen capture: the repo carries no screen-capture fixture, so take
21601 // the first OBS recording the real-library manifest names.
21602 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
21603 Ok(manifest) => {
21604 let screen = manifest
21605 .lines()
21606 .skip(1)
21607 .filter_map(|l| l.split('\t').next())
21608 .find(|p| {
21609 p.contains("/OBS/")
21610 && p.ends_with(".mkv")
21611 && std::path::Path::new(p).exists()
21612 });
21613 match screen {
21614 Some(p) => clips.push((
21615 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
21616 std::path::PathBuf::from(p),
21617 )),
21618 None => {
21619 eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
21620 }
21621 }
21622 }
21623 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
21624 }
21625 assert!(!clips.is_empty(), "no source clip available");
21626
21627 let (width, height, frames) = (640usize, 384usize, 12usize);
21628 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
21629 .iter()
21630 .map(|q| {
21631 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
21632 .map(String::from)
21633 .to_vec()
21634 })
21635 .collect();
21636 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
21637 .iter()
21638 .map(|q| {
21639 vec![
21640 "-rav1e-params".to_string(),
21641 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
21642 ]
21643 })
21644 .collect();
21645 println!(
21646 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
21647 );
21648 println!(
21649 "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"
21650 );
21651 println!("|---|---|---|---|---|");
21652 for (name, path) in &clips {
21653 let fctx = &crate::decode::FrameCtx::for_encoder();
21654 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
21655 let _ = take_partition_hits();
21656 let _ = crate::tile::take_palette_hits();
21657 SCREEN_FRAMES.iter().for_each(|c| {
21658 c.store(0, std::sync::atomic::Ordering::Relaxed);
21659 });
21660 let _ = take_uv_mode_hits();
21661 let _ = crate::tile::take_inter_mode_hits();
21662 let _ = crate::tile::take_drl_hits();
21663 let _ = crate::tile::take_ref_hits();
21664 let _ = crate::tile::take_compound_mode_hits();
21665 let _ = crate::tile::take_compound_pair_hits();
21666 let _ = crate::tile::take_compound_size_hits();
21667 let _ = crate::tile::take_compound_leaf_mode_hits();
21668 let _ = take_b64_root_hits();
21669 let _ = take_b64_residual_hits();
21670 let _ = take_b64_compound_hits();
21671 let _ = crate::motion::take_census();
21672 // The entry-surface arm: run the SAME ladder through the
21673 // streaming facade the editor's export calls, which must print
21674 // the same BD numbers as the sequence path -- byte for byte the
21675 // same stream now that both drive one mini-GOP driver
21676 // (lane-av1pyrdef).
21677 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
21678 let (ours, ours_wall) = match facade {
21679 false => our_ladder(name, &source, width, height, fctx),
21680 true => {
21681 let pyramid = crate::encoder::Pyramid::from_env();
21682 let (ladder, wall, counts, bytes, effective) =
21683 our_ladder_facade(name, &source, width, height, pyramid);
21684 eprintln!(
21685 "{name}: facade, pyramid requested {pyramid:?} effective \
21686 {effective:?} -- frames key {} arf {} leaf {} \
21687 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
21688 counts[0],
21689 counts[1],
21690 counts[2],
21691 counts[3],
21692 bytes[0],
21693 bytes[1],
21694 bytes[2],
21695 bytes[3],
21696 );
21697 (ladder, wall)
21698 }
21699 };
21700 // How often the inter split actually fired over this clip's four
21701 // encodes, against the whole 32x32 that was the only outcome
21702 // before (gate-blind-to-feature).
21703 let [whole32, split32, whole16, split16] = take_partition_hits();
21704 // Which inter modes actually fired over this clip's four encodes,
21705 // and at which DRL index -- a mode nobody picks is a mode the BD
21706 // number cannot be crediting (gate-blind-to-feature).
21707 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
21708 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
21709 let refs = crate::tile::take_ref_hits();
21710 let modes_total = (nearest + near + global + new).max(1);
21711 eprintln!(
21712 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
21713 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
21714 {drl0}/{drl1}/{drl2}/{drl3}",
21715 100.0 * nearest as f64 / modes_total as f64,
21716 100.0 * near as f64 / modes_total as f64,
21717 100.0 * global as f64 / modes_total as f64,
21718 100.0 * new as f64 / modes_total as f64,
21719 );
21720 // The compound census: what share of the coded inter blocks took
21721 // a compound reference at all, which compound mode they took, and
21722 // which pair (gate-blind-to-feature -- a compound mode nobody
21723 // picks cannot be what a BD number credits).
21724 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
21725 // superblocks were left whole at all, and how many of those coded
21726 // a residual or took a compound reference.
21727 let (roots, root_res, root_comp) = (
21728 take_b64_root_hits(),
21729 take_b64_residual_hits(),
21730 take_b64_compound_hits(),
21731 );
21732 eprintln!(
21733 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
21734 );
21735 let comp_modes = crate::tile::take_compound_mode_hits();
21736 let comp_pairs = crate::tile::take_compound_pair_hits();
21737 let comp_sizes = crate::tile::take_compound_size_hits();
21738 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
21739 let comp_total: usize = comp_modes.iter().sum();
21740 eprintln!(
21741 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
21742 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
21743 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
21744 modes_total + comp_total,
21745 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
21746 comp_modes[0],
21747 comp_modes[1],
21748 comp_modes[2],
21749 comp_modes[3],
21750 comp_modes[6],
21751 comp_modes[7],
21752 comp_pairs[3],
21753 comp_pairs[6],
21754 );
21755 eprintln!(
21756 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
21757 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
21758 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6], comp_leaf[7],
21759 );
21760 eprintln!(
21761 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
21762 comp_sizes[1], comp_sizes[2], comp_sizes[3],
21763 );
21764 // Where the wall-owning stage actually goes: how many candidate
21765 // evaluations (one `mc::predict` + SAD each) a search spends, how
21766 // many of them are subpel, and how often the winner is the seed
21767 // it started from -- the census the seeded search is judged by.
21768 let [
21769 calls,
21770 evals,
21771 subpel,
21772 rounds,
21773 near_pred,
21774 unmoved,
21775 widest,
21776 widest_moves,
21777 ] = crate::motion::take_census();
21778 let per = |n: u64| n as f64 / calls.max(1) as f64;
21779 eprintln!(
21780 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
21781 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
21782 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
21783 per(evals),
21784 100.0 * subpel as f64 / evals.max(1) as f64,
21785 per(rounds),
21786 100.0 * near_pred as f64 / calls.max(1) as f64,
21787 100.0 * unmoved as f64 / calls.max(1) as f64,
21788 );
21789 // lane-newmv, class `instrument at bound`: how often the winner
21790 // was walked to at the log stage's own WIDEST step -- a high
21791 // share means the search stops where its step lets it, not where
21792 // the content is.
21793 eprintln!(
21794 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
21795 100.0 * widest as f64 / calls.max(1) as f64,
21796 per(widest_moves),
21797 );
21798 eprintln!(
21799 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
21800 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
21801 );
21802 eprintln!(
21803 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
21804 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
21805 whole32 + split32,
21806 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
21807 whole16 + split16,
21808 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
21809 );
21810 // The deblocking level each of this clip's frames chose
21811 // (lane-av1filt): 0 everywhere would mean the filter never fires.
21812 let levels = crate::filter_search::take_chosen_levels();
21813 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
21814 let mean = |f: fn(&Chosen) -> u8| {
21815 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
21816 };
21817 eprintln!(
21818 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
21819 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
21820 levels.len(),
21821 mean(|l| l.0.0),
21822 mean(|l| l.0.1),
21823 mean(|l| l.1.0),
21824 mean(|l| l.1.1),
21825 mean(|l| l.2.0),
21826 mean(|l| l.2.1),
21827 );
21828 // How many strength presets each frame's CDEF list carried and
21829 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
21830 // everywhere would mean the per-unit choice never fires.
21831 let presets = crate::filter_search::take_cdef_presets();
21832 let mut by_bits = [0usize; 4];
21833 for (b, _) in &presets {
21834 by_bits[usize::from(*b)] += 1;
21835 }
21836 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
21837 let on_extra: usize = presets.iter().flat_map(|(_, c)| c.iter().skip(1)).sum();
21838 eprintln!(
21839 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
21840 on a non-default preset ({:.1}%)",
21841 by_bits[0],
21842 by_bits[1],
21843 by_bits[2],
21844 by_bits[3],
21845 on_extra,
21846 units,
21847 100.0 * on_extra as f64 / units.max(1) as f64
21848 );
21849 // How the 64x64 luma restoration units split between
21850 // RESTORE_NONE and Wiener (lane-av1lr).
21851 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
21852 eprintln!(
21853 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
21854 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
21855 );
21856 // Which chroma modes the search actually wins with, against the
21857 // unconditional DC_PRED that was the only outcome before
21858 // (gate-blind-to-feature).
21859 // Screen-content detection and the palette it turns on
21860 // (gate-blind-to-feature): how many frames set
21861 // `allow_screen_content_tools`, how many blocks took a palette,
21862 // and of what size. A film clip must print `screen frames on=0`.
21863 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
21864 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
21865 // Which tables the SEARCH priced against, per frame arming
21866 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
21867 // real starting ones. A film clip must show every inter arming on
21868 // the real side, a screen clip none of them.
21869 let (price_default, price_real) = crate::tile::take_pricing_hits();
21870 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
21871 let palette = crate::tile::take_palette_hits();
21872 eprintln!(
21873 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
21874 palette[0],
21875 (2..=8)
21876 .filter(|&n| palette[n] > 0)
21877 .map(|n| format!("{n}={}", palette[n]))
21878 .collect::<Vec<_>>()
21879 .join(" ")
21880 );
21881 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
21882 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
21883 // only ever fires at one magnitude is a search that never left
21884 // its first candidate (gate-blind-to-feature).
21885 // The luma angle-delta histogram (lane-av1cfl): how many
21886 // directional blocks won at each delta. All-zero would mean the
21887 // refinement never beat the base angle.
21888 let deltas = take_angle_delta_hits();
21889 if deltas.iter().sum::<usize>() > 0 {
21890 eprintln!(
21891 "{name}: angle_delta_y {}",
21892 deltas
21893 .iter()
21894 .enumerate()
21895 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
21896 .collect::<Vec<_>>()
21897 .join(" ")
21898 );
21899 }
21900 let alphas = take_cfl_alpha_hits();
21901 if alphas.iter().sum::<usize>() > 0 {
21902 eprintln!(
21903 "{name}: cfl |alpha| {}",
21904 alphas
21905 .iter()
21906 .enumerate()
21907 .filter(|&(_, &n)| n > 0)
21908 .map(|(a, &n)| format!("{a}={n}"))
21909 .collect::<Vec<_>>()
21910 .join(" ")
21911 );
21912 }
21913 let palette_uv = crate::tile::take_palette_uv_hits();
21914 eprintln!(
21915 "{name}: chroma palette blocks {} sizes {}",
21916 palette_uv[0],
21917 (2..=8)
21918 .filter(|&n| palette_uv[n] > 0)
21919 .map(|n| format!("{n}={}", palette_uv[n]))
21920 .collect::<Vec<_>>()
21921 .join(" ")
21922 );
21923 let uv = take_uv_mode_hits();
21924 let uv_total: usize = uv.iter().sum();
21925 eprintln!(
21926 "{name}: uv modes {}",
21927 uv.iter()
21928 .enumerate()
21929 .filter(|&(_, &n)| n > 0)
21930 .map(|(m, &n)| format!(
21931 "{}={n} ({:.1}%)",
21932 UV_MODE_NAMES[m],
21933 100.0 * n as f64 / uv_total.max(1) as f64
21934 ))
21935 .collect::<Vec<_>>()
21936 .join(" ")
21937 );
21938 // Which transform depth the intra blocks of this clip's key
21939 // frames resolved to (lane-av1tx): depth 0 is one transform over
21940 // the whole block, 1 and 2 its halvings.
21941 let depths = take_tx_depth_hits();
21942 let depth_total: usize = depths.iter().sum();
21943 eprintln!(
21944 "{name}: intra tx depths {}",
21945 depths
21946 .iter()
21947 .enumerate()
21948 .map(|(d, &n)| format!(
21949 "{d}={n} ({:.1}%)",
21950 100.0 * n as f64 / depth_total.max(1) as f64
21951 ))
21952 .collect::<Vec<_>>()
21953 .join(" ")
21954 );
21955 print_inter_tx_census(name);
21956 // lane-av1obmc: how many blocks actually CODED a motion_mode
21957 // symbol and which value they took, by footprint -- "OBMC is on"
21958 // as a measurement rather than a claim (class
21959 // `gate-blind-to-feature`).
21960 let mm = crate::tile::take_motion_mode_hits();
21961 eprintln!(
21962 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
21963 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
21964 eligible)",
21965 mm[0],
21966 mm[1],
21967 mm[2],
21968 mm[3],
21969 mm[4],
21970 mm[5],
21971 mm[6],
21972 mm[7],
21973 mm[8],
21974 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
21975 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
21976 mm.iter().sum::<usize>(),
21977 );
21978 let (aom, aom_wall) =
21979 external_ladder(&source, width, height, "libaom-av1", &aom_points);
21980 let (rav1e, rav1e_wall) =
21981 external_ladder(&source, width, height, "librav1e", &rav1e_points);
21982 assert_monotone(&format!("{name}: ours"), &ours);
21983 assert_monotone(&format!("{name}: libaom"), &aom);
21984 assert_monotone(&format!("{name}: rav1e"), &rav1e);
21985 let points = ours
21986 .iter()
21987 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
21988 .collect::<Vec<_>>()
21989 .join(", ");
21990 println!(
21991 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
21992 bd_rate(&aom, &ours) * 100.0,
21993 bd_rate(&rav1e, &ours) * 100.0,
21994 );
21995 println!(
21996 "| references | libaom {} | rav1e {} | | |",
21997 aom.iter()
21998 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
21999 .collect::<Vec<_>>()
22000 .join(", "),
22001 rav1e
22002 .iter()
22003 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22004 .collect::<Vec<_>>()
22005 .join(", "),
22006 );
22007 }
22008 assert_ladder_decodes();
22009 }
22010 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
22011 /// split by block class in lane-av1txdepth): depth 0 is one transform over
22012 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
22013 /// leaves and the 32x32 root, each single-reference or compound. A class
22014 /// with no counts at all never reached `commit_inter_luma` -- which is
22015 /// what its knob being off looks like (class `gate-blind-to-feature`).
22016 fn print_inter_tx_census(name: &str) {
22017 let splits = take_inter_tx_split_hits();
22018 let total: usize = splits.iter().sum();
22019 let row = |label: &str, base: usize| {
22020 let (n0, n1) = (splits[base], splits[base + 1]);
22021 format!(
22022 "{label} 0={n0} 1={n1} ({:.1}% split)",
22023 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
22024 )
22025 };
22026 eprintln!(
22027 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
22028 row("leaf single", 0),
22029 row("leaf compound", 2),
22030 row("32x32 single", 4),
22031 row("32x32 compound", 6),
22032 );
22033 // lane-txrd: which types the two searches actually COMMITTED over
22034 // this row's four encodes -- the gate could not say whether a type
22035 // search fired at all (class `gate-blind-to-feature`).
22036 const NAMES: [&str; 16] = [
22037 "IDTX",
22038 "DCT_DCT",
22039 "ADST_ADST",
22040 "ADST_DCT",
22041 "DCT_ADST",
22042 "V_DCT",
22043 "H_DCT",
22044 "FLIPADST_DCT",
22045 "DCT_FLIPADST",
22046 "FLIPADST_FLIPADST",
22047 "ADST_FLIPADST",
22048 "FLIPADST_ADST",
22049 "V_ADST",
22050 "H_ADST",
22051 "V_FLIPADST",
22052 "H_FLIPADST",
22053 ];
22054 let name_of = |t: usize| NAMES[t];
22055 for (label, hits) in [
22056 ("inter", take_inter_tx_type_hits()),
22057 ("intra", take_tx_type_hits()),
22058 ] {
22059 let total: usize = hits.iter().sum();
22060 let live: Vec<String> = hits
22061 .iter()
22062 .enumerate()
22063 .filter(|&(_, &n)| n > 0)
22064 .map(|(t, &n)| {
22065 format!(
22066 "{}={n} ({:.1}%)",
22067 name_of(t),
22068 100.0 * n as f64 / total.max(1) as f64
22069 )
22070 })
22071 .collect();
22072 eprintln!(
22073 "{name}: {label} tx_type of {total} units -- {}",
22074 live.join(" ")
22075 );
22076 }
22077 let t = take_txrd_stats();
22078 if t[0] > 0 {
22079 eprintln!(
22080 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
22081 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
22082 t[0],
22083 t[1],
22084 t[3] as f64 / 64.0,
22085 t[2],
22086 t[4] as f64 / 64.0,
22087 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
22088 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
22089 );
22090 eprintln!(
22091 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
22092 flat: dsse {:+.2}%, dbits {:+.2}%)",
22093 t[5],
22094 t[6] as f64 / 64.0,
22095 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
22096 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
22097 );
22098 }
22099 }
22100
22101 /// The video stream's coded size, from ffprobe.
22102 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
22103 crate::probe::dims(clip)
22104 }
22105
22106 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
22107 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
22108 /// superblock-aligned one, still centred and still even for 4:2:0.
22109 ///
22110 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
22111 /// superblocks by design, so no default gate row has a block the frame
22112 /// edge cuts through -- while every arbitrary export size does (3840x1608
22113 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
22114 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
22115 /// read on.
22116 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
22117 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
22118 let (w, h) = spec
22119 .split_once('x')
22120 .expect("EC_AV1_NATIVE_CROP is <width>x<height>");
22121 let (cw, ch): (usize, usize) = (
22122 w.parse().expect("crop width"),
22123 h.parse().expect("crop height"),
22124 );
22125 let (nw, nh) = crate::probe::dims(clip)?;
22126 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
22127 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
22128 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
22129 }
22130
22131 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
22132 /// with `probe_screen_detect` so the detector sweep measures exactly the
22133 /// clips the keep table is read off. Selector env vars as documented on
22134 /// the gate; a missing clip prints a SKIP and drops its row.
22135 fn native_gate_clips() -> Vec<(String, String, String)> {
22136 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
22137 let fixtures = crate::library_fixture::root();
22138 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
22139 let (film, film4k, screen) = (
22140 on("EC_AV1_NATIVE_FILM"),
22141 on("EC_AV1_NATIVE_FILM4K"),
22142 on("EC_AV1_NATIVE_SCREEN"),
22143 );
22144 // No selector at all means every clip; any selector means that subset.
22145 let all = !(film || film4k || screen);
22146 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
22147 // not film -- they print as "bars" so no reader takes them for real
22148 // content -- and the two rows below them are the real AV1 films.
22149 let mut clips: Vec<(String, String, String)> = Vec::new();
22150 for (want, label, file) in [
22151 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
22152 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
22153 ] {
22154 if !want {
22155 continue;
22156 }
22157 // lane-av1clipprobe: the one probe, so a missing clip is RED under
22158 // the require envs instead of a dropped row with no escape.
22159 if let Some(path) = crate::library_fixture::require(
22160 &format!("video/{file}"),
22161 &format!("the native BD-rate gate: {label}"),
22162 ) {
22163 clips.push((
22164 label.to_string(),
22165 path.to_str().unwrap().to_string(),
22166 "0".into(),
22167 ));
22168 }
22169 }
22170 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
22171 // The real films, taken out of the real-library manifest by codec and
22172 // coded width so no title and no home path lives in this file. Each
22173 // seek is PINNED (class `seeded fixture not reproducible`) at a
22174 // moving, non-black window -- a black leader would make every arm
22175 // read +0.000 (class `flat sample window`). Both sources are 10-bit
22176 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
22177 // what all three encoders see, so the comparison stays
22178 // encoder-vs-encoder.
22179 let pick = |width: &str| -> Option<String> {
22180 let m = manifest.as_ref().ok()?;
22181 m.lines()
22182 .skip(1)
22183 .map(|l| l.split('\t').collect::<Vec<_>>())
22184 .find(|f| {
22185 f.len() > 4
22186 && f[2] == "av1"
22187 && f[3] == width
22188 && std::path::Path::new(f[0]).exists()
22189 })
22190 .map(|f| f[0].to_string())
22191 };
22192 for (want, label, width, seek) in [
22193 (all || film, "film A (1080p source)", "1920", "00:35:00"),
22194 (
22195 all || film4k,
22196 "film B (2160p HDR source)",
22197 "3840",
22198 "00:40:00",
22199 ),
22200 ] {
22201 if !want {
22202 continue;
22203 }
22204 match pick(width) {
22205 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
22206 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
22207 }
22208 }
22209 if all || screen {
22210 match &manifest {
22211 Ok(manifest) => match manifest
22212 .lines()
22213 .skip(1)
22214 .filter_map(|l| l.split('\t').next())
22215 .find(|p| {
22216 p.contains("/OBS/")
22217 && p.ends_with(".mkv")
22218 && std::path::Path::new(p).exists()
22219 }) {
22220 Some(p) => clips.push((
22221 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
22222 p.to_string(),
22223 "0".into(),
22224 )),
22225 None => {
22226 eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
22227 }
22228 },
22229 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
22230 }
22231 }
22232 clips
22233 }
22234
22235 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
22236 /// downscales the OBS capture to 640x384, which destroys exactly the
22237 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
22238 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
22239 /// on that recipe is taken on content the tool cannot serve. This arm
22240 /// crops -- never scales -- a superblock-aligned window out of the middle
22241 /// of the capture at its own resolution (at most 1920x1024, so the wall
22242 /// stays in the minutes) and runs the same 12-frame, four-quantizer
22243 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
22244 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
22245 /// sample-exactness assertion `our_ladder` makes.
22246 ///
22247 /// It is its own `--ignored` test so the default gate's wall does not
22248 /// grow. Every variant is an environment knob, and each of those is a
22249 /// `OnceLock` read once per process, so a variant is a separate run:
22250 ///
22251 /// cargo test -p ec-av1 --release --lib -- --ignored \
22252 /// bd_rate_screen_native --nocapture # baseline
22253 /// EC_AV1_INTRABC=1 ... same command # intra block copy
22254 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
22255 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
22256 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
22257 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
22258 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
22259 ///
22260 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
22261 /// through (lane-av1pyrdef); the run prints the requested and the
22262 /// effective pyramid per clip, and a screen clip's effective one is
22263 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
22264 /// streaming facade instead, which prints the per-level frame and byte
22265 /// census and asserts ffmpeg's decode against our own decoder on all
22266 /// three planes in display order; both arms code the same bytes
22267 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
22268 ///
22269 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
22270 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
22271 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
22272 /// cost -- so every "film" column in the historical tables of this file
22273 /// is that generator, not film. The real content is `film A`, `film B`
22274 /// (native crops out of the two AV1 films the real-library manifest
22275 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
22276 /// decision only the bars rows support is not supported.
22277 ///
22278 /// Measured 2026-09-07, the five rows before and after the screen
22279 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
22280 /// BOTH real films were classified as screen content on 48/48 frames, so
22281 /// their coefficients were priced against the DEFAULT CDFs and the
22282 /// palette search ran over film; after, both are non-screen (0/48) and
22283 /// the capture is unchanged at 48/48:
22284 ///
22285 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
22286 /// |---|---|---|---|
22287 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
22288 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
22289 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
22290 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
22291 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
22292 ///
22293 /// Both bars rows and the capture are byte-identical across that change
22294 /// (their classification never moved); the palette search over film was
22295 /// costing roughly a tenth of the film rows' wall.
22296 ///
22297 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
22298 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
22299 /// the capture is gated flat and does not move a byte:
22300 ///
22301 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
22302 /// |---|---|---|---|---|
22303 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
22304 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
22305 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
22306 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
22307 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
22308 ///
22309 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
22310 /// which is the point of the shared driver: the two entry points code one
22311 /// stream. The bars rows are fixtures (recorded, never a decision); the
22312 /// two real films are what the pyramid ships for.
22313 ///
22314 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
22315 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
22316 /// setting any one of them keeps only the selected rows (the two 1080p
22317 /// rows, the two 2160p rows, the capture row respectively). A missing
22318 /// real film SKIPs its row; it never fails the gate.
22319 #[test]
22320 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
22321 fn bd_rate_screen_native() {
22322 let _knobs = crate::speed::knob_read();
22323 native_bd_arm("bd_rate_screen_native", 12, false);
22324 }
22325
22326 /// The LONG-GOP arm of the native BD gate: the same recipe as
22327 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
22328 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
22329 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
22330 /// reaches libaom as `--kf-max-dist=48` and rav1e as
22331 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
22332 /// inter pictures.
22333 ///
22334 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
22335 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
22336 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
22337 /// above 12 codes the same stream there -- the shipped `16` was measured
22338 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
22339 /// group (class `instrument at bound` / `gate blind to feature`). The
22340 /// user's exports are long GOPs, so the pyramid shape is decided here.
22341 ///
22342 /// cargo test -p ec-av1 --release --lib -- --ignored \
22343 /// bd_rate_film_long_gop --nocapture
22344 ///
22345 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
22346 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
22347 /// Read every row off the log's own "pyramid requested/effective" print,
22348 /// never off the argument order of the runs (lane-pyr3 misattributed
22349 /// three rows that way).
22350 ///
22351 /// Table: `lanes/pyr4.sweep.txt`.
22352 #[test]
22353 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
22354 fn bd_rate_film_long_gop() {
22355 let _knobs = crate::speed::knob_write();
22356 native_bd_arm("bd_rate_film_long_gop", 48, true);
22357 }
22358
22359 /// The shared driver of the two native BD arms above: `frames` pictures
22360 /// per row (the sequence's `gop` is the same number, so one key frame),
22361 /// four quantizers, `films_only` dropping every row but the two real
22362 /// films.
22363 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
22364 if !have_ffmpeg() {
22365 eprintln!("SKIP {label}: no ffmpeg");
22366 return;
22367 }
22368 let mut clips = native_gate_clips();
22369 if films_only {
22370 clips.retain(|(name, _, _)| name.starts_with("film "));
22371 }
22372 if clips.is_empty() {
22373 eprintln!("SKIP {label}: no clip");
22374 return;
22375 }
22376
22377 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
22378 .iter()
22379 .map(|q| {
22380 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
22381 .map(String::from)
22382 .to_vec()
22383 })
22384 .collect();
22385 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
22386 .iter()
22387 .map(|q| {
22388 vec![
22389 "-rav1e-params".to_string(),
22390 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
22391 ]
22392 })
22393 .collect();
22394 println!(
22395 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
22396 intrabc {}, palette maxcolors {}",
22397 armed_tiles(),
22398 crate::par::tile_threads(),
22399 intrabc_enabled(),
22400 palette_max_colors(),
22401 );
22402 println!(
22403 "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |"
22404 );
22405 println!("|---|---|---|---|---|");
22406 for (name, path, seek) in &clips {
22407 let fctx = &crate::decode::FrameCtx::for_encoder();
22408 if probe_dims(path).is_none() {
22409 eprintln!("SKIP {name}: ffprobe gave no size");
22410 continue;
22411 }
22412 // A whole number of 128-wide superblocks, at most 1920x1024, out
22413 // of the middle of the frame; the offsets stay even for 4:2:0.
22414 // ONE definition, shared with `examples/enc_probe` so the probe
22415 // cannot measure a different window than this gate (lane-probe).
22416 let (vf, cw, ch) = match native_crop_override(path) {
22417 Some(over) => over,
22418 None => crate::probe::gate_crop(path),
22419 };
22420 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
22421 SCREEN_FRAMES.iter().for_each(|c| {
22422 c.store(0, std::sync::atomic::Ordering::Relaxed);
22423 });
22424 let _ = crate::tile::take_palette_hits();
22425 let _ = crate::tile::take_palette_uv_hits();
22426 let _ = crate::tile::take_intrabc_hits();
22427 let _ = take_intrabc_search();
22428 let _ = crate::tile::take_filter_intra_hits();
22429 let _ = take_edge_census();
22430 // The sequence path itself codes the pyramid now
22431 // (lane-av1pyrdef), and prints what it requested and what the
22432 // content gate left effective.
22433 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
22434 // lane-sse: the blocks the true frame edge cuts through, and how
22435 // much of their RAW squared error sat in the padding the encoder
22436 // invented past it -- what the inside-only score stopped ranking
22437 // on. Empty on a superblock-aligned crop, which is every default
22438 // gate row (class `gate-blind-to-feature`).
22439 if edge_census() {
22440 for (side, n, inside, padding) in take_edge_census() {
22441 eprintln!(
22442 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
22443 padding_sse={padding} ({:.1}% of raw)",
22444 100.0 * padding as f64 / (inside + padding).max(1) as f64,
22445 );
22446 }
22447 }
22448 // gate-blind-to-feature: what the screen tools actually did at
22449 // native resolution, over this clip's four encodes.
22450 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
22451 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
22452 // Which tables the SEARCH priced against, per frame arming
22453 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
22454 // real starting ones. A film clip must show every inter arming on
22455 // the real side, a screen clip none of them.
22456 let (price_default, price_real) = crate::tile::take_pricing_hits();
22457 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
22458 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
22459 // superblocks stayed whole, and how many of those coded a
22460 // residual, split that residual's luma, or took a compound
22461 // reference (class `gate-blind-to-feature`).
22462 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
22463 // the superblocks offered the trial were coded whole.
22464 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
22465 eprintln!(
22466 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
22467 {i64_edge} on a superblock the frame edge cuts",
22468 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
22469 );
22470 eprintln!(
22471 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
22472 {} (search) / {} (writer); rect/AB pieces with a residual \
22473 {} (search) / {} (writer)",
22474 take_b128_none_hits(),
22475 crate::tile::take_sb128_none_hits(),
22476 take_b128_residual_hits(),
22477 crate::tile::take_sb128_residual_hits(),
22478 take_b128_rectres_hits(),
22479 crate::tile::take_sb128_rectres_hits(),
22480 );
22481 eprintln!(
22482 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
22483 take_b64_root_hits(),
22484 take_b64_residual_hits(),
22485 take_b64_var_tx_hits(),
22486 take_b64_compound_hits(),
22487 );
22488 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
22489 // of every priced block): what the deadzone quantiser handed the
22490 // RDOQ pass and what the pass changed, over every TRIAL block of
22491 // this row's four encodes -- not over the coded stream, so it is
22492 // the bits AT STAKE in the search, not in the bitstream.
22493 let rq = crate::tile::take_rdoq_stats();
22494 if rq[0] > 0 {
22495 eprintln!(
22496 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
22497 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
22498 rq[0],
22499 rq[1],
22500 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
22501 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
22502 rq[4],
22503 rq[5],
22504 rq[7] as f64 / 64.0,
22505 rq[6] as f64 / 64.0,
22506 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
22507 );
22508 }
22509 // lane-av1obmc2: the same motion_mode census the 640x384 gate
22510 // prints (class `gate-blind-to-feature`) -- how many blocks coded
22511 // the symbol at each footprint and how many took OBMC. Without it
22512 // the native table, which is the standing keep table, could not
22513 // say whether the tool fired at all.
22514 let mm = crate::tile::take_motion_mode_hits();
22515 eprintln!(
22516 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
22517 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
22518 eligible)",
22519 mm[0],
22520 mm[1],
22521 mm[2],
22522 mm[3],
22523 mm[4],
22524 mm[5],
22525 mm[6],
22526 mm[7],
22527 mm[8],
22528 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22529 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22530 mm.iter().sum::<usize>(),
22531 );
22532 print_inter_tx_census(name);
22533 // lane-last2 (class `gate-blind-to-feature`): which reference the
22534 // 32x32-and-below inter blocks of this clip's four encodes chose.
22535 // The native table is the standing keep table, so a second past
22536 // reference that never won a block has to be visible HERE and not
22537 // only in a synthetic witness.
22538 let rh = crate::encode::take_ref_frame_hits();
22539 let rtot: usize = rh.iter().sum();
22540 eprintln!(
22541 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
22542 (LAST2 {:.1}%)",
22543 rh[1],
22544 rh[2],
22545 rh[4],
22546 rh[7],
22547 rtot,
22548 100.0 * rh[2] as f64 / rtot.max(1) as f64,
22549 );
22550 let palette = crate::tile::take_palette_hits();
22551 let palette_uv = crate::tile::take_palette_uv_hits();
22552 let ibc = crate::tile::take_intrabc_hits();
22553 let search = take_intrabc_search();
22554 eprintln!(
22555 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
22556 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
22557 won {})",
22558 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
22559 palette[0],
22560 palette_uv[0],
22561 ibc[0],
22562 search[0],
22563 search[1],
22564 search[2],
22565 );
22566 // gate-blind-to-feature: how often the five recursive filter-intra
22567 // modes actually won a block over this clip's four encodes -- a
22568 // tool that never fires is not measured by the row above it.
22569 let fi = crate::tile::take_filter_intra_hits();
22570 eprintln!(
22571 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
22572 filter_intra_on(),
22573 fi[0],
22574 fi[1],
22575 fi[2],
22576 fi[3],
22577 fi[4],
22578 fi[5],
22579 );
22580 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
22581 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
22582 assert_monotone(&format!("{name}: ours"), &ours);
22583 assert_monotone(&format!("{name}: libaom"), &aom);
22584 assert_monotone(&format!("{name}: rav1e"), &rav1e);
22585 let points = ours
22586 .iter()
22587 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22588 .collect::<Vec<_>>()
22589 .join(", ");
22590 println!(
22591 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
22592 bd_rate(&aom, &ours) * 100.0,
22593 bd_rate(&rav1e, &ours) * 100.0,
22594 );
22595 // lane-pareto2: the two references at THEIR fast presets, plus
22596 // SVT-AV1, measured in the SAME arm as the row above -- the only
22597 // way the wall column of a Pareto table means anything (class:
22598 // wall tables are comparable only inside one interleaved batch).
22599 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
22600 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
22601 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
22602 [50, 100, 150, 200]
22603 .iter()
22604 .map(|q| {
22605 vec![
22606 "-rav1e-params".to_string(),
22607 format!(
22608 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
22609 ),
22610 ]
22611 })
22612 .collect()
22613 };
22614 let aom_at = |cu: u32| -> Vec<Vec<String>> {
22615 [5, 20, 35, 45]
22616 .iter()
22617 .map(|q| {
22618 vec![
22619 "-cpu-used".to_string(),
22620 cu.to_string(),
22621 "-b:v".to_string(),
22622 "0".to_string(),
22623 "-crf".to_string(),
22624 q.to_string(),
22625 ]
22626 })
22627 .collect()
22628 };
22629 let svt_at = |pr: u32| -> Vec<Vec<String>> {
22630 [20, 35, 45, 55]
22631 .iter()
22632 .map(|q| {
22633 vec![
22634 "-preset".to_string(),
22635 pr.to_string(),
22636 "-crf".to_string(),
22637 q.to_string(),
22638 "-svtav1-params".to_string(),
22639 "lp=1".to_string(),
22640 ]
22641 })
22642 .collect()
22643 };
22644 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
22645 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
22646 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
22647 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
22648 ];
22649 if have_encoder("libsvtav1") {
22650 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
22651 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
22652 } else {
22653 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
22654 }
22655 for (label, encoder, points) in arms {
22656 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
22657 // A REFERENCE stream our decoder cannot read is a note in
22658 // this table, not a gate failure: these rows exist to
22659 // price the references, and `assert_ladder_decodes` keeps
22660 // its teeth for the two ladders the keep table is read off.
22661 let notes =
22662 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
22663 if !notes.is_empty() {
22664 eprintln!(
22665 "{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)",
22666 notes.len()
22667 );
22668 }
22669 assert_monotone(&format!("{name}: {label}"), &lad);
22670 println!(
22671 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
22672 bd_rate(&aom, &lad) * 100.0,
22673 bd_rate(&rav1e, &lad) * 100.0,
22674 );
22675 }
22676 }
22677 }
22678 assert_ladder_decodes();
22679 }
22680
22681 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
22682 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
22683 /// on the two film clips at their native gate crop. The 2160p clip loses
22684 /// at every arm of the propagating map and the named suspect was that its
22685 /// heavily filtered flat cells give a tiny denominator, so the dependence
22686 /// ratio explodes exactly where coding is cheap; this prints the numbers
22687 /// that confirm or refute it.
22688 #[test]
22689 // Reads ONLY `fixtures/video/h264-{1080p,2160p}-23.976-8bit.mp4` -- the
22690 // COLOUR-BARS fixtures, in a centred crop. It never opens a film, so the
22691 // old reason ("the film fixtures") sent readers looking for content the
22692 // test cannot read. 0.9 s; prints the per-cell intra-MAD distribution.
22693 #[ignore = "0.9 s; reads only the fixtures/video COLOUR-BARS clips (not the films) and prints the per-cell intra-MAD distribution"]
22694 fn tpl_intra_denominator_histogram() {
22695 let _knobs = crate::speed::knob_read();
22696 if !have_ffmpeg() {
22697 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
22698 return;
22699 }
22700 for (label, file) in [
22701 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
22702 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
22703 ] {
22704 // lane-av1clipprobe: the one probe, so a missing clip is RED under
22705 // the require envs. With both clips absent this histogram used to
22706 // loop zero times and pass having printed nothing.
22707 let Some(path) = crate::library_fixture::require(
22708 &format!("video/{file}"),
22709 &format!("tpl_intra_denominator_histogram: {label}"),
22710 ) else {
22711 continue;
22712 };
22713 let path = path.to_str().unwrap();
22714 let Some((nw, nh)) = probe_dims(path) else {
22715 eprintln!("SKIP {label}: ffprobe gave no size");
22716 continue;
22717 };
22718 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
22719 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
22720 let source = clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
22721 let mut costs: Vec<f64> = Vec::new();
22722 for pic in &source {
22723 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
22724 costs.extend(
22725 super::tpl_intra_costs(&y8, cw, ch)
22726 .iter()
22727 .map(|&c| f64::from(c)),
22728 );
22729 }
22730 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
22731 let mut sorted = costs.clone();
22732 sorted.sort_by(f64::total_cmp);
22733 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
22734 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
22735 eprintln!(
22736 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
22737 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
22738 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
22739 below 1.0x {} ({:.1}%)",
22740 costs.len(),
22741 q(0.0),
22742 q(0.01),
22743 q(0.05),
22744 q(0.25),
22745 q(0.50),
22746 q(0.75),
22747 q(0.99),
22748 q(1.0),
22749 below(0.25),
22750 100.0 * below(0.25) as f64 / costs.len() as f64,
22751 below(0.5),
22752 100.0 * below(0.5) as f64 / costs.len() as f64,
22753 below(1.0),
22754 100.0 * below(1.0) as f64 / costs.len() as f64,
22755 );
22756 }
22757 }
22758
22759 /// The probe arms the gate's source (lane-probe, class `instrument
22760 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
22761 /// command line and had no `-ss`, so it read film B from frame 0 -- a
22762 /// black leader -- and coded 59 kB where the gate's own ladder point
22763 /// coded 89 kB of the same title; every census taken through it was
22764 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
22765 /// the shared loader honours the seek (arming the probe's way and the
22766 /// gate's way gives byte-identical streams, and dropping the seek does
22767 /// not), on a synthetic clip whose content moves over time.
22768 #[test]
22769 fn the_probe_arms_the_gates_source() {
22770 let _knobs = crate::speed::knob_write();
22771 if !have_ffmpeg() {
22772 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
22773 return;
22774 }
22775 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
22776 std::fs::create_dir_all(&dir).unwrap();
22777 let clip = dir.join("testsrc2.y4m");
22778 // 384x202: neither side is a multiple of 128, so the gate's centre
22779 // window is a real derivation and not the frame itself -- exactly the
22780 // shape film B has (3840x1608, never 3840x2160).
22781 let ok = Command::new("ffmpeg")
22782 .args([
22783 "-v",
22784 "error",
22785 "-y",
22786 "-f",
22787 "lavfi",
22788 "-i",
22789 "testsrc2=size=384x202:rate=10",
22790 ])
22791 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
22792 .arg(&clip)
22793 .status()
22794 .expect("ffmpeg failed to run")
22795 .success();
22796 assert!(ok, "ffmpeg could not write the synthetic clip");
22797 let path = clip.to_str().unwrap();
22798
22799 // The window: superblock-aligned, centred, even offsets.
22800 let (vf, w, h) = crate::probe::gate_crop(path);
22801 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
22802
22803 let (seek, q) = ("00:00:01", 150u8);
22804 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
22805 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
22806 assert!(
22807 gate.iter()
22808 .zip(&probe)
22809 .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
22810 "the probe's source differs from the gate's at the same window"
22811 );
22812 let bytes = |src: &[Picture]| {
22813 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
22814 .unwrap()
22815 .stream
22816 };
22817 assert_eq!(
22818 bytes(&gate),
22819 bytes(&probe),
22820 "probe and gate code different bytes"
22821 );
22822 // The two witnesses that both halves of the arming reach ffmpeg: the
22823 // seek, and the crop's own offset (the film-B defect in miniature --
22824 // the probe was reading `crop=..:568` of a 1608-high frame).
22825 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
22826 assert_ne!(
22827 bytes(&gate),
22828 bytes(&unseeked),
22829 "seeked and unseeked arming coded the same bytes -- the seek is inert"
22830 );
22831 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
22832 assert_ne!(
22833 bytes(&gate),
22834 bytes(&offset),
22835 "centred and top-aligned windows coded the same bytes -- the crop is inert"
22836 );
22837 std::fs::remove_dir_all(&dir).ok();
22838 }
22839
22840 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
22841 /// point inside the test binary, to compare against `examples/enc_probe`.
22842 #[test]
22843 // Panics on the first `env::var(...).unwrap()` when unset -- it needs FIVE
22844 // variables, not "a clip": `EC_PARITY_DIMS`, `EC_PARITY_FRAMES`,
22845 // `EC_PARITY_Q`, `EC_PARITY_CLIP`, `EC_PARITY_SS`, `EC_PARITY_VF`. Prints
22846 // one PARITY line (bytes + fnv1a of the stream) to diff against
22847 // `examples/enc_probe`.
22848 #[ignore = "diagnostic: needs EC_PARITY_{DIMS,FRAMES,Q,CLIP,SS,VF} -- all five, it unwraps the first missing one; prints one PARITY hash line"]
22849 fn probe_parity_point() {
22850 let _knobs = crate::speed::knob_write();
22851 let g = |k: &str| std::env::var(k).unwrap();
22852 let (w, h) = g("EC_PARITY_DIMS")
22853 .split_once(':')
22854 .map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap()))
22855 .unwrap();
22856 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
22857 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
22858 let source = clip_frames_vf(
22859 &g("EC_PARITY_CLIP"),
22860 &g("EC_PARITY_SS"),
22861 &g("EC_PARITY_VF"),
22862 w,
22863 h,
22864 frames,
22865 );
22866 let fctx = &crate::decode::FrameCtx::for_encoder();
22867 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
22868 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
22869 for &b in &e.stream {
22870 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
22871 }
22872 eprintln!(
22873 "PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
22874 e.stream.len(),
22875 crate::speed::speed(),
22876 crate::encoder::Pyramid::from_env(),
22877 last_sequence_pyramid()
22878 );
22879 }
22880 /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The
22881 /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`):
22882 /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in
22883 /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32
22884 /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags
22885 /// the census's far row measures were already banked by `arf_altref`.
22886 /// This census stays the PRICING arm (class `gate-blind-to-feature`): its
22887 /// best-of-two SAD shares are read against the fire share the gate census
22888 /// prints (`references ... LAST2 n (n%)`) and the refutation in
22889 /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the
22890 /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off
22891 /// `LAST`, the backward `ALTREF`, and the rate term price in.
22892 ///
22893 /// The measurement is on the gate's own window and loader (`gate_crop`,
22894 /// 12 pictures) of the two real films: every 16x16 luma block of every
22895 /// picture gets one full-pel diamond search against the NEAR reference
22896 /// and the same search against the FAR one, at the two lags the pyramid
22897 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
22898 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
22899 /// reference wins at all and by more than 10%, and -- the number the
22900 /// decision is taken on -- the total SAD of best-of-{near, far} against
22901 /// the total SAD of near alone, which is the prediction energy a second
22902 /// reference could remove before any rate is paid for naming it.
22903 ///
22904 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
22905 #[test]
22906 #[ignore = "reads the real films"]
22907 fn last2_census() {
22908 if !have_ffmpeg() {
22909 eprintln!("SKIP last2_census: no ffmpeg");
22910 return;
22911 }
22912 const SIDE: usize = 16;
22913 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
22914 // `None` when the displaced block leaves the picture.
22915 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
22916 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
22917 if sy < 0 || sx < 0 {
22918 return None;
22919 }
22920 let (sy, sx) = (sy as usize, sx as usize);
22921 if sy + SIDE > r.height || sx + SIDE > r.width {
22922 return None;
22923 }
22924 let mut acc = 0u64;
22925 for row in 0..SIDE {
22926 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
22927 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
22928 acc += c
22929 .iter()
22930 .zip(p)
22931 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
22932 .sum::<u64>();
22933 }
22934 Some(acc)
22935 };
22936 // A log-step diamond from the zero motion vector: the cheapest search
22937 // that still finds real pans. Both references get exactly this one,
22938 // so the comparison is search-fair.
22939 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
22940 let mut best = (
22941 sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX),
22942 (0isize, 0isize),
22943 );
22944 let mut step = 16isize;
22945 while step >= 1 {
22946 let centre = best.1;
22947 for (dy, dx) in [
22948 (-1, -1),
22949 (-1, 0),
22950 (-1, 1),
22951 (0, -1),
22952 (0, 1),
22953 (1, -1),
22954 (1, 0),
22955 (1, 1),
22956 ] {
22957 let mv = (centre.0 + dy * step, centre.1 + dx * step);
22958 if let Some(s) = sad(cur, r, bx, by, mv) {
22959 if s < best.0 {
22960 best = (s, mv);
22961 }
22962 }
22963 }
22964 step /= 2;
22965 }
22966 best.0
22967 };
22968 println!(
22969 "| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |"
22970 );
22971 println!("|---|---|---|---|---|---|---|---|");
22972 for (name, path, seek) in native_gate_clips() {
22973 if !name.starts_with("film ") {
22974 continue;
22975 }
22976 let (vf, cw, ch) = crate::probe::gate_crop(&path);
22977 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
22978 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
22979 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
22980 let (mut near_sad, mut best_sad) = (0u64, 0u64);
22981 for i in far..pictures.len() {
22982 let cur = &pictures[i];
22983 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
22984 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
22985 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
22986 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
22987 blocks += 1;
22988 wins += u64::from(f < n);
22989 big += u64::from(f as f64 * 1.1 < n as f64);
22990 near_sad += n;
22991 best_sad += n.min(f);
22992 }
22993 }
22994 }
22995 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
22996 println!(
22997 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
22998 pct(wins),
22999 pct(big),
23000 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
23001 );
23002 }
23003 }
23004 }
23005
23006 /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
23007 /// temporal filter of its SOURCE would take off it, priced before any
23008 /// encoder change (class `gate-blind-to-feature`).
23009 ///
23010 /// The stream census says our top ARF costs 6992 B a frame against
23011 /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
23012 /// quality, and that 61% of the gap is residual, not syntax. Two
23013 /// explanations are separable here without an encoder: our anchor
23014 /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
23015 /// the residual it codes at that lag is dominated by film grain, which no
23016 /// motion search can predict (source noise). So, per ARF position of the
23017 /// gate's own 48-picture window:
23018 ///
23019 /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
23020 /// * the same at lag 8 with the CURRENT picture temporally filtered --
23021 /// a libaom-shaped motion-compensated average of the +-2 display
23022 /// neighbours, weights `exp(-mse / strength)` -- which is the residual
23023 /// energy an ARF temporal filter would remove, and
23024 /// * PSNR of that filtered picture against the unfiltered one, the
23025 /// CEILING the filtered ARF's own PSNR is then measured under (the
23026 /// BD gate scores against the unfiltered source).
23027 ///
23028 /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
23029 /// --ignored arf_pred_census --nocapture
23030 #[test]
23031 #[ignore = "reads the real films"]
23032 fn arf_pred_census() {
23033 if !have_ffmpeg() {
23034 eprintln!("SKIP arf_pred_census: no ffmpeg");
23035 return;
23036 }
23037 const SIDE: usize = 16;
23038 let strength: f64 = std::env::var("EC_ARF_TF_S")
23039 .ok()
23040 .and_then(|v| v.parse().ok())
23041 .unwrap_or(30.0);
23042 let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
23043 // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
23044 // when the displaced block leaves the picture.
23045 let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
23046 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
23047 if sy < 0 || sx < 0 {
23048 return None;
23049 }
23050 let (sy, sx) = (sy as usize, sx as usize);
23051 if sy + SIDE > r.height || sx + SIDE > r.width {
23052 return None;
23053 }
23054 let mut acc = 0u64;
23055 for row in 0..SIDE {
23056 let c = &cur[row * cw..][..SIDE];
23057 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
23058 acc += c
23059 .iter()
23060 .zip(p)
23061 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
23062 .sum::<u64>();
23063 }
23064 Some((acc, (sy, sx)))
23065 };
23066 // The same log-step diamond `last2_census` uses, so the two censuses'
23067 // SADs are comparable.
23068 let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
23069 let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
23070 Some(v) => v,
23071 None => return (u64::MAX, (by, bx)),
23072 };
23073 let mut centre = (0isize, 0isize);
23074 let mut step = 16isize;
23075 while step >= 1 {
23076 let from = centre;
23077 for (dy, dx) in [
23078 (-1, -1),
23079 (-1, 0),
23080 (-1, 1),
23081 (0, -1),
23082 (0, 1),
23083 (1, -1),
23084 (1, 0),
23085 (1, 1),
23086 ] {
23087 let mv = (from.0 + dy * step, from.1 + dx * step);
23088 if let Some(s) = at(cur, cw, r, bx, by, mv) {
23089 if s.0 < best.0 {
23090 best = s;
23091 centre = mv;
23092 }
23093 }
23094 }
23095 step /= 2;
23096 }
23097 best
23098 };
23099 println!(
23100 "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
23101 );
23102 println!("|---|---|---|---|---|---|---|");
23103 for (name, path, seek) in native_gate_clips() {
23104 if !name.starts_with("film ") {
23105 continue;
23106 }
23107 let (vf, cw, ch) = crate::probe::gate_crop(&path);
23108 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
23109 let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
23110 let (mut tf_sse, mut tf_px) = (0f64, 0u64);
23111 for i in (8..pictures.len()).step_by(8) {
23112 arfs += 1;
23113 let cur = &pictures[i];
23114 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
23115 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
23116 let block: Vec<u16> = (0..SIDE)
23117 .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
23118 .collect();
23119 n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
23120 n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
23121 // The temporal filter: each +-2 display neighbour is
23122 // motion-compensated onto this block and averaged in
23123 // with libaom's shape, a weight that falls with the
23124 // match's own mean squared error.
23125 let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
23126 let mut wsum = 1.0f64;
23127 // `EC_ARF_TF_PAST=1` restricts the filter to the
23128 // DISPLAY-PAST neighbours -- the only ones the
23129 // encoder's own group buffer holds when it codes its
23130 // top ARF (the group's future is not buffered yet).
23131 let offs: &[isize] = match past {
23132 true => &[-2, -1],
23133 false => &[-2, -1, 1, 2],
23134 };
23135 for &d in offs {
23136 let j = i as isize + d;
23137 let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
23138 else {
23139 continue;
23140 };
23141 let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
23142 let mut sse = 0f64;
23143 for row in 0..SIDE {
23144 for col in 0..SIDE {
23145 let d = f64::from(block[row * SIDE + col])
23146 - f64::from(nb.y[(sy + row) * nb.width + sx + col]);
23147 sse += d * d;
23148 }
23149 }
23150 let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp();
23151 for row in 0..SIDE {
23152 for col in 0..SIDE {
23153 acc[row * SIDE + col] +=
23154 w * f64::from(nb.y[(sy + row) * nb.width + sx + col]);
23155 }
23156 }
23157 wsum += w;
23158 }
23159 let filtered: Vec<u16> = acc
23160 .iter()
23161 .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16)
23162 .collect();
23163 for (a, b) in filtered.iter().zip(&block) {
23164 let d = f64::from(*a) - f64::from(*b);
23165 tf_sse += d * d;
23166 }
23167 tf_px += (SIDE * SIDE) as u64;
23168 ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0;
23169 px += (SIDE * SIDE) as u64;
23170 }
23171 }
23172 }
23173 let per = |v: u64| v as f64 / px.max(1) as f64;
23174 let mse = tf_sse / tf_px.max(1) as f64;
23175 println!(
23176 "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |",
23177 per(n8),
23178 per(n4),
23179 per(ntf),
23180 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64,
23181 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(),
23182 );
23183 }
23184 }
23185
23186 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
23187 /// hardwire the REGULAR kernel, so the encoder could not have coded a
23188 /// SMOOTH or SHARP frame even if the header had said so -- the search,
23189 /// the trials, the recon and the frame header now all read
23190 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
23191 /// distinct stream (a filter that never reached the prediction would code
23192 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
23193 /// reconstructs every frame of each of them exactly, which is what proves
23194 /// the header and the prediction agree.
23195 #[test]
23196 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
23197 let _knobs = crate::speed::knob_write();
23198 if !have_ffmpeg() {
23199 eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg");
23200 return;
23201 }
23202 let (width, height) = (256usize, 128usize);
23203 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
23204 // all three kernels would code the same bytes and the test would pass
23205 // on a wiring that does nothing (class `fixture proves the symbol, not
23206 // the signal`). `panned_test_card` shifts by whole pixels, so the
23207 // search finds the sub-pel positions off the reconstruction instead:
23208 // three frames of a slow diagonal pan.
23209 let pictures: Vec<Picture> = (0..3)
23210 .map(|i| panned_test_card(width, height, i * 3))
23211 .collect();
23212 let mut streams = Vec::new();
23213 for filter in [
23214 ec_av1_syntax::InterpolationFilter::Eighttap,
23215 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
23216 ec_av1_syntax::InterpolationFilter::EighttapSharp,
23217 ] {
23218 set_frame_interp(Some(filter));
23219 let fctx = &crate::decode::FrameCtx::for_encoder();
23220 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
23221 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
23222 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
23223 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
23224 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
23225 assert_eq!(
23226 decoded.y, frame.reconstruction.y,
23227 "{filter:?} frame {i}: luma"
23228 );
23229 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
23230 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
23231 }
23232 streams.push((filter, encoded.stream));
23233 }
23234 set_frame_interp(None);
23235 for (i, (fa, a)) in streams.iter().enumerate() {
23236 for (fb, b) in &streams[i + 1..] {
23237 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
23238 }
23239 }
23240 }
23241
23242 /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
23243 /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
23244 /// residual outright (`round_to_valid_mv` rounds it away first), so the
23245 /// finest vector the encoder could commit to was a quarter pel. With the
23246 /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
23247 /// non-zero component and the search's fourth stage refines to the
23248 /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
23249 /// on arm, and -- the part that makes it a signal rather than a symbol
23250 /// count (class `fixture proves the symbol, not the signal`) -- that some
23251 /// of them come out ZERO, i.e. name a vector the off arm cannot code at
23252 /// all. Both streams are decoded by ffmpeg AND by this crate's own
23253 /// decoder and asserted sample-exact against the encoder's own
23254 /// reconstruction, which is what proves the header bit and the symbols
23255 /// agree.
23256 #[test]
23257 fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
23258 let _knobs = crate::speed::knob_write();
23259 if !have_ffmpeg() {
23260 eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg");
23261 return;
23262 }
23263 let (width, height) = (256usize, 128usize);
23264 let pictures: Vec<Picture> = (0..3)
23265 .map(|i| panned_test_card(width, height, i * 3))
23266 .collect();
23267 let mut arms = Vec::new();
23268 for hp in [false, true] {
23269 set_high_precision_mv(Some(hp));
23270 let _ = crate::tile::take_hp_symbols();
23271 let fctx = &crate::decode::FrameCtx::for_encoder();
23272 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
23273 .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
23274 let (symbols, eighth) = crate::tile::take_hp_symbols();
23275 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
23276 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
23277 assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
23278 assert_eq!(
23279 ours.len(),
23280 pictures.len(),
23281 "hp={hp}: our decoder frame count"
23282 );
23283 for (i, e) in encoded.frames.iter().enumerate() {
23284 for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
23285 if let Some((plane, s, got, want)) =
23286 first_plane_mismatch(got, &e.reconstruction)
23287 {
23288 panic!(
23289 "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
23290 the encoder reconstructed {want}"
23291 );
23292 }
23293 }
23294 }
23295 arms.push((symbols, eighth, encoded.stream));
23296 }
23297 set_high_precision_mv(None);
23298 let (off, on) = (&arms[0], &arms[1]);
23299 assert_eq!(
23300 off.0, 0,
23301 "a frame without the header bit codes no hp symbol"
23302 );
23303 assert!(
23304 on.0 > 0,
23305 "a high-precision frame codes hp symbols (got {})",
23306 on.0
23307 );
23308 assert!(
23309 on.1 > 0,
23310 "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
23311 on.0
23312 );
23313 assert_ne!(off.2, on.2, "the two arms coded the same bytes");
23314 println!(
23315 "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
23316 off.0,
23317 off.2.len(),
23318 on.0,
23319 on.1,
23320 on.2.len()
23321 );
23322 }
23323}