forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB052d1d3Tahinli2 months ago3627 commits

encode.rs23377 lines, 1.0 MiBHistoryRawDownload
1//! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out.
2//!
3//! This is the layer that turns the pieces below it — the intra predictors of
4//! [`crate::intra`], the forward transform and quantizer of
5//! [`crate::transform`], and the tile writer of [`crate::tile`] — into
6//! something that takes a picture. Every block is 32x32 (its chroma 16x16),
7//! which is the subset the tile writer codes, and each one picks its luma mode
8//! from the seven non-directional ones by rate-distortion; chroma searches
9//! its own `uv_mode` over the seven that read no further than the row above
10//! and the column to the left, its transform type derived from that mode the
11//! way the decoder derives it. Block sizes are what a loop above this would
12//! choose between.
13//!
14//! The encoder carries its own reconstruction, because prediction reads it: a
15//! block predicts from the reconstructed samples above and to its left, exactly
16//! as the decoder will. That makes the reconstruction a claim about what a
17//! decoder produces, and it is gated as one — sample for sample against ffmpeg.
18
19use crate::decode::WithRef;
20use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
21use ec_av1_syntax::{
22 CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams,
23 LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode,
24};
25use ec_core::{Error, Result};
26
27use crate::cdf;
28use crate::cdf_state::TxbSet;
29use crate::frame::frame_obu;
30use crate::intra::{
31 D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED,
32 SMOOTH_V_PRED, V_PRED,
33};
34use crate::mc;
35use crate::motion;
36use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16};
37use crate::obu::temporal_delimiter;
38use crate::quant::ac_q;
39use crate::sequence::sequence_header_obu;
40use crate::tile::{
41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
42};
43#[cfg(test)]
44use crate::transform::forward_and_quantize;
45use crate::transform::{
46 TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
47 forward_and_quantize_typed_scaled,
48};
49
50/// The side of the larger of the two luma blocks this encoder codes, in
51/// samples.
52const BLOCK: usize = 32;
53
54/// The side of the smaller one, which a 32x32 block may be split into four of.
55const SUB: usize = 16;
56
57/// The side of a superblock, which is what the partition tree starts from.
58pub(crate) const SUPERBLOCK: usize = 64;
59
60// lane-sb128 r1: the superblock size in samples the intra-reach rules
61// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the
62// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and
63// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128
64// superblock changes every answer inside it (the tables themselves are
65// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
66// stays the encoder's own fixed 64.
67
68/// Sets the superblock size [`Reach`] answers against (64 or 128).
69pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
70 fctx.reach_sb_px.with(|c| c.set(px));
71}
72
73fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
74 fctx.reach_sb_px.with(|c| c.get())
75}
76
77/// 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.
1810///
1811/// The chroma extent is `ROUND_POWER_OF_TWO(size, 1)` -- `(size + 1) / 2`,
1812/// libaom's `av1_common_plane_width` (`av1/common/av1_common_int.h`) -- so an
1813/// ODD declared luma size keeps the chroma column a decoder keeps (a 65-wide
1814/// 4:2:0 frame has 33, not 32). Every even size is unaffected: `(2k+1)/2 ==
1815/// k`, so this is a no-op for every caller `encode_key_frame`'s even-size
1816/// check lets through.
1817pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1818 let reconstruction = &encoded.reconstruction;
1819 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
1820 let cropped = if reconstruction.width == width && reconstruction.height == height {
1821 reconstruction.clone()
1822 } else {
1823 Picture {
1824 width,
1825 height,
1826 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1827 u: crop_plane(&reconstruction.u, reconstruction.width / 2, cw, ch),
1828 v: crop_plane(&reconstruction.v, reconstruction.width / 2, cw, ch),
1829 }
1830 };
1831 Encoded {
1832 stream: encoded.stream.clone(),
1833 modes: encoded.modes.clone(),
1834 inter_block_share: encoded.inter_block_share,
1835 reconstruction: cropped,
1836 tile: encoded.tile.clone(),
1837 mi_cols: encoded.mi_cols,
1838 mi_rows: encoded.mi_rows,
1839 base_q_idx: encoded.base_q_idx,
1840 tx_select: encoded.tx_select,
1841 switchable_motion_mode: encoded.switchable_motion_mode,
1842 screen: encoded.screen,
1843 reduced_tx_set: encoded.reduced_tx_set,
1844 start_cdfs: encoded.start_cdfs.clone(),
1845 next_cdfs: encoded.next_cdfs.clone(),
1846 loop_filter: encoded.loop_filter,
1847 loop_restoration: encoded.loop_restoration,
1848 allow_intrabc: encoded.allow_intrabc,
1849 delta: encoded.delta.clone(),
1850 cdef: encoded.cdef,
1851 }
1852}
1853
1854/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1855/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1856#[derive(Clone)]
1857pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1858
1859impl std::fmt::Debug for CdfSnapshot {
1860 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1861 f.write_str("CdfSnapshot")
1862 }
1863}
1864
1865/// What one call to [`encode_key_frame`] produced.
1866#[derive(Clone, Debug)]
1867pub struct Encoded {
1868 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1869 /// OBU carrying one tile.
1870 pub stream: Vec<u8>,
1871 /// What a decoder will produce from `stream` — the encoder's own
1872 /// reconstruction, which its prediction was built on.
1873 pub reconstruction: Picture,
1874 /// The luma intra mode each block was coded under, in the order the blocks
1875 /// are coded — raster order among the quadrants of each superblock, and
1876 /// among the four 16x16 blocks of a quadrant that was split.
1877 pub modes: Vec<u8>,
1878 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1879 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1880 /// for a key frame, which has no such choice — so a caller can tell a
1881 /// frame with no motion worth coding from one that never got the chance.
1882 pub inter_block_share: f64,
1883 /// The tile payload alone, undecorated by any OBU framing, and the frame
1884 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1885 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1886 /// off the wire by parsing `stream`'s OBUs instead.
1887 pub(crate) tile: Vec<u8>,
1888 pub(crate) mi_cols: u32,
1889 pub(crate) mi_rows: u32,
1890 pub(crate) base_q_idx: u8,
1891 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1892 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1893 /// and reading it off `stream`'s header is what `decode_stream` does. A
1894 /// test that decodes `tile` directly must pass this one along, or it reads
1895 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1896 /// block.
1897 pub(crate) tx_select: bool,
1898 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1899 /// bit that makes every eligible single-reference inter block carry a
1900 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1901 /// decoding `tile` directly must pass it along or it desyncs at the
1902 /// first eligible block.
1903 pub(crate) switchable_motion_mode: bool,
1904 /// The CDF state this frame's tile writer started from -- the defaults
1905 /// for a key frame and for the first inter frame, and the previous
1906 /// frame's stored tables after that. A test that decodes `tile` directly
1907 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1908 /// the frame's `primary_ref_frame` slot holds (same class as
1909 /// `tx_select`: a header bit a raw tile decode cannot guess).
1910 pub(crate) start_cdfs: CdfSnapshot,
1911 /// What this frame stores into the slots it refreshes (spec 7.20,
1912 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1913 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1914 /// started from when it is on.
1915 pub(crate) next_cdfs: CdfSnapshot,
1916 /// This frame header's chosen deblocking parameters
1917 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1918 /// picture the decoder produces UNDER them, so a test that decodes
1919 /// `tile` directly must pass these along, exactly as it must `tx_select`
1920 /// (class: test asserts against a stale header).
1921 pub(crate) loop_filter: LoopFilterParams,
1922 /// This frame header's chosen CDEF parameters, threaded for the same
1923 /// reason as `loop_filter`.
1924 pub(crate) cdef: CdefParams,
1925 /// This frame header's `allow_screen_content_tools`
1926 /// ([`screen_content`]) -- every intra block of the tile carries the two
1927 /// palette-mode symbols under it, so a raw tile decode that guessed
1928 /// `false` would desync at the first block (same class as `tx_select`).
1929 pub(crate) screen: bool,
1930 /// This frame header's own `reduced_tx_set` (spec 5.9.2) -- the bit that
1931 /// picks the inter `tx_type` alphabets AND, on an inter block, the
1932 /// allowance the chroma transform's inherited type reduces against
1933 /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). A raw tile
1934 /// decode that guesses `true` here mis-derives every inherited chroma
1935 /// type on a `reduced_tx_set = 0` frame (lane-intertx; same class as
1936 /// `tx_select`/`screen` above).
1937 pub(crate) reduced_tx_set: bool,
1938 /// This frame header's chosen loop restoration parameters, threaded for
1939 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1940 /// filters themselves are coded in `tile`, so a decode of it under a
1941 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1942 pub(crate) loop_restoration: LoopRestorationParams,
1943 /// This frame header's `allow_intrabc` -- every intra block of the tile
1944 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1945 /// guessed `false` would desync at the first block (same class as
1946 /// `screen`/`tx_select`).
1947 pub(crate) allow_intrabc: bool,
1948 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1949 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1950 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1951 /// decode that guessed the defaults desyncs at the first superblock
1952 /// (same class as `screen`/`tx_select`).
1953 pub(crate) delta: ec_av1_syntax::DeltaParams,
1954}
1955
1956thread_local! {
1957 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
1958 /// for on the last key frame encoded on this thread -- read by the gates,
1959 /// which print it beside the block counts (class `gate-blind-to-feature`).
1960 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
1961}
1962
1963/// [`IBC_SHARE`] for the last key frame encoded on this thread.
1964#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1965pub(crate) fn intrabc_source_share() -> f64 {
1966 IBC_SHARE.with(std::cell::Cell::get)
1967}
1968
1969thread_local! {
1970 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
1971 /// header offers the per-frame `allow_screen_content_tools` bit at all.
1972 /// Armed once by the key frame ([`encode_key_frame_inner`], from
1973 /// [`screen_content`]) and read by every header builder after it, so that
1974 /// the inter frames of a screen sequence lay their headers out the same
1975 /// way the sequence header the key frame wrote says they do -- a per-call
1976 /// parameter would have to thread through `inter_frame_headers`' four
1977 /// public entry points and every hand-built-stream test that calls them.
1978 /// A sequence with no screen content leaves this false and writes exactly
1979 /// the bits it wrote before this lane.
1980 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1981}
1982
1983thread_local! {
1984 /// Overrides [`screen_content`] for the calling thread, which is what the
1985 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
1986 /// codes every block losslessly, so both arms of a mode ablation reach
1987 /// infinite PSNR and the ablation measures nothing at all (the
1988 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
1989 /// variable cannot do this -- the tests run in one process, in parallel.
1990 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1991}
1992
1993thread_local! {
1994 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
1995 /// under, AFTER the content gate: the pyramid, or `None` for a stream
1996 /// that stayed flat. Read by the BD gates, which print the requested and
1997 /// the effective pyramid side by side -- a screen clip requests one and
1998 /// codes flat, and that difference is the gate (class
1999 /// `gate-blind-to-feature`).
2000 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
2001 const { std::cell::Cell::new(None) };
2002}
2003
2004/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
2005#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2006pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
2007 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
2008}
2009
2010#[cfg(test)]
2011pub(crate) fn force_screen(value: Option<bool>) {
2012 SCREEN_FORCE.with(|c| c.set(value));
2013}
2014
2015// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
2016// ablation can measure the mode search alone. Setting it also clears the
2017// sequence header's own `enable_filter_intra` bit, so the stream the arm
2018// writes is exactly the one this encoder wrote before the lane.
2019#[cfg(test)]
2020thread_local! {
2021 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2022}
2023
2024#[cfg(test)]
2025pub(crate) fn force_filter_intra(value: Option<bool>) {
2026 FILTER_INTRA_FORCE.with(|c| c.set(value));
2027}
2028
2029pub(crate) fn arm_seq_screen(on: bool) {
2030 SEQ_SCREEN.with(|c| c.set(on));
2031}
2032
2033fn seq_screen() -> bool {
2034 SEQ_SCREEN.with(std::cell::Cell::get)
2035}
2036
2037/// How many distinct colours a 16x16 luma block may hold and still count as
2038/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
2039/// `av1_set_screen_content_options` bound is 4, which separates nothing on
2040/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
2041/// the variance floor below on the five gate clips at BOTH the native crop
2042/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
2043/// the frame is the widest-margin split of those ten rows -- every
2044/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
2045/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
2046/// native and 17.9% scaled.
2047fn screen_colors() -> usize {
2048 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2049 *N.get_or_init(|| {
2050 std::env::var("EC_AV1_SCREEN_COLORS")
2051 .ok()
2052 .and_then(|v| v.parse().ok())
2053 .unwrap_or(16)
2054 })
2055}
2056
2057/// The reciprocal of the frame area those blocks must cover, in tenths --
2058/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
2059/// 8 (an eighth) is the midpoint of the two populations
2060/// `probe_screen_detect` measures at the colour bound and variance floor
2061/// around it. `EC_AV1_SCREEN_PCT`.
2062fn screen_pct() -> usize {
2063 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2064 *N.get_or_init(|| {
2065 std::env::var("EC_AV1_SCREEN_PCT")
2066 .ok()
2067 .and_then(|v| v.parse().ok())
2068 .unwrap_or(10)
2069 })
2070}
2071
2072/// The per-pixel variance a few-colour block must clear before it counts as
2073/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
2074/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
2075/// a smooth dark film frame is all few-colour blocks and reads as a desktop
2076/// capture -- which is exactly what this detector did until 2026-09-07, when
2077/// it called BOTH real films screen content on 48/48 frames, priced every
2078/// coefficient against the default CDFs and ran the palette search over
2079/// film. `probe_screen_detect`: at 16 colours the floor takes both films
2080/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
2081/// 23.6%.
2082fn screen_var() -> u64 {
2083 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
2084 *N.get_or_init(|| {
2085 std::env::var("EC_AV1_SCREEN_VAR")
2086 .ok()
2087 .and_then(|v| v.parse().ok())
2088 .unwrap_or(16)
2089 })
2090}
2091
2092/// How many frames [`screen_content`] said yes/no to, so a gate can print
2093/// whether the detector fired at all (class `gate-blind-to-feature`).
2094pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
2095 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2096
2097/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
2098/// the distinct colours of every 16x16 block and turn the screen-content
2099/// tools on when the blocks holding between 2 and [`screen_colors`] of them
2100/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
2101/// frame. `width` is the plane's
2102/// stride, `true_*` the frame's real (decodable) extent.
2103fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
2104 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
2105 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2106 return forced;
2107 }
2108 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
2109 let on = v != "0";
2110 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2111 return on;
2112 }
2113 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
2114 let mut counted = 0usize;
2115 for by in (0..true_height).step_by(blk) {
2116 for bx in (0..true_width).step_by(blk) {
2117 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
2118 let mut seen = [false; 256];
2119 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
2120 for row in 0..h {
2121 for col in 0..w {
2122 let v = y[(by + row) * width + bx + col];
2123 sum += u64::from(v);
2124 sq += u64::from(v) * u64::from(v);
2125 if !seen[usize::from(v)] {
2126 seen[usize::from(v)] = true;
2127 colors += 1;
2128 }
2129 }
2130 }
2131 // Per-pixel variance over the block's real (edge-clipped) extent.
2132 let n = (h * w) as u64;
2133 let var = (sq - sum * sum / n) / n;
2134 if colors > 1 && colors <= limit && var > floor {
2135 counted += 1;
2136 }
2137 }
2138 }
2139 let on = counted * blk * blk * screen_pct() > true_width * true_height;
2140 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2141 on
2142}
2143
2144/// Whether this SOURCE picture reads as screen content, for a caller that has
2145/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
2146/// gates its coding pyramid on this (a desktop capture keeps the flat
2147/// one-in-one-out structure the BD gate measured it on, camera material takes
2148/// the mini-GOP). The key frame runs the same detector again when it builds
2149/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
2150/// count, so this probe undoes its own tick and leaves the gate prints
2151/// reading one detection per coded frame.
2152pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
2153 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
2154 let on = screen_content(&y, picture.width, picture.width, picture.height);
2155 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2156 on
2157}
2158
2159/// The sequence and frame headers a picture of this size is coded under: one
2160/// tile, one transform size per block, no in-loop filter parameters yet
2161/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
2162/// CDEF strengths in once the tile is coded), no CDF adaptation
2163/// and no tool the tile writer does not code.
2164///
2165/// # Errors
2166/// Returns an error when the picture is larger than the 16-bit frame size the
2167/// sequence header carries.
2168pub fn key_frame_headers(
2169 width: usize,
2170 height: usize,
2171 base_q_idx: u8,
2172) -> Result<(SequenceHeader, FrameHeader)> {
2173 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
2174}
2175
2176/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
2177/// studio (limited) range: what this crate's sequence header carried before
2178/// [`crate::encoder`]'s facade could configure it, and what
2179/// [`key_frame_headers`] still asks for.
2180fn unspecified_color_config() -> ColorConfig {
2181 ColorConfig {
2182 bit_depth: 8,
2183 mono_chrome: false,
2184 num_planes: 3,
2185 color_primaries: 2,
2186 transfer_characteristics: 2,
2187 matrix_coefficients: 2,
2188 color_range: false,
2189 subsampling_x: 1,
2190 subsampling_y: 1,
2191 chroma_sample_position: ChromaSamplePosition::Unknown,
2192 separate_uv_delta_q: false,
2193 }
2194}
2195
2196/// [`key_frame_headers`] with the sequence header's colour config named
2197/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
2198/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
2199/// which is all a player picks a colour transform from and which
2200/// [`crate::encoder::Colour`] is the facade's own name for.
2201///
2202/// `color_config` also carries the chroma shape, and that is what a coverage
2203/// witness needs: nothing in this crate's ENCODER codes a shape other than
2204/// 4:2:0, but a sequence header can still be written at any
2205/// `subsampling_x`/`subsampling_y` the spec allows, which is how the 4:4:0
2206/// header witness is built. It builds HEADERS only -- pair the pair it
2207/// returns with a tile from [`encode_key_frame`] (4:2:0) or
2208/// [`encode_key_frame_at_size`].
2209///
2210/// # Errors
2211/// The same as [`key_frame_headers`].
2212pub fn key_frame_headers_colour(
2213 width: usize,
2214 height: usize,
2215 base_q_idx: u8,
2216 color_config: ColorConfig,
2217) -> Result<(SequenceHeader, FrameHeader)> {
2218 let bits = |n: usize| -> Result<u32> {
2219 let n = u32::try_from(n).map_err(|_| too_large())?;
2220 if n == 0 || n > 1 << 16 {
2221 return Err(too_large());
2222 }
2223 Ok((32 - (n - 1).leading_zeros()).max(1))
2224 };
2225 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
2226 let (w, h) = (width as u32, height as u32);
2227 let seq = SequenceHeader {
2228 seq_profile: 0,
2229 operating_points: vec![OperatingPoint {
2230 seq_level_idx: 8,
2231 ..OperatingPoint::default()
2232 }],
2233 frame_width_bits,
2234 frame_height_bits,
2235 max_frame_width: w,
2236 max_frame_height: h,
2237 use_128x128_superblock: sb128_on(),
2238 // lane-fintra: the encoder's intra search offers the five recursive
2239 // filter-intra modes on eligible blocks, so the sequence bit is set
2240 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
2241 // off and restores the streams this encoder wrote before the lane).
2242 enable_filter_intra: filter_intra_on(),
2243 enable_intra_edge_filter: false,
2244 enable_order_hint: true,
2245 order_hint_bits: 7,
2246 enable_superres: false,
2247 // spec 5.9.19: with the sequence bit set every frame header carries
2248 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
2249 // pair for the whole frame, chosen by `crate::filter_search` -- so no
2250 // `cdef_idx` literal is coded in the tile and a frame that wants no
2251 // CDEF simply carries zero strengths.
2252 enable_cdef: true,
2253 enable_restoration: true,
2254 // SELECT (2) when this sequence's key frame detected screen content
2255 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
2256 // is then coded in every frame header, and only the frames that want
2257 // the palette syntax set it. 0 -- the forced-off form, no bit at all
2258 // -- otherwise, which is what every non-screen stream this encoder
2259 // writes still carries.
2260 seq_force_screen_content_tools: if seq_screen() {
2261 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
2262 } else {
2263 0
2264 },
2265 seq_force_integer_mv: 0,
2266 color_config,
2267 still_picture: false,
2268 reduced_still_picture_header: false,
2269 timing_info: None,
2270 decoder_model_info: None,
2271 initial_display_delay_present_flag: false,
2272 operating_point: 0,
2273 operating_point_idc: 0,
2274 frame_id_numbers_present_flag: false,
2275 delta_frame_id_length: 0,
2276 additional_frame_id_length: 0,
2277 enable_interintra_compound: false,
2278 enable_masked_compound: false,
2279 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
2280 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
2281 // header is byte-identical to the streams before this lane.
2282 enable_warped_motion: warp_on(),
2283 enable_dual_filter: false,
2284 enable_jnt_comp: false,
2285 enable_ref_frame_mvs: false,
2286 film_grain_params_present: false,
2287 };
2288 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
2289 // own (true, unpadded) width and height, not from any block-grid
2290 // alignment — a decoder derives these straight from `frame_width`/
2291 // `frame_height` below, so this must match it exactly.
2292 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
2293 let header = FrameHeader {
2294 frame_type: FrameType::Key,
2295 frame_is_intra: true,
2296 show_frame: true,
2297 error_resilient_mode: true,
2298 // The tile writer keeps the same CDF state the decoder does and
2299 // updates it in the same order, so the frame lets the decoder adapt.
2300 disable_cdf_update: false,
2301 // Nothing reads the state this frame leaves behind: a key frame always
2302 // starts from the defaults, and this encoder emits one frame.
2303 disable_frame_end_update_cdf: true,
2304 force_integer_mv: true,
2305 refresh_frame_flags: 0xFF,
2306 primary_ref_frame: PRIMARY_REF_NONE,
2307 frame_width: w,
2308 frame_height: h,
2309 upscaled_width: w,
2310 render_width: w,
2311 render_height: h,
2312 mi_cols,
2313 mi_rows,
2314 tile_info: TileInfo {
2315 uniform_spacing: true,
2316 cols: 1,
2317 rows: 1,
2318 mi_col_starts: vec![0, mi_cols],
2319 mi_row_starts: vec![0, mi_rows],
2320 tile_size_bytes: 1,
2321 ..TileInfo::default()
2322 },
2323 quantization: QuantizationParams {
2324 base_q_idx,
2325 ..QuantizationParams::default()
2326 },
2327 tx_mode: TxMode::Largest,
2328 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
2329 // intra transform below 32x32, not only 16x16 -- the set this crate
2330 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
2331 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
2332 // so a decoder honouring the header picks the same CDF the writer
2333 // used only if this is set here too, not only on the inter variant
2334 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
2335 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
2336 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
2337 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
2338 // the arithmetic coder's `rng` register from the very first 8x8-leaf
2339 // luma transform onward with no symbol value ever differing.
2340 reduced_tx_set: true,
2341 ..FrameHeader::default()
2342 };
2343 Ok((seq, header))
2344}
2345
2346/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
2347/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
2348/// 1 still holds the key frame however long the GOP runs.
2349pub const GOLDEN_SLOT: u8 = 1;
2350
2351/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
2352/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
2353/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
2354/// one filter for the whole frame, which is what libaom does on this content
2355/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
2356/// stream, so a per-BLOCK filter search has no bits to win). The kernel
2357/// reaches the search, the trials and the recon through
2358/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
2359/// prediction the search priced are the same one.
2360/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the
2361/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
2362/// the witness that has to see a non-REGULAR kernel coded and decoded turns
2363/// it on through this while holding [`crate::speed::knob_write`].
2364static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
2365
2366/// Sets [`INTERP_OVERRIDE`]; `None` clears it.
2367#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
2368pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) {
2369 INTERP_OVERRIDE.store(
2370 filter.map_or(u8::MAX, |f| f as u8),
2371 std::sync::atomic::Ordering::Relaxed,
2372 );
2373}
2374
2375fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
2376 use ec_av1_syntax::InterpolationFilter as F;
2377 match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2378 0 => return F::Eighttap,
2379 1 => return F::EighttapSmooth,
2380 2 => return F::EighttapSharp,
2381 _ => {}
2382 }
2383 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2384 crate::envflags::var("EC_AV1_INTERP")
2385 .ok()
2386 .map(|v| match v.as_str() {
2387 "smooth" => F::EighttapSmooth,
2388 "sharp" => F::EighttapSharp,
2389 _ => F::Eighttap,
2390 })
2391 });
2392 ENV.unwrap_or(F::Eighttap)
2393}
2394
2395/// The frame header for a shown inter frame that predicts from the single
2396/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
2397/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
2398/// reused verbatim: an inter frame never changes the sequence.
2399///
2400/// # Errors
2401/// Returns an error under the same conditions as [`key_frame_headers`].
2402pub fn inter_frame_headers(
2403 width: usize,
2404 height: usize,
2405 base_q_idx: u8,
2406 order_hint: u32,
2407 last_slot: u8,
2408) -> Result<(SequenceHeader, FrameHeader)> {
2409 inter_frame_headers_slots(
2410 width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot,
2411 )
2412}
2413
2414/// [`inter_frame_headers`] with the three slots named apart: the one read as
2415/// `LAST_FRAME`, the one this frame refreshes, and the one read as
2416/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
2417/// so that the frame two back is still intact in the slot this one is about
2418/// to overwrite -- read before write, spec 7.20's decode order.
2419///
2420/// # Errors
2421/// As [`inter_frame_headers`].
2422pub fn inter_frame_headers_slots(
2423 width: usize,
2424 height: usize,
2425 base_q_idx: u8,
2426 order_hint: u32,
2427 last_slot: u8,
2428 self_slot: u8,
2429 altref_slot: u8,
2430) -> Result<(SequenceHeader, FrameHeader)> {
2431 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
2432 let header = FrameHeader {
2433 frame_type: FrameType::Inter,
2434 frame_is_intra: false,
2435 show_frame: true,
2436 error_resilient_mode: false,
2437 disable_cdf_update: false,
2438 // The tile writer hands its end-of-tile tables to the next frame
2439 // (`encode_sequence_with_ctx`), so the frame stores them the way the
2440 // decoder will load them (spec 7.20).
2441 disable_frame_end_update_cdf: false,
2442 force_integer_mv: false,
2443 order_hint,
2444 primary_ref_frame: 0,
2445 refresh_frame_flags: 1 << self_slot,
2446 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
2447 // names the slot this frame both predicts from and refreshes;
2448 // GOLDEN names slot 1, which the key frame wrote when it refreshed
2449 // all eight and which no inter frame ever overwrites, so it holds
2450 // the key frame's own picture for the whole GOP.
2451 ref_frame_idx: {
2452 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
2453 idx[3] = GOLDEN_SLOT;
2454 idx[6] = altref_slot;
2455 idx
2456 },
2457 // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`:
2458 // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's
2459 // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in
2460 // every frame this constructor builds, so no further guard is needed.
2461 allow_high_precision_mv: high_precision_mv_at(base_q_idx),
2462 // A FIXED frame-level filter, so no block codes an `interp_filter`
2463 // symbol. lane-obmc3 instrumented whether that costs anything: a
2464 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
2465 // (45941 B, the same point `lanes/libcen.report.md` matched) read
2466 // back through `EC_AV1_BITCENSUS=1 syntax_census` codes
2467 // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed
2468 // frame filter here too, so there are ZERO per-block filter bits at
2469 // stake on this content and the per-block switchable search was not
2470 // built (the charter's premise that libaom codes switchable interp
2471 // per block on film B is refuted by its own stream).
2472 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
2473 // lane-av1obmc: with this bit set every single-reference inter block
2474 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
2475 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
2476 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
2477 // to the OBMC knob rather than always on: with every block choosing
2478 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
2479 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
2480 // and stays byte-identical to the streams before this lane.
2481 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
2482 // `allow_warped_motion` besides -- which is what makes an eligible
2483 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
2484 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2485 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on(),
2486 allow_warped_motion: warp_on(),
2487 use_ref_frame_mvs: false,
2488 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
2489 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
2490 // set this crate carries a table for at 16x16 (see
2491 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
2492 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
2493 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
2494 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
2495 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
2496 // path) -- with this flag set, `get_tx_set`'s intra branch returns
2497 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
2498 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
2499 reduced_tx_set: true,
2500 ..key
2501 };
2502 Ok((seq, header))
2503}
2504
2505fn too_large() -> Error {
2506 Error::unsupported(
2507 "AV1 encode",
2508 "the picture is larger than a frame size can carry",
2509 )
2510}
2511
2512/// One plane of the picture being coded, and the reconstruction being built
2513/// beside it.
2514/// What one committed 4x4 cell left behind for the coefficient contexts of
2515/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
2516/// is the same state decode.rs records.
2517#[derive(Clone, Copy, Default, PartialEq, Eq)]
2518struct CoefCtx {
2519 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
2520 level: u8,
2521 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
2522 /// the DC itself was zero (tile.rs `dc_vote`).
2523 dc: i8,
2524}
2525
2526/// One plane's coefficient contexts, committed in CODING ORDER: the search
2527/// prices partition TREES, so the neighbour state a candidate reads has to be
2528/// whatever the blocks coded before it left -- the parent's committed
2529/// neighbours for a tree's first child, the just-committed sibling for the
2530/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
2531/// writer's two running bands is what makes that fall out: a trial commits
2532/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
2533/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
2534/// to its left is exactly what the tile writer's `Neighbours` bands will hold
2535/// when it gets there.
2536///
2537/// Before this map the pricer took both contexts as zero, which is exact for
2538/// a luma transform covering its whole block and the largest remaining row of
2539/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
2540#[derive(Default)]
2541struct CoefCtxMap {
2542 cells: Vec<CoefCtx>,
2543 stride: usize,
2544 /// Whether the transforms being priced right now are SMALLER than the
2545 /// block they sit in -- a `TxMode::Select` depth split
2546 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
2547 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
2548 /// trial cannot tell, and it is what decides whether luma reads context 0
2549 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
2550 tu_split: bool,
2551}
2552
2553/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
2554/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
2555/// padding-inclusive score the search used before lane-sse, which is how the
2556/// before/after arms of the straddling gate rows are read off ONE binary.
2557fn edge_sse() -> bool {
2558 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
2559 crate::envflags::var("EC_AV1_EDGESSE")
2560 .ok()
2561 .map(|v| v != "0")
2562 });
2563 ENV.unwrap_or(true)
2564}
2565
2566/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
2567/// through and the share of their raw squared error that sat in the padding
2568/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
2569/// it, but the numbers are an instrument, not a decision (class
2570/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
2571/// without this census no gate row can say the clip fires at all).
2572fn edge_census() -> bool {
2573 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
2574 crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1")
2575 });
2576 *ENV
2577}
2578
2579/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
2580/// 128x128): how many scores clipped, the inside squared error they kept and
2581/// the padding squared error they dropped.
2582static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
2583 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
2584
2585/// One clipped score, for [`take_edge_census`].
2586fn record_edge_score(side: usize, inside: u64, padding: u64) {
2587 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
2588 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2589 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
2590 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
2591}
2592
2593/// The straddling-block census since the last call, and zero it: one
2594/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
2595#[must_use]
2596pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
2597 EDGE_SCORES
2598 .iter()
2599 .enumerate()
2600 .filter_map(|(log2, row)| {
2601 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
2602 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
2603 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
2604 (n != 0).then_some((1usize << log2, n, inside, padding))
2605 })
2606 .collect()
2607}
2608
2609struct Plane<'a> {
2610 source: &'a [u8],
2611 reconstruction: Vec<u8>,
2612 width: usize,
2613 height: usize,
2614 /// The frame's true, decodable extent in this plane's own units --
2615 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
2616 /// not `width`/`height` above, which is the padded coding-surface size.
2617 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
2618 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
2619 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
2620 /// this bound, even though the padded reconstruction buffer holds real
2621 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
2622 /// those instead of stopping here is what desyncs prediction at the true
2623 /// edge.
2624 true_width: usize,
2625 true_height: usize,
2626 /// This plane's own tile's pixel bounds, in this plane's units -- the
2627 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
2628 /// prediction never reaches across a tile edge even though the
2629 /// neighbouring tile's real samples sit right there in the shared
2630 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
2631 /// leaves every edge exactly as it was before tiles existed.
2632 tile_x0: usize,
2633 tile_y0: usize,
2634 tile_x1: usize,
2635 tile_y1: usize,
2636 /// [`CoefCtxMap`]: what the blocks already committed left for the
2637 /// coefficient contexts of the ones still being priced. Sized on the
2638 /// first commit, so a plane literal does not have to know its own extent
2639 /// twice.
2640 ctx: CoefCtxMap,
2641}
2642
2643impl Plane<'_> {
2644 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
2645 /// called at every superblock of the frame-raster search with the rect
2646 /// of the tile that superblock belongs to.
2647 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
2648 self.tile_x0 = x0;
2649 self.tile_y0 = y0;
2650 self.tile_x1 = x1.min(self.width);
2651 self.tile_y1 = y1.min(self.height);
2652 }
2653 /// The reconstructed samples a block at `(x, y)` predicts from: the row
2654 /// above it, the column to its left and the sample between them, each
2655 /// missing where the block sits against an edge of the frame.
2656 ///
2657 /// `reach` says whether the samples above the block's right and below its
2658 /// left are decoded, which is what a directional mode reads into; where
2659 /// they are not, or where the frame ends first, the edge is shorter and
2660 /// the predictor repeats its last sample, exactly as the decoder's clamp
2661 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
2662 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
2663 /// a free per mode per block, on the search's hottest path -- while an
2664 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
2665 /// samples, on the caller's stack.
2666 fn edges_into<'a>(
2667 &self,
2668 x: usize,
2669 y: usize,
2670 side: usize,
2671 reach: Reach,
2672 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
2673 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
2674 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
2675 // Even a block's *own* edge is clamped to the true frame bound, not
2676 // just a `reach` extension: libaom's `av1_predict_intra_block`
2677 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
2678 // this block's own right/bottom to the frame edge -- from
2679 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
2680 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
2681 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
2682 // samples the row/column above/left holds before the decoder starts
2683 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
2684 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
2685 // extent straddles that edge legally (`has_half`) -- the transform
2686 // still covers the whole block, but prediction does not get to read
2687 // real reconstructed pixels past the true edge for its own row/column,
2688 // only for the padded tail it invents.
2689 let own_across = x + side.min(self.true_width.saturating_sub(x));
2690 let across = if reach.above_right {
2691 own_across + side.min(self.true_width.saturating_sub(own_across))
2692 } else {
2693 own_across
2694 }
2695 .min(self.width);
2696 let own_down = y + side.min(self.true_height.saturating_sub(y));
2697 let down = if reach.below_left {
2698 own_down + side.min(self.true_height.saturating_sub(own_down))
2699 } else {
2700 own_down
2701 }
2702 .min(self.height);
2703 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
2704 // whose own origin already sits past the true edge -- only reachable
2705 // through a partition trial priced for comparison on a split this
2706 // frame's straddling quadrant will go on to refuse (see
2707 // `a_picture_off_the_block_grid_is_refused`), never through a block
2708 // this encoder actually commits. Such a block has no true-edge
2709 // samples above or left of it at all, same as `y == 0`/`x == 0`.
2710 let across = across.min(self.tile_x1);
2711 let down = down.min(self.tile_y1);
2712 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
2713 if let Some(n) = above_n {
2714 above_buf[..n].copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
2715 }
2716 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
2717 if let Some(n) = left_n {
2718 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
2719 *d = self.reconstruction[row * self.width + x - 1];
2720 }
2721 }
2722 let corner = (x > self.tile_x0 && y > self.tile_y0)
2723 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
2724 (
2725 above_n.map(|n| &above_buf[..n]),
2726 left_n.map(|n| &left_buf[..n]),
2727 corner,
2728 )
2729 }
2730
2731 /// Codes one block under one mode without committing it: hands back the
2732 /// levels, the block the decoder would reconstruct, the squared error
2733 /// against the source and an estimate of what the levels cost in bits.
2734 fn trial(
2735 &self,
2736 at: At,
2737 mode: u8,
2738 angle_delta: i32,
2739 base_q_idx: u8,
2740 deadzone: f64,
2741 fctx: &crate::decode::FrameCtx,
2742 ) -> Trial {
2743 self.trial_typed(
2744 at,
2745 mode,
2746 angle_delta,
2747 base_q_idx,
2748 deadzone,
2749 TxType::DctDct,
2750 fctx,
2751 )
2752 }
2753
2754 /// [`Self::trial`] under a named transform type -- what an intra chroma
2755 /// block gets, since chroma codes no `tx_type` symbol and the decoder
2756 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
2757 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
2758 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
2759 #[allow(clippy::too_many_arguments)]
2760 /// Sum of absolute differences between the source block at `(x, y)` and a
2761 /// `side x side` prediction, as the whole number it is.
2762 ///
2763 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
2764 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
2765 /// exactly, so no add here rounds and the order of the adds cannot change
2766 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
2767 /// integer division per sample -- is what lets the row walk vectorize.
2768 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
2769 let mut sad = 0u32;
2770 for row in 0..side {
2771 let source = &self.source[(y + row) * self.width + x..][..side];
2772 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
2773 sad += u32::from(s.abs_diff(p));
2774 }
2775 }
2776 f64::from(sad)
2777 }
2778
2779 /// Squared error between the source block at `(x, y)` and a reconstruction
2780 /// of it, over the part of the block that is INSIDE the true frame.
2781 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
2782 /// `255^2 * 64 * 64`, under 2^28.
2783 ///
2784 /// A block the frame edge cuts through is still coded whole -- the
2785 /// decoder reconstructs its outside samples too and the display crop
2786 /// throws them away -- so scoring the padding would rank a mode, a
2787 /// transform or a partition tree by how well it codes samples the source
2788 /// does not have (libaom clips the same way: `av1_dist_block` measures
2789 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
2790 /// edge pixels, so predicting it is nearly free, but coding coefficients
2791 /// for it spends real bits. Both gate films are superblock-aligned; this
2792 /// only reaches arbitrary export sizes (lane-sse, generalising
2793 /// lane-b64b's 64-root-only rescore of the 64 root).
2794 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
2795 let inside_rows = side.min(self.true_height.saturating_sub(y));
2796 let inside_cols = side.min(self.true_width.saturating_sub(x));
2797 let straddles = inside_rows < side || inside_cols < side;
2798 // The knob is read only for a block the edge cuts, so the interior
2799 // path -- the hot one -- carries no extra load at all.
2800 let (rows, cols) = match straddles && !edge_sse() {
2801 true => (side, side),
2802 false => (inside_rows, inside_cols),
2803 };
2804 let mut sse = 0u64;
2805 for row in 0..rows {
2806 let source = &self.source[(y + row) * self.width + x..][..cols];
2807 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
2808 let d = u32::from(s.abs_diff(r));
2809 sse += u64::from(d * d);
2810 }
2811 }
2812 if straddles && edge_census() {
2813 let (mut inside, mut whole) = (0u64, 0u64);
2814 for row in 0..side {
2815 let source = &self.source[(y + row) * self.width + x..][..side];
2816 for (col, (&s, &r)) in source
2817 .iter()
2818 .zip(&reconstruction[row * side..][..side])
2819 .enumerate()
2820 {
2821 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
2822 whole += d;
2823 if row < inside_rows && col < inside_cols {
2824 inside += d;
2825 }
2826 }
2827 }
2828 record_edge_score(side, inside, whole - inside);
2829 }
2830 sse as f64
2831 }
2832
2833 fn trial_typed(
2834 &self,
2835 at: At,
2836 mode: u8,
2837 // This block's `angle_delta_y`/`angle_delta_uv` (spec
2838 // `read_intra_angle_info`, -3..=3), zero for every non-directional
2839 // mode -- the predictor's own `angle_delta` argument.
2840 angle_delta: i32,
2841 base_q_idx: u8,
2842 deadzone: f64,
2843 tx_type: TxType,
2844 fctx: &crate::decode::FrameCtx,
2845 ) -> Trial {
2846 let At {
2847 x, y, side, reach, ..
2848 } = at;
2849 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2850 let (above, left, corner) =
2851 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2852 // Per-candidate scratch on the search's hottest path, so both buffers
2853 // live on the stack -- `side` is at most `BLOCK` -- rather than
2854 // costing a malloc/free pair per trial (`mc_trial` already does this).
2855 let mut prediction = [0u8; BLOCK * BLOCK];
2856 let prediction = &mut prediction[..side * side];
2857 intra_predict_u8(
2858 mode,
2859 angle_delta,
2860 above,
2861 left,
2862 corner,
2863 side,
2864 side,
2865 false,
2866 false,
2867 prediction,
2868 fctx,
2869 );
2870
2871 let mut residual = [0i32; BLOCK * BLOCK];
2872 let residual = &mut residual[..side * side];
2873 for row in 0..side {
2874 for col in 0..side {
2875 residual[row * side + col] =
2876 i32::from(self.source[(y + row) * self.width + x + col])
2877 - i32::from(prediction[row * side + col]);
2878 }
2879 }
2880 #[cfg(test)]
2881 let t = stage_start();
2882 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
2883 // reconstruction below and the price further down are both of the
2884 // grid this trial would really code.
2885 let (levels, rdoq_bits) = if rdoq_on() {
2886 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2887 residual,
2888 side,
2889 8,
2890 i32::from(base_q_idx),
2891 deadzone,
2892 tx_type,
2893 );
2894 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2895 let bits = crate::tile::rdoq(
2896 &mut levels,
2897 &scaled,
2898 side,
2899 base_q_idx,
2900 at.set,
2901 skip_ctx,
2902 sign_ctx,
2903 rdoq_lambda(),
2904 tx_type,
2905 );
2906 (levels, Some(bits))
2907 } else {
2908 (
2909 forward_and_quantize_typed(
2910 residual,
2911 side,
2912 8,
2913 i32::from(base_q_idx),
2914 deadzone,
2915 tx_type,
2916 ),
2917 None,
2918 )
2919 };
2920 // lane-av1speed2: 60% of the transform units of an inter stream carry
2921 // no coefficient at all, and the square entry point re-inflates that
2922 // case into `side * side` zeros (one allocate-and-memset per trial)
2923 // only for the sum below to add them to the prediction. The `_wh`
2924 // entry hands back the empty all-zero marker instead, and a zero
2925 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
2926 // `p` for a `u8`, so the bytes are the same.
2927 let coded = dequant_and_inverse_typed_wh(
2928 &levels,
2929 side,
2930 side,
2931 8,
2932 i32::from(base_q_idx),
2933 0,
2934 0,
2935 tx_type,
2936 None,
2937 );
2938 #[cfg(test)]
2939 stage_since(2, t);
2940
2941 let reconstruction: Vec<u8> = if coded.is_empty() {
2942 prediction.to_vec()
2943 } else {
2944 prediction
2945 .iter()
2946 .zip(&coded)
2947 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2948 .collect()
2949 };
2950 let sse = self.block_sse(x, y, side, &reconstruction);
2951 // What the levels cost is priced through the same CDFs the tile writer
2952 // will code them with, so the search ranks modes -- and the partition
2953 // trial ranks trees -- by the bits they actually spend.
2954 #[cfg(test)]
2955 let t = stage_start();
2956 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2957 // What the search used before it could price a block exactly: a
2958 // level costs its magnitude's width plus a sign and a run. Kept
2959 // reachable from the sweep so the two rate terms can be compared
2960 // on one build.
2961 levels
2962 .iter()
2963 .filter(|&&level| level != 0)
2964 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2965 .sum()
2966 } else if let Some(bits) = rdoq_bits {
2967 // Already priced, against the grid the pass settled on.
2968 bits
2969 } else {
2970 {
2971 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2972 crate::tile::coeff_bits_typed(
2973 &levels,
2974 at.set,
2975 crate::decode::q_ctx_of(base_q_idx),
2976 skip_ctx,
2977 sign_ctx,
2978 tx_type,
2979 )
2980 }
2981 };
2982 #[cfg(test)]
2983 stage_since(3, t);
2984 Trial {
2985 levels,
2986 reconstruction,
2987 sse,
2988 bits,
2989 }
2990 }
2991
2992 /// [`Self::trial`] with the prediction already built, so that an inter
2993 /// block's motion-compensated prediction can go through the same
2994 /// residual/quantize/reconstruct path an intra block's does. `skip`
2995 /// takes the prediction as the reconstruction outright, coding no
2996 /// residual at all — what a `NEARESTMV` block that names no coefficients
2997 /// codes.
2998 #[allow(clippy::too_many_arguments)]
2999 fn code_from_prediction(
3000 &self,
3001 x: usize,
3002 y: usize,
3003 side: usize,
3004 prediction: &[u8],
3005 skip: bool,
3006 base_q_idx: u8,
3007 deadzone: f64,
3008 set: TxbSet,
3009 ) -> Trial {
3010 self.code_from_prediction_typed(
3011 x,
3012 y,
3013 side,
3014 prediction,
3015 skip,
3016 base_q_idx,
3017 deadzone,
3018 set,
3019 TxType::DctDct,
3020 )
3021 }
3022
3023 /// [`Self::code_from_prediction`] coding the residual with a NAMED
3024 /// transform type (lane-txset2): the inter luma sets carry a two-type
3025 /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
3026 /// a symbol for, and [`commit_inter_luma`] prices both through this.
3027 #[allow(clippy::too_many_arguments)]
3028 fn code_from_prediction_typed(
3029 &self,
3030 x: usize,
3031 y: usize,
3032 side: usize,
3033 prediction: &[u8],
3034 skip: bool,
3035 base_q_idx: u8,
3036 deadzone: f64,
3037 set: TxbSet,
3038 tx_type: TxType,
3039 ) -> Trial {
3040 if skip {
3041 let sse = self.block_sse(x, y, side, prediction);
3042 return Trial {
3043 levels: vec![0i32; side * side],
3044 reconstruction: prediction.to_vec(),
3045 sse,
3046 bits: 0.0,
3047 };
3048 }
3049 // A 64x64 root's residual is four times the scratch every other
3050 // block coder here sizes for [`BLOCK`]; only that one case pays for
3051 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
3052 let mut small = [0i32; BLOCK * BLOCK];
3053 let mut big = if side > BLOCK {
3054 vec![0i32; side * side]
3055 } else {
3056 Vec::new()
3057 };
3058 let residual: &mut [i32] = if side > BLOCK {
3059 &mut big
3060 } else {
3061 &mut small[..side * side]
3062 };
3063 for row in 0..side {
3064 for col in 0..side {
3065 residual[row * side + col] =
3066 i32::from(self.source[(y + row) * self.width + x + col])
3067 - i32::from(prediction[row * side + col]);
3068 }
3069 }
3070 #[cfg(test)]
3071 let t = stage_start();
3072 // lane-rdoq, as in [`Self::trial_typed`].
3073 let (levels, rdoq_bits) = if rdoq_on() {
3074 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
3075 residual,
3076 side,
3077 8,
3078 i32::from(base_q_idx),
3079 deadzone,
3080 tx_type,
3081 );
3082 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3083 let bits = crate::tile::rdoq(
3084 &mut levels,
3085 &scaled,
3086 side,
3087 base_q_idx,
3088 set,
3089 skip_ctx,
3090 sign_ctx,
3091 rdoq_lambda(),
3092 tx_type,
3093 );
3094 (levels, Some(bits))
3095 } else {
3096 (
3097 forward_and_quantize_typed(
3098 residual,
3099 side,
3100 8,
3101 i32::from(base_q_idx),
3102 deadzone,
3103 tx_type,
3104 ),
3105 None,
3106 )
3107 };
3108 // The same all-zero shortcut [`Self::trial_typed`] takes.
3109 let coded = dequant_and_inverse_typed_wh(
3110 &levels,
3111 side,
3112 side,
3113 8,
3114 i32::from(base_q_idx),
3115 0,
3116 0,
3117 tx_type,
3118 None,
3119 );
3120 #[cfg(test)]
3121 stage_since(2, t);
3122 let reconstruction: Vec<u8> = if coded.is_empty() {
3123 prediction.to_vec()
3124 } else {
3125 prediction
3126 .iter()
3127 .zip(&coded)
3128 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
3129 .collect()
3130 };
3131 let sse = self.block_sse(x, y, side, &reconstruction);
3132 // A 64-point transform codes only its top-left 32x32 corner (spec
3133 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
3134 // key frame writer takes a 32x32 level grid for one). The inverse
3135 // above reads the whole 64x64 array, but the price below and the
3136 // levels the writer takes are that corner.
3137 let levels = if side > BLOCK {
3138 coded_corner(&levels, side, BLOCK)
3139 } else {
3140 levels
3141 };
3142 #[cfg(test)]
3143 let t = stage_start();
3144 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
3145 levels
3146 .iter()
3147 .filter(|&&level| level != 0)
3148 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
3149 .sum()
3150 } else if let Some(bits) = rdoq_bits {
3151 bits
3152 } else {
3153 {
3154 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3155 crate::tile::coeff_bits_typed(
3156 &levels,
3157 set,
3158 crate::decode::q_ctx_of(base_q_idx),
3159 skip_ctx,
3160 sign_ctx,
3161 tx_type,
3162 )
3163 }
3164 };
3165 #[cfg(test)]
3166 stage_since(3, t);
3167 Trial {
3168 levels,
3169 reconstruction,
3170 sse,
3171 bits,
3172 }
3173 }
3174
3175 /// Codes this block's luma at transform depth `depth`: the
3176 /// `(side >> depth)^2` transform units in raster order, each predicted
3177 /// from the reconstruction the units before it left behind -- exactly
3178 /// what the decoder's multi-transform-unit branch does (decode.rs
3179 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
3180 /// reconstructed on its own. Commits the result and hands back the
3181 /// block-coordinate levels, the block's squared error and what its
3182 /// coefficients cost.
3183 #[allow(clippy::too_many_arguments)]
3184 fn code_tx_depth(
3185 &mut self,
3186 at: At,
3187 mode: u8,
3188 angle_delta: i32,
3189 depth: usize,
3190 // This block's `filter_intra_mode` when it is coded with one, in
3191 // which case every transform unit predicts recursively off the
3192 // reconstruction the units before it left -- what the decoder does
3193 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
3194 // `filter_intra`), not once over the whole block.
3195 filter_intra: Option<u8>,
3196 search: &Search,
3197 fctx: &crate::decode::FrameCtx,
3198 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
3199 let At {
3200 x, y, side, reach, ..
3201 } = at;
3202 let tx = side >> depth;
3203 let n = 1usize << depth;
3204 let set = luma_set_for(
3205 match tx {
3206 32 => TxbSet::Luma32,
3207 16 => TxbSet::Luma16,
3208 8 => TxbSet::Luma8,
3209 _ => TxbSet::Luma4,
3210 },
3211 search.screen,
3212 );
3213 let mut levels = vec![0i32; side * side];
3214 census_add(4, n * n);
3215 // A unit smaller than its block reads the neighbour magnitude table
3216 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
3217 self.ctx.tu_split = n > 1;
3218 let (mut sse, mut bits) = (0.0, 0.0);
3219 // One entry per unit at its own `tu_row * n + tu_col`, which is how
3220 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
3221 // frame edge cuts away is never coded there, so a compacted list
3222 // would slide every later unit's type onto the wrong transform.
3223 let mut tx_types = vec![TxType::DctDct; n * n];
3224 for tu_row in 0..n {
3225 for tu_col in 0..n {
3226 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3227 let tu = At {
3228 x: x + col_off,
3229 y: y + row_off,
3230 side: tx,
3231 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
3232 set,
3233 };
3234 let trial = match filter_intra {
3235 Some(fi) => {
3236 let (mut above_buf, mut left_buf) =
3237 ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3238 let (above, left, corner) = self.edges_into(
3239 tu.x,
3240 tu.y,
3241 tx,
3242 tu.reach,
3243 &mut above_buf,
3244 &mut left_buf,
3245 );
3246 let mut prediction = vec![0u8; tx * tx];
3247 filter_intra_predict_u8(
3248 usize::from(fi),
3249 above,
3250 left,
3251 corner,
3252 tx,
3253 &mut prediction,
3254 fctx,
3255 );
3256 self.code_from_prediction(
3257 tu.x,
3258 tu.y,
3259 tx,
3260 &prediction,
3261 false,
3262 search.base_q_idx,
3263 search.deadzone,
3264 set,
3265 )
3266 }
3267 None => {
3268 // lane-txset: the unit picks its own transform type
3269 // out of the set the writer can name it in, priced
3270 // through the same RDOQ'd trial path (its `bits`
3271 // already carry the `tx_type` symbol itself).
3272 let mut best: Option<(f64, TxType, Trial)> = None;
3273 for &tx_type in tx_type_candidates(set, search.screen) {
3274 let candidate = self.trial_typed(
3275 tu,
3276 mode,
3277 angle_delta,
3278 search.base_q_idx,
3279 search.deadzone,
3280 tx_type,
3281 fctx,
3282 );
3283 // lane-txi: a non-`DCT_DCT` type is charged its
3284 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
3285 // search's weight (default 1 = unchanged). The
3286 // film rows buy 0.04 dB for 1.2% more bytes at
3287 // weight 1 on every frame and every PLANE, key
3288 // frame included -- a rate term this decision
3289 // under-charges (class
3290 // `rd-rate-term-calibration`), not the
3291 // propagation loss the leaves would have shown.
3292 let cost = candidate.sse
3293 + search.lambda * candidate.bits
3294 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
3295 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
3296 best = Some((cost, tx_type, candidate));
3297 }
3298 }
3299 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
3300 tx_types[tu_row * n + tu_col] = tx_type;
3301 TX_TYPE_HITS[tx_type as usize]
3302 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3303 trial
3304 }
3305 };
3306 sse += trial.sse;
3307 bits += trial.bits;
3308 self.commit(tu.x, tu.y, tx, &trial);
3309 for row in 0..tx {
3310 levels[(row_off + row) * side + col_off..][..tx]
3311 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3312 }
3313 }
3314 }
3315 self.ctx.tu_split = false;
3316 (levels, sse, bits, tx_types)
3317 }
3318
3319 /// Writes a trial's reconstruction back into the plane, and the
3320 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
3321 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
3322 for row in 0..side {
3323 self.reconstruction[(y + row) * self.width + x..][..side]
3324 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
3325 }
3326 self.commit_ctx(x, y, side, &trial.levels);
3327 }
3328
3329 /// Publishes one committed transform's own context over every 4x4 cell it
3330 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
3331 /// which is what the writer will read when it reaches the next block.
3332 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
3333 if self.ctx.cells.is_empty() {
3334 self.ctx.stride = self.width.div_ceil(4);
3335 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
3336 }
3337 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
3338 let state = CoefCtx {
3339 level: cul,
3340 dc: match levels[0].signum() {
3341 0 => 0,
3342 -1 => -1,
3343 _ => 1,
3344 },
3345 };
3346 let n = (side / 4).max(1);
3347 // Only up to the frame's TRUE extent: the writer's own
3348 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
3349 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
3350 // and leaves the cells past it uncoded even mid-block, so a
3351 // straddling block publishes context for its inside part only.
3352 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
3353 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
3354 for row in 0..rows {
3355 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3356 let end = (start + cols).min(self.ctx.cells.len());
3357 if start < end {
3358 self.ctx.cells[start..end].fill(state);
3359 }
3360 }
3361 }
3362
3363 /// A block committed without any residual at all ([`ibc_commit`]): the
3364 /// cells it covers coded nothing, and leaving an earlier trial's state
3365 /// there would price its neighbours off a block that was never coded.
3366 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
3367 self.commit_ctx(x, y, side, &[0i32]);
3368 }
3369
3370 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
3371 /// plane reads, off what the blocks before it in coding order committed
3372 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
3373 /// the above/left neighbours coded anything (tile.rs
3374 /// `write_block_planes`), luma reads context 0 when its transform covers
3375 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
3376 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
3377 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
3378 /// the same neighbours (tile.rs `dc_sign_ctx`).
3379 ///
3380 /// A neighbour outside this plane's own TILE does not exist, exactly as
3381 /// the writer's per-tile `Neighbours` bands start blank.
3382 ///
3383 /// CLOSED (lane-av1straddle): the decisions this price changes used to
3384 /// make `decode_stream_round_trips_an_odd_size_gop` and
3385 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
3386 /// fail at 216x96. Never this map: the writer coded the phantom
3387 /// transform units of a right-edge-straddling 32x32 (tile.rs
3388 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
3389 /// like decode.rs and libaom), which libdav1d and libaom both refused
3390 /// outright while a decision change was what first walked into it.
3391 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
3392 if self.ctx.cells.is_empty() {
3393 return (0, 0);
3394 }
3395 let n = (side / 4).max(1);
3396 let (cx, cy) = (x / 4, y / 4);
3397 let (mut top, mut left) = (0u8, 0u8);
3398 let mut vote = 0i32;
3399 if y > self.tile_y0 && cy > 0 {
3400 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
3401 top |= cell.level;
3402 vote += i32::from(cell.dc);
3403 }
3404 }
3405 if x > self.tile_x0 && cx > 0 {
3406 for row in 0..n {
3407 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
3408 left |= cell.level;
3409 vote += i32::from(cell.dc);
3410 }
3411 }
3412 let skip_ctx = if set.is_chroma() {
3413 usize::from(top != 0) + usize::from(left != 0)
3414 } else if self.ctx.tu_split {
3415 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3416 } else {
3417 0
3418 };
3419 let sign_ctx = match vote.signum() {
3420 0 => 0,
3421 -1 => 1,
3422 _ => 2,
3423 };
3424 (skip_ctx, sign_ctx)
3425 }
3426
3427 /// The source samples of one square, contiguous — what a motion search
3428 /// compares its candidates' predictions against ([`motion::search`]'s
3429 /// `source`), since [`Self::source`] itself is the whole plane, strided
3430 /// by [`Self::width`].
3431 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
3432 rows_of(self.source, self.width, x, y, side)
3433 }
3434
3435 /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
3436 /// root's own HORZ/VERT motion search.
3437 fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
3438 let mut out = vec![0u8; w * h];
3439 for row in 0..h {
3440 out[row * w..][..w].copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3441 }
3442 out
3443 }
3444
3445 /// The reconstructed samples of one square, so that a partition trial can
3446 /// be undone.
3447 /// The reconstructed samples of one square AND the coefficient contexts
3448 /// its cells hold, so that a partition trial can be undone whole: a
3449 /// losing trial that left its own nz/DC state behind would price the
3450 /// blocks after it off a block the tile writer never codes.
3451 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
3452 (
3453 rows_of(&self.reconstruction, self.width, x, y, side),
3454 self.ctx_rows(x, y, side),
3455 )
3456 }
3457
3458 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
3459 if self.ctx.cells.is_empty() {
3460 return Vec::new();
3461 }
3462 let n = (side / 4).max(1);
3463 (0..n)
3464 .flat_map(|row| {
3465 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3466 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
3467 })
3468 .collect()
3469 }
3470
3471 /// Puts a snapshot back.
3472 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
3473 for row in 0..side {
3474 self.reconstruction[(y + row) * self.width + x..][..side]
3475 .copy_from_slice(&saved.0[row * side..][..side]);
3476 }
3477 if saved.1.is_empty() {
3478 return;
3479 }
3480 let n = (side / 4).max(1);
3481 for row in 0..n {
3482 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3483 let end = (start + n).min(self.ctx.cells.len());
3484 if start < end {
3485 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
3486 }
3487 }
3488 }
3489
3490 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
3491 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
3492 /// prescreen by the identical rule rather than a second one that could
3493 /// drift from it.
3494 fn intra_scores(
3495 &self,
3496 at: At,
3497 modes: &[u8],
3498 mode_bits: &[f64; 13],
3499 lambda: f64,
3500 fctx: &crate::decode::FrameCtx,
3501 ) -> Vec<(f64, u8)> {
3502 let At {
3503 x, y, side, reach, ..
3504 } = at;
3505 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3506 let (above, left, corner) =
3507 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3508 modes
3509 .iter()
3510 .map(|&mode| {
3511 let mut prediction = vec![0u8; side * side];
3512 intra_predict_u8(
3513 mode,
3514 0,
3515 above,
3516 left,
3517 corner,
3518 side,
3519 side,
3520 false,
3521 false,
3522 &mut prediction,
3523 fctx,
3524 );
3525 let sad = self.block_sad(x, y, side, &prediction);
3526 (sad + lambda * mode_bits[usize::from(mode)], mode)
3527 })
3528 .collect()
3529 }
3530
3531 /// Codes one block under every mode the search offers (or, when
3532 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
3533 /// pre-pass plus DC) and commits the one whose squared error and
3534 /// estimated rate come out cheapest.
3535 ///
3536 /// The prediction is built once per mode regardless -- the full RD trial
3537 /// needs it too -- so ranking modes by SAD on that same prediction before
3538 /// running the expensive part (forward transform, quantize, reconstruct,
3539 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
3540 /// only to sum.
3541 fn search_block(
3542 &mut self,
3543 at: At,
3544 search: &Search,
3545 mode_bits: &[f64; 13],
3546 fctx: &crate::decode::FrameCtx,
3547 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
3548 let At {
3549 x, y, side, reach, ..
3550 } = at;
3551 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3552 let (above, left, corner) =
3553 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3554 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
3555 // the census reports it), so summing it under the default unpruned
3556 // search is `side * side` absolute differences per mode spent on a
3557 // number no one reads.
3558 let want_sad = search.top_k.is_some() || census_on();
3559 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
3560 .modes
3561 .iter()
3562 .map(|&mode| {
3563 let mut prediction = vec![0u8; side * side];
3564 intra_predict_u8(
3565 mode,
3566 0,
3567 above,
3568 left,
3569 corner,
3570 side,
3571 side,
3572 false,
3573 false,
3574 &mut prediction,
3575 fctx,
3576 );
3577 let sad = if want_sad {
3578 self.block_sad(x, y, side, &prediction)
3579 } else {
3580 0.0
3581 };
3582 (
3583 sad + search.lambda * mode_bits[usize::from(mode)],
3584 mode,
3585 prediction,
3586 )
3587 })
3588 .collect();
3589 if let Some(k) = search.top_k {
3590 if k < scored.len() {
3591 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
3592 let dc_entry = dc_pos.map(|i| scored.remove(i));
3593 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3594 scored.truncate(if dc_entry.is_some() {
3595 k.saturating_sub(1)
3596 } else {
3597 k
3598 });
3599 if let Some(dc_entry) = dc_entry {
3600 scored.push(dc_entry);
3601 }
3602 }
3603 }
3604 let ranking: Vec<(f64, u8)> = if census_on() {
3605 scored
3606 .iter()
3607 .map(|&(score, mode, _)| (score, mode))
3608 .collect()
3609 } else {
3610 Vec::new()
3611 };
3612 census_add(0, 1);
3613 census_add(1, scored.len());
3614 let mut best: Option<(f64, u8, Trial)> = None;
3615 for (_, mode, prediction) in scored {
3616 let trial = self.code_from_prediction(
3617 x,
3618 y,
3619 side,
3620 &prediction,
3621 false,
3622 search.base_q_idx,
3623 search.deadzone,
3624 at.set,
3625 );
3626 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
3627 if best
3628 .as_ref()
3629 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
3630 {
3631 best = Some((cost, mode, trial));
3632 }
3633 }
3634 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
3635 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
3636 // directional modes each carry a -3..=3 delta, three degrees a step,
3637 // which the writer has always coded as ZERO because nothing searched
3638 // it. Refined on the winning mode only -- libaom's own ordering, and
3639 // six extra trials on the directional blocks instead of on every
3640 // block times every mode. The edges are the ones the base angle
3641 // already read (`enable_intra_edge_filter` is off in this encoder's
3642 // sequence header, so no delta changes which samples exist), and the
3643 // predictor is the decoder's, `angle_delta` argument and all.
3644 let mut angle_delta = 0i32;
3645 // Not on a screen frame: measured on the 5-row native gate, the
3646 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
3647 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
3648 // synthetic edges land on the base angles, so every delta there buys
3649 // a symbol and no prediction. Same `search.screen` gate palette and
3650 // intrabc already stand behind.
3651 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
3652 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
3653 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
3654 let mut prediction = vec![0u8; side * side];
3655 for delta in [-3i32, -2, -1, 1, 2, 3] {
3656 intra_predict_u8(
3657 mode,
3658 delta,
3659 above,
3660 left,
3661 corner,
3662 side,
3663 side,
3664 false,
3665 false,
3666 &mut prediction,
3667 fctx,
3668 );
3669 let candidate = self.code_from_prediction(
3670 x,
3671 y,
3672 side,
3673 &prediction,
3674 false,
3675 search.base_q_idx,
3676 search.deadzone,
3677 at.set,
3678 );
3679 let bits =
3680 symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3681 - zero_bits;
3682 let cost_d = candidate.sse
3683 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
3684 if cost_d < cost {
3685 cost = cost_d;
3686 angle_delta = delta;
3687 trial = candidate;
3688 }
3689 }
3690 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
3691 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3692 }
3693 // lane-txset: the block's own transform type, searched on the mode
3694 // and angle the trials above settled -- the same ordering the angle
3695 // refinement uses, and the same RD terms.
3696 let mut tx_type = TxType::DctDct;
3697 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
3698 let candidate = self.trial_typed(
3699 at,
3700 mode,
3701 angle_delta,
3702 search.base_q_idx,
3703 search.deadzone,
3704 candidate_type,
3705 fctx,
3706 );
3707 let cost_t =
3708 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3709 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3710 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3711 // block's true one for the caller's own decision.
3712 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3713 cost = cost_t;
3714 tx_type = candidate_type;
3715 trial = candidate;
3716 }
3717 }
3718 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3719 if census_on() {
3720 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
3721 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3722 }
3723 self.commit(x, y, side, &trial);
3724 // A 64-point transform codes only its top-left 32x32 corner, which is
3725 // the grid `code_from_prediction` hands back (lane-i64).
3726 (
3727 coeffs(&trial.levels, side.min(BLOCK)),
3728 mode,
3729 angle_delta,
3730 cost,
3731 tx_type,
3732 )
3733 }
3734}
3735
3736/// Where one block sits in its plane, and how far past its own edges its
3737/// prediction may read.
3738#[derive(Clone, Copy)]
3739struct At {
3740 x: usize,
3741 y: usize,
3742 side: usize,
3743 reach: Reach,
3744 /// Which of the tile writer's coefficient tables this block's levels are
3745 /// coded with, and so which the search prices them through.
3746 set: TxbSet,
3747}
3748
3749/// Which of the samples past a block's own edges the decoder has decoded by
3750/// the time it predicts the block, and so which a directional mode may read.
3751///
3752/// The decoder derives these from its `BlockDecoded` flags, which are cleared
3753/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
3754/// that map, this reads the answer the same way libaom and rav1e do: for a
3755/// block whose transform covers it whole, whether the samples above its right
3756/// (or below its left) are decoded depends only on where the block sits inside
3757/// its 64x64 superblock, which is a pinned table per block size.
3758#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3759pub(crate) struct Reach {
3760 pub(crate) above_right: bool,
3761 pub(crate) below_left: bool,
3762}
3763
3764/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
3765/// libaom): for a block that is neither in the superblock's top row nor its
3766/// rightmost column, whether the block above and to its right is coded before
3767/// it. Indexed by the block's position in the superblock, in blocks of its own
3768/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
3769/// 128, not this crate's 64 superblock -- bit by bit from the low end.
3770const HAS_TOP_RIGHT: [&[u8]; 4] = [
3771 &[255, 85, 119, 85, 127, 85, 119, 85],
3772 &[95, 87],
3773 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
3774 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
3775 &[
3776 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
3777 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
3778 ],
3779 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
3780 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
3781 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
3782 // with side 4 outside a TX4 split; without their own row they clamped
3783 // into the 8x8 table and read above-right samples the decoder has not
3784 // written yet (all-zero pixels in the bottom-right triangle of a
3785 // directional 4x4 leaf).
3786 &[
3787 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
3788 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
3789 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
3790 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
3791 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
3792 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
3793 119, 119, 119, 119, 85, 85, 85, 85,
3794 ],
3795];
3796
3797/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
3798/// left.
3799const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
3800 &[84, 16, 84, 0, 84, 16, 84, 0],
3801 &[4, 4],
3802 // has_bl_8x8 (libaom av1/common/reconintra.c)
3803 &[
3804 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
3805 84, 85, 16, 17, 84, 85, 0, 0,
3806 ],
3807 // has_bl_4x4 (same source, same order).
3808 &[
3809 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
3810 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,
3811 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
3812 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,
3813 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
3814 85, 85, 0, 0, 0, 0,
3815 ],
3816];
3817
3818/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
3819/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
3820/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
3821/// rather than in raster order, so the bottom-left square's top-right
3822/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
3823/// libaom switches tables on the partition type (`get_has_tr_table`); the
3824/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
3825/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
3826/// lane-part32 r5 caught reading undecoded samples.
3827const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
3828 // has_tr_vert_16x16
3829 &[255, 0, 119, 0, 127, 0, 119, 0],
3830 // has_tr_vert_32x32
3831 &[15, 7],
3832 // has_tr_vert_8x8
3833 &[
3834 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
3835 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
3836 ],
3837];
3838
3839/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
3840const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
3841 // has_bl_vert_16x16
3842 &[254, 16, 254, 0, 254, 16, 254, 0],
3843 // has_bl_vert_32x32
3844 &[14, 14],
3845 // has_bl_vert_8x8
3846 &[
3847 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
3848 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
3849 ],
3850];
3851
3852thread_local! {
3853 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
3854 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
3855 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
3856 /// threading one bool through this crate's already twenty-argument
3857 /// `decode_block` would touch every call site instead of the two arms
3858 /// that need it.
3859 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3860}
3861
3862/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
3863pub(crate) struct VertAbGuard(bool);
3864
3865impl Drop for VertAbGuard {
3866 fn drop(&mut self) {
3867 VERT_AB_PARTITION.with(|c| c.set(self.0));
3868 }
3869}
3870
3871/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
3872/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
3873/// so no byte is retyped). Each is indexed by
3874/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
3875/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
3876/// superblock grid; on this crate's 64-pixel superblock the highest index a
3877/// shape can reach stays inside its own table, so no wrap is involved.
3878///
3879/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
3880/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
3881/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
3882/// 10 of the 21 reachable superblock positions for above-right and 7 for
3883/// below-left.
3884/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3885const HAS_TR_4X8: [u8; 64] = [
3886 255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255,
3887 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119,
3888 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127,
3889 127, 127, 127, 119, 119, 119, 119,
3890];
3891/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3892const HAS_BL_4X8: [u8; 64] = [
3893 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,
3894 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,
3895 1, 1, 16, 17, 17, 17, 0, 0, 0, 0,
3896];
3897/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3898const HAS_TR_8X4: [u8; 64] = [
3899 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,
3900 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,
3901 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0,
3902];
3903/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3904const HAS_BL_8X4: [u8; 64] = [
3905 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254,
3906 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255,
3907 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0,
3908];
3909/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3910const HAS_TR_8X16: [u8; 16] = [
3911 255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119,
3912];
3913/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3914const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
3915/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3916const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
3917/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3918const HAS_BL_16X8: [u8; 16] = [
3919 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0,
3920];
3921/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3922const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
3923/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3924const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
3925/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3926const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
3927/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3928const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
3929/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3930const HAS_TR_32X64: [u8; 1] = [127];
3931/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3932const HAS_BL_32X64: [u8; 1] = [0];
3933/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3934const HAS_TR_64X32: [u8; 1] = [19];
3935/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3936const HAS_BL_64X32: [u8; 1] = [34];
3937/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3938const HAS_TR_4X16: [u8; 32] = [
3939 255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255,
3940 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127,
3941];
3942/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3943const HAS_BL_4X16: [u8; 32] = [
3944 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,
3945];
3946/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3947const HAS_TR_16X4: [u8; 32] = [
3948 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,
3949 85, 0, 0, 0,
3950];
3951/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3952const HAS_BL_16X4: [u8; 32] = [
3953 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84,
3954 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0,
3955];
3956/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3957const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
3958/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3959const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
3960/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3961const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
3962/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3963const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
3964/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3965const HAS_TR_16X64: [u8; 2] = [255, 127];
3966/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3967const HAS_BL_16X64: [u8; 2] = [0, 0];
3968/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3969const HAS_TR_64X16: [u8; 2] = [3, 1];
3970/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3971const HAS_BL_64X16: [u8; 2] = [42, 42];
3972
3973/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
3974fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
3975 match (bw, bh) {
3976 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
3977 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
3978 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
3979 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
3980 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
3981 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
3982 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
3983 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
3984 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
3985 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
3986 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
3987 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
3988 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
3989 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
3990 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
3991 }
3992}
3993
3994impl Reach {
3995 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3996 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
3997 /// own answer is `block` -- a different rule from the standalone-block
3998 /// tables, because a unit's neighbours are mostly its own block's
3999 /// already-reconstructed units:
4000 /// * top-right: available while the unit to the right is still inside
4001 /// the block (`col_off + tx < bw`); otherwise only the block's top row
4002 /// of units reaches past it, through the block-level answer
4003 /// (libaom's `row_off > 0` branch returns exactly
4004 /// `col_off + txw < plane_bw`).
4005 /// * bottom-left: a unit outside the block's left column has none
4006 /// (libaom returns 0 for `col_off > 0`); inside the block
4007 /// (`row_off + tx < bh`) they are the left unit's, already
4008 /// reconstructed; the bottom row falls back to the block-level answer.
4009 pub(crate) fn of_tu(
4010 bw: usize,
4011 bh: usize,
4012 col_off: usize,
4013 row_off: usize,
4014 // The unit's own width and height in pixels; equal for a square
4015 // transform, different for the rect unit a 1:4 strip's first split
4016 // produces (lane-rectsplitx r1).
4017 tx_w: usize,
4018 tx_h: usize,
4019 block: Self,
4020 ) -> Self {
4021 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
4022 // order, so both libaom predicates special-case it (lane-sb128c r10);
4023 // without this the last unit column of every chunk of a 128x64 block
4024 // predicts from a chunk libaom has not decoded yet.
4025 let wide = bw > 64;
4026 Self {
4027 above_right: if row_off > 0 {
4028 // `has_top_right`'s `row_off > 0` branch: the offset is taken
4029 // modulo the 64-wide chunk, except for the one unit whose
4030 // top-right corner is the centre of a 128x128 block.
4031 if wide {
4032 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
4033 } else {
4034 col_off + tx_w < bw
4035 }
4036 } else if col_off + tx_w < bw {
4037 true
4038 } else {
4039 block.above_right
4040 },
4041 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
4042 // `has_bottom_left`: at the left edge of a right-hand chunk
4043 // the bottom-left pixels are in the already-coded left chunk,
4044 // provided they stay inside it.
4045 (row_off % 64) + tx_h < bh.min(64)
4046 } else if col_off > 0 {
4047 false
4048 } else if row_off + tx_h < bh {
4049 true
4050 } else {
4051 block.below_left
4052 },
4053 }
4054 }
4055
4056 /// What a block of `side` samples at `(x, y)` may read past its own edges,
4057 /// in a frame of `width` by `height`.
4058 pub(crate) fn of(
4059 side: usize,
4060 x: usize,
4061 y: usize,
4062 width: usize,
4063 height: usize,
4064 fctx: &crate::decode::FrameCtx,
4065 ) -> Self {
4066 Self {
4067 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
4068 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
4069 }
4070 }
4071
4072 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
4073 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
4074 /// block's own width for the row stride and by its own height for the
4075 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
4076 /// unlike the square [`Self::of`] which uses one `side` for everything.
4077 pub(crate) fn of_rect(
4078 bw: usize,
4079 bh: usize,
4080 x: usize,
4081 y: usize,
4082 width: usize,
4083 height: usize,
4084 fctx: &crate::decode::FrameCtx,
4085 ) -> Self {
4086 Self {
4087 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
4088 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
4089 }
4090 }
4091
4092 /// [`Self::of`] for one transform unit of a square block whose transform
4093 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
4094 /// non-zero `row_off`/`col_off`): interior units answer from the block's
4095 /// own geometry, and only a unit on the block's top row (resp. left
4096 /// column) reaches the table -- which is the BLOCK's table read at the
4097 /// BLOCK's position, never a table row for the transform's size. Letting
4098 /// the unit stand in for a block of its own size agrees with libaom for
4099 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
4100 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
4101 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
4102 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
4103 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
4104 /// the transform covering the whole block, luma): everything before the
4105 /// table lookup is that function's own early-exit ladder.
4106 fn top_right_rect(
4107 bw: usize,
4108 bh: usize,
4109 x: usize,
4110 y: usize,
4111 fctx: &crate::decode::FrameCtx,
4112 ) -> bool {
4113 let sb_mi: usize = reach_sb_px(fctx) / 4;
4114 let (mi_row, mi_col) = (y / 4, x / 4);
4115 let bw_log2 = (bw / 4).trailing_zeros() as usize;
4116 let bh_log2 = (bh / 4).trailing_zeros() as usize;
4117 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
4118 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
4119 // Top row of the superblock: the top-right pixels are in the (already
4120 // decoded) superblock above.
4121 if blk_row == 0 {
4122 return true;
4123 }
4124 // Rightmost column: they fall in the superblock to the right.
4125 if ((blk_col + 1) << bw_log2) >= sb_mi {
4126 return false;
4127 }
4128 let table = rect_reach_tables(bw, bh).0;
4129 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4130 }
4131
4132 /// libaom `has_top_right`'s own index arithmetic:
4133 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
4134 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
4135 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
4136 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
4137 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
4138 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
4139 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
4140 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
4141 (blk_row << (5 - bw_log2)) + blk_col
4142 }
4143
4144 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
4145 fn bottom_left_rect(
4146 bw: usize,
4147 bh: usize,
4148 x: usize,
4149 y: usize,
4150 fctx: &crate::decode::FrameCtx,
4151 ) -> bool {
4152 let sb_mi: usize = reach_sb_px(fctx) / 4;
4153 let (mi_row, mi_col) = (y / 4, x / 4);
4154 let bw_log2 = (bw / 4).trailing_zeros() as usize;
4155 let bh_log2 = (bh / 4).trailing_zeros() as usize;
4156 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
4157 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
4158 // Leftmost column of the superblock: the bottom-left pixels are in
4159 // the left superblock iff they stay inside its height.
4160 if blk_col == 0 {
4161 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
4162 }
4163 // Bottom row (and not the leftmost column): they fall in the
4164 // superblock below, which is not decoded yet.
4165 if ((blk_row + 1) << bh_log2) >= sb_mi {
4166 return false;
4167 }
4168 let table = rect_reach_tables(bw, bh).1;
4169 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4170 }
4171
4172 /// Marks every [`Reach::of`] made until the returned guard drops as being
4173 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
4174 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
4175 /// unaffected: libaom's own comment says vertical rectangles keep their
4176 /// non-vert table, which is what [`Reach::of_rect`] already reads.
4177 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
4178 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
4179 /// can count the sub-block work that partition creates (lane-ab16).
4180 pub(crate) fn in_vert_ab() -> bool {
4181 VERT_AB_PARTITION.with(std::cell::Cell::get)
4182 }
4183
4184 pub(crate) fn vert_ab_partition() -> VertAbGuard {
4185 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
4186 }
4187
4188 /// Neither, which is all a mode that reads no further than its own edges
4189 /// needs.
4190 pub(crate) fn none() -> Self {
4191 Self {
4192 above_right: false,
4193 below_left: false,
4194 }
4195 }
4196
4197 /// `has_top_right` for a block whose transform covers it whole: the top
4198 /// row of a superblock reads into the superblock above, which is decoded;
4199 /// the rightmost column would read into the superblock to the right, which
4200 /// is not; and everything between is the table's to answer.
4201 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4202 let (row, col, per_side) = Self::position(side, x, y, fctx);
4203 if row == 0 {
4204 return true;
4205 }
4206 if col + 1 == per_side {
4207 return false;
4208 }
4209 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4210 // (the clamp corner-cut that used to live here is gone); sides
4211 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4212 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4213 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4214 // -- a reach over-estimate (extra above-right reference pixels),
4215 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4216 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4217 // NB: named `table_row`, not `row` -- `row` above is the block's
4218 // position inside the superblock and is what the bit index below
4219 // steps by (a merge that shadowed it desynced every block size).
4220 let table_row = Self::table(side);
4221 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
4222 && table_row < HAS_TOP_RIGHT_VERT.len()
4223 {
4224 HAS_TOP_RIGHT_VERT[table_row]
4225 } else {
4226 HAS_TOP_RIGHT[table_row]
4227 };
4228 Self::bit(
4229 table,
4230 (row * Self::table_stride(side) + col) % (table.len() * 8),
4231 )
4232 }
4233
4234 /// `has_bottom_left` for such a block: the leftmost column of a superblock
4235 /// reads into the superblock to its left, which is decoded only as far
4236 /// down as its own bottom; the bottom row would read into the superblock
4237 /// below, which is not decoded at all; and the table answers the rest.
4238 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4239 let (row, col, per_side) = Self::position(side, x, y, fctx);
4240 if col == 0 {
4241 return row * side + side < reach_sb_px(fctx);
4242 }
4243 if row + 1 == per_side {
4244 return false;
4245 }
4246 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4247 // (the clamp corner-cut that used to live here is gone); sides
4248 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4249 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4250 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4251 // -- a reach over-estimate (extra above-right reference pixels),
4252 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4253 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4254 // NB: named `table_row`, not `row` -- `row` above is the block's
4255 // position inside the superblock and is what the bit index below
4256 // steps by (a merge that shadowed it desynced every block size).
4257 let table_row = Self::table(side);
4258 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
4259 && table_row < HAS_BOTTOM_LEFT_VERT.len()
4260 {
4261 HAS_BOTTOM_LEFT_VERT[table_row]
4262 } else {
4263 HAS_BOTTOM_LEFT[table_row]
4264 };
4265 Self::bit(
4266 table,
4267 (row * Self::table_stride(side) + col) % (table.len() * 8),
4268 )
4269 }
4270
4271 /// Where a block sits inside its superblock, in blocks of its own size,
4272 /// and how many of them a superblock is across.
4273 fn position(
4274 side: usize,
4275 x: usize,
4276 y: usize,
4277 fctx: &crate::decode::FrameCtx,
4278 ) -> (usize, usize, usize) {
4279 let sb = reach_sb_px(fctx);
4280 ((y % sb) / side, (x % sb) / side, sb / side)
4281 }
4282
4283 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
4284 /// these tables to its compile-time maximum superblock (128, spec
4285 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
4286 /// size an encode actually uses, so a block's row in the bit index steps
4287 /// by 128 / `side` even though this crate only ever codes a 64
4288 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
4289 /// here instead indexes the wrong bit for every block size but the one
4290 /// where 64 and 128 give the same stride.
4291 fn table_stride(side: usize) -> usize {
4292 128 / side
4293 }
4294
4295 /// Which of the three block sizes the encoder codes a table row is for.
4296 fn table(side: usize) -> usize {
4297 if side == BLOCK {
4298 1
4299 } else if side == 8 {
4300 2
4301 } else if side == 4 {
4302 3
4303 } else {
4304 0
4305 }
4306 }
4307
4308 /// One bit of a table, counting from the low end of its first byte.
4309 fn bit(table: &[u8], index: usize) -> bool {
4310 (table[index / 8] >> (index % 8)) & 1 != 0
4311 }
4312}
4313
4314/// What one symbol costs against a CDF, in bits.
4315/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
4316/// search, the frame header's `allow_warped_motion` and the sequence's
4317/// `enable_warped_motion`, all three together. ON by default since
4318/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
4319/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
4320/// bits -- back off for an A/B on one build.
4321pub(crate) fn warp_on() -> bool {
4322 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4323 crate::envflags::var("EC_AV1_WARP")
4324 .ok()
4325 .map(|v| !matches!(v.as_str(), "0" | "off"))
4326 });
4327 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
4328}
4329
4330/// The smallest LEAF an OBMC candidate is offered for, so the census can
4331/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
4332/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
4333/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
4334///
4335/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
4336/// (12 frames, four quantizers, the standing keep table):
4337///
4338/// | min side | film 1080p | film 2160p | screen |
4339/// |---|---|---|---|
4340/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
4341/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
4342/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
4343/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
4344///
4345/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
4346/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
4347/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
4348/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
4349/// that wins the local RD on five blocks in six and loses ladder bytes is
4350/// the `local-RD-on-references` class again, not a missing footprint.
4351///
4352/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
4353/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
4354/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
4355/// loss on the 1080p film became a 0.3-point win and the other two rows went
4356/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
4357/// of the "local win, ladder loss" it was charged with was the rate weight.
4358/// It still does not meet the keep rule (two down, one flat, both columns).
4359/// The tool stays OFF by default; the upgrade path is the price, not the size
4360/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
4361/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
4362/// 1080p film up, i.e. the same disagreement between the two gates).
4363///
4364/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
4365/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
4366/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
4367/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
4368/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
4369/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
4370/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
4371/// the margin's gain are the same bytes. It stays OFF.
4372///
4373/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
4374/// judgement above was taken when the gate's "film" rows were the `testsrc2`
4375/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
4376/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
4377/// the standing native keep table (`bd_rate_screen_native`):
4378///
4379/// | arm | film A | film B | screen | OBMC fire A/B |
4380/// |---|---|---|---|---|
4381/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
4382/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
4383/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
4384///
4385/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
4386/// only), where the anchors' non-skip area is the known gap:
4387///
4388/// | arm | film B long GOP | wall ours |
4389/// |---|---|---|
4390/// | off (control) | +89.8 / +9.1 | 477.5s |
4391/// | min side 8 | +89.6 / +9.0 | 514.1s |
4392///
4393/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
4394/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
4395/// only at min side 16, which is exactly where film B loses 0.7 on both
4396/// columns. Nothing here meets the keep rule (both films down on both
4397/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
4398/// costs +7.7% wall. OBMC stays OFF at every preset.
4399fn obmc_min_side() -> usize {
4400 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4401 *N.get_or_init(|| {
4402 std::env::var("EC_AV1_OBMC_MIN")
4403 .ok()
4404 .and_then(|v| v.parse().ok())
4405 .unwrap_or(8)
4406 })
4407}
4408
4409/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
4410/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
4411/// same frame-CDF price the coefficients of a non-screen frame are estimated
4412/// with, not the static default table.
4413/// The same price for whichever alphabet the writer will really use for this
4414/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
4415/// (`allow_warped_motion` and at least one warp sample), otherwise the
4416/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
4417/// search pay it, so the alphabet cancels out of a comparison and only its
4418/// per-value spread decides.
4419fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
4420 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
4421 return 0.0;
4422 };
4423 match warp_alphabet {
4424 true => crate::tile::motion_mode_symbol_bits(row, motion),
4425 false => crate::tile::obmc_symbol_bits(row, motion == 1),
4426 }
4427}
4428
4429/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
4430/// candidate, the header's `allow_warped_motion` and the sequence's
4431/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
4432/// native keep table, against the same build with the knob off:
4433///
4434/// | clip | warp on | off |
4435/// |---|---|---|
4436/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
4437/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
4438/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
4439///
4440/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
4441/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
4442/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
4443/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
4444/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
4445/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
4446/// this is a measured loss, not an inert knob. Same shape as the OBMC
4447/// candidate above it (`obmc_min_side`): a local RD win that does not convert
4448/// into ladder bytes.
4449///
4450/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
4451/// because a tool whose gain is local and whose cost is the rate it adds is
4452/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
4453///
4454/// | clip | warp on | off (both at lambda 0.05) |
4455/// |---|---|---|
4456/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
4457/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
4458/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
4459///
4460/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
4461/// column inside 0.1 everywhere -- which reads as a keep rather than the
4462/// 0.7/0.9 loss it was.
4463///
4464/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
4465/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
4466/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
4467/// ran the conformance shape the lambda lane deferred: every warp stream
4468/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
4469/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
4470/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
4471/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
4472/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
4473/// `allow_warped_motion` and `enable_warped_motion` back off together.
4474///
4475/// The WARPED_CAUSAL prediction of one square single-reference block: the
4476/// decoder's own warp-sample walk (`decode::find_samples` +
4477/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
4478/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
4479/// grid -- never a second implementation of any of the three. `None` when the
4480/// block would code no motion_mode symbol at all, when it has no warp sample
4481/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
4482/// or when the projection is not filter-representable (the decoder would then
4483/// predict translationally, so the mode is pure cost).
4484#[allow(clippy::too_many_arguments)]
4485fn warp_prediction(
4486 grid: &MiGrid,
4487 (mi_row, mi_col): (usize, usize),
4488 (mi_rows, mi_cols): (usize, usize),
4489 (x, y): (usize, usize),
4490 side: usize,
4491 mv: (i32, i32),
4492 ref_frame: i8,
4493 ref_planes: [(&[u16], usize, usize, usize); 3],
4494 fctx: &crate::decode::FrameCtx,
4495) -> Option<[Vec<u8>; 3]> {
4496 let n4 = side / 4;
4497 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
4498 return None;
4499 }
4500 let mut samples = crate::decode::find_samples(
4501 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
4502 );
4503 if samples.is_empty() {
4504 return None;
4505 }
4506 if samples.len() > 1 {
4507 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
4508 }
4509 let params = crate::warp::find_projection(
4510 &samples,
4511 side as i32,
4512 side as i32,
4513 mv.1,
4514 mv.0,
4515 mi_row as i32,
4516 mi_col as i32,
4517 )?;
4518 let mut pred = [
4519 vec![0u16; side * side],
4520 vec![0u16; side * side / 4],
4521 vec![0u16; side * side / 4],
4522 ];
4523 // The translational prediction first, exactly as the decoder builds it,
4524 // then the affine one over the planes whose OWN block is at least 8x8
4525 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
4526 // 4x4 chroma stays translational).
4527 for (i, r) in ref_planes.into_iter().enumerate() {
4528 let luma_plane = i == 0;
4529 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
4530 let s = if luma_plane { side } else { side / 2 };
4531 mc::predict(
4532 r.0,
4533 r.1,
4534 r.2,
4535 r.3,
4536 mv_to_q4(px, mv.1, luma_plane),
4537 mv_to_q4(py, mv.0, luma_plane),
4538 s,
4539 s,
4540 &mut pred[i],
4541 fctx,
4542 );
4543 if crate::decode::warp_plane_allowed(s, s) {
4544 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
4545 crate::warp::warp_affine(
4546 &params,
4547 r.0,
4548 r.2 as i32,
4549 r.3 as i32,
4550 r.1 as i32,
4551 &mut pred[i],
4552 px as i32,
4553 py as i32,
4554 cside,
4555 cside,
4556 cside,
4557 sub,
4558 sub,
4559 fctx,
4560 );
4561 }
4562 }
4563 let [py_buf, pu_buf, pv_buf] = pred;
4564 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4565 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4566}
4567
4568/// What tile.rs' `write_compound_ref_frames` pays for the pair
4569/// `(ref0, ref1)`, symbol for symbol, each at the context its own
4570/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
4571/// derives from the block's above/left neighbours -- plus the `comp_mode`
4572/// symbol itself at `reference_mode_ctx`.
4573///
4574/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
4575/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
4576/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
4577/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4578pub(crate) fn compound_ref_bits((ref0, ref1): (i8, i8), stack: &crate::mvstack::MvStack) -> f64 {
4579 use crate::mvstack::{
4580 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4581 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
4582 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
4583 uni_comp_ref_p1_ctx,
4584 };
4585 let (a, a1) = stack.above_refs;
4586 let (l, l1) = stack.left_refs;
4587 let unidir = is_uni_comp_ref(ref0, ref1);
4588 let comp_mode = symbol_bits(
4589 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4590 1,
4591 );
4592 let ref_type = symbol_bits(
4593 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
4594 usize::from(!unidir),
4595 );
4596 if unidir {
4597 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
4598 let p0 = symbol_bits(
4599 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4600 usize::from(both_backward),
4601 );
4602 if both_backward {
4603 return comp_mode + ref_type + p0;
4604 }
4605 let past_last2 = ref1 != LAST2_FRAME;
4606 let p1 = symbol_bits(
4607 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
4608 usize::from(past_last2),
4609 );
4610 let p2 = if past_last2 {
4611 symbol_bits(
4612 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4613 usize::from(ref1 == GOLDEN_FRAME),
4614 )
4615 } else {
4616 0.0
4617 };
4618 return comp_mode + ref_type + p0 + p1 + p2;
4619 }
4620 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
4621 let fwd = symbol_bits(
4622 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
4623 usize::from(far),
4624 ) + if far {
4625 symbol_bits(
4626 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4627 usize::from(ref0 == GOLDEN_FRAME),
4628 )
4629 } else {
4630 symbol_bits(
4631 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
4632 usize::from(ref0 == LAST2_FRAME),
4633 )
4634 };
4635 let is_altref = ref1 == ALTREF_FRAME;
4636 let bwd = symbol_bits(
4637 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
4638 usize::from(is_altref),
4639 ) + if is_altref {
4640 0.0
4641 } else {
4642 symbol_bits(
4643 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
4644 usize::from(ref1 == ALTREF2_FRAME),
4645 )
4646 };
4647 comp_mode + ref_type + fwd + bwd
4648}
4649
4650/// What the `skip` symbol costs at the context tile.rs really codes it with
4651/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
4652/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
4653/// exactly the difference between this symbol's two values, so the row it is
4654/// read from moves that decision (class pricer-context-zero, lane-ctx).
4655pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
4656 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
4657 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
4658}
4659
4660/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
4661/// neighbours' intra/inter state, with an out-of-tile side contributing
4662/// nothing, off the same two cells (lane-ctx).
4663pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
4664 let ctx = crate::tile::intra_inter_ctx(
4665 stack.above_nbr.is_some(),
4666 stack.left_nbr.is_some(),
4667 stack.above_nbr.is_some_and(|n| n.is_inter),
4668 stack.left_nbr.is_some_and(|n| n.is_inter),
4669 );
4670 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
4671}
4672
4673/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
4674/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
4675/// context -- zero on a frame that carries no `reference_select` bit, where
4676/// the writer codes no symbol at all.
4677fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
4678 if !reference_select() {
4679 return 0.0;
4680 }
4681 symbol_bits(
4682 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4683 0,
4684 )
4685}
4686
4687/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
4688/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
4689/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
4690/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
4691/// LAST is p1=0,p3=0,p4=0,
4692/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
4693/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
4694/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
4695/// symbols off the wrong CDFs -- which is what made the search believe an
4696/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
4697/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
4698/// paid nothing at all, so compound was overcharged by the whole symbol.
4699pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
4700 use crate::mvstack::{
4701 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4702 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4703 single_ref_p5_ctx, single_ref_p6_ctx,
4704 };
4705 let (a, a1) = stack.above_refs;
4706 let (l, l1) = stack.left_refs;
4707 let comp_mode = comp_mode_single_bits(stack);
4708 let backward = ref_frame >= BWDREF_FRAME;
4709 let p1 = symbol_bits(
4710 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4711 usize::from(backward),
4712 );
4713 if backward {
4714 let is_altref = ref_frame == ALTREF_FRAME;
4715 let p2 = symbol_bits(
4716 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
4717 usize::from(is_altref),
4718 );
4719 return comp_mode
4720 + p1
4721 + p2
4722 + if is_altref {
4723 0.0
4724 } else {
4725 symbol_bits(
4726 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
4727 usize::from(ref_frame == ALTREF2_FRAME),
4728 )
4729 };
4730 }
4731 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4732 comp_mode
4733 + p1
4734 + symbol_bits(
4735 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4736 usize::from(far),
4737 )
4738 + if far {
4739 symbol_bits(
4740 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4741 usize::from(ref_frame == GOLDEN_FRAME),
4742 )
4743 } else {
4744 symbol_bits(
4745 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4746 usize::from(ref_frame == LAST2_FRAME),
4747 )
4748 }
4749}
4750
4751pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
4752 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
4753 let width = cdf[symbol] - low;
4754 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
4755 // 32769 prices a symbol can carry; the `log2` behind each is computed
4756 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
4757 // profile -- this function is called for every symbol of every candidate
4758 // the RD search prices). Each entry is exactly the expression this used
4759 // to evaluate, so every price is bit-identical.
4760 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
4761 PRICES.get_or_init(|| {
4762 (0..=32768u32)
4763 .map(|w| -(f64::from(w) / 32768.0).log2())
4764 .collect()
4765 })[usize::from(width)]
4766}
4767
4768/// What the tile writer spends to say a block is coded in each of the thirteen
4769/// modes, given the modes of the blocks above it and to its left: the luma mode
4770/// symbol against the CDF those two neighbours pick, the angle delta a
4771/// directional mode carries, and the chroma mode symbol, whose CDF the luma
4772/// mode itself indexes.
4773///
4774/// Without this the search is blind to what a mode costs to name, which is not
4775/// a rounding error: a directional mode on a picture that does not run that way
4776/// is a rate loss the squared error never sees.
4777/// Codes one square of the picture as a single block: searches the luma mode,
4778/// codes both chroma planes DC, and hands back the block and what it cost --
4779/// squared error plus lambda times the bits its symbols spend.
4780/// How many halvings of a `side`-square block's transform the `tx_depth`
4781/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
4782/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
4783fn max_tx_depth(side: usize) -> usize {
4784 match side {
4785 8 => 1,
4786 16 | 32 => 2,
4787 _ => 0,
4788 }
4789}
4790
4791/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
4792/// Priced at context row 0 -- the writer picks the real row from its
4793/// neighbours' transform sizes, which the search has no view of; the term is
4794/// the same for every depth of one block either way, so it only shifts the
4795/// depth-0-versus-split margin, never the ordering between two splits.
4796fn tx_depth_bits(side: usize, depth: usize) -> f64 {
4797 match side {
4798 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
4799 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
4800 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
4801 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
4802 }
4803}
4804
4805/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4806/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4807/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4808/// (the mode search's own weight); below 1 the split trial is charged less
4809/// for its bits and fires more often.
4810///
4811/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4812/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4813/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4814/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4815/// so what is mis-calibrated is the weight the split's rate is judged under,
4816/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4817pub(crate) fn split_lambda_mult() -> f64 {
4818 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4819 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4820 .ok()
4821 .and_then(|v| v.parse().ok())
4822 .unwrap_or(SPLIT_LAMBDA)
4823 });
4824 *M
4825}
4826
4827/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4828/// the sweep that chose it.
4829const SPLIT_LAMBDA: f64 = 1.0;
4830
4831/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4832/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
4833/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
4834/// trials offered, trials the split won, then the (rate, distortion) of the
4835/// split and flat arms summed apart for the split-won and flat-won trials --
4836/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
4837static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
4838 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
4839
4840/// Whether [`SPLIT_CENSUS`] is armed, read once.
4841pub(crate) fn split_census_on() -> bool {
4842 static ON: std::sync::LazyLock<bool> =
4843 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
4844 *ON
4845}
4846
4847/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
4848/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
4849fn split_census_base(site: usize, key: bool, side: usize) -> usize {
4850 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
4851 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
4852}
4853
4854/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
4855/// `(rate in bits, distortion as squared error)`.
4856fn split_census(
4857 site: usize,
4858 key: bool,
4859 side: usize,
4860 split_won: bool,
4861 split: (f64, f64),
4862 flat: (f64, f64),
4863) {
4864 use std::sync::atomic::Ordering::Relaxed;
4865 let base = split_census_base(site, key, side);
4866 let add = |i: usize, v: u64| {
4867 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
4868 };
4869 add(0, 1);
4870 let off = if split_won {
4871 add(1, 1);
4872 2
4873 } else {
4874 6
4875 };
4876 let (win, lose) = if split_won {
4877 (split, flat)
4878 } else {
4879 (flat, split)
4880 };
4881 add(off, (win.0 * 64.0).max(0.0) as u64);
4882 add(off + 1, win.1.max(0.0) as u64);
4883 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
4884 add(off + 3, lose.1.max(0.0) as u64);
4885}
4886
4887/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
4888/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
4889/// last table a run prints is the whole encode's total (there is no flush
4890/// hook the encoder API guarantees to reach).
4891pub(crate) fn dump_split_census() {
4892 use std::sync::atomic::Ordering::Relaxed;
4893 eprintln!(
4894 "SPLITCENSUS site frame side offered split share% \
4895 win_rate win_dist lose_rate lose_dist"
4896 );
4897 for site in 0..2 {
4898 for key in [true, false] {
4899 for side_idx in 0..4 {
4900 let base = split_census_base(site, key, 8 << side_idx);
4901 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
4902 if v[0] == 0 {
4903 continue;
4904 }
4905 let (n, s) = (v[0] as f64, v[1] as f64);
4906 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
4907 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
4908 // all `n` trials, not a mean of two means.
4909 eprintln!(
4910 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
4911 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
4912 if site == 0 { "intra" } else { "inter" },
4913 if key { "key " } else { "inter" },
4914 8 << side_idx,
4915 v[0],
4916 v[1],
4917 100.0 * s / n,
4918 (v[2] + v[6]) as f64 / n / 64.0,
4919 (v[3] + v[7]) as f64 / n,
4920 (v[4] + v[8]) as f64 / n / 64.0,
4921 (v[5] + v[9]) as f64 / n,
4922 );
4923 }
4924 }
4925 }
4926}
4927
4928/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
4929/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
4930/// its mode/reference syntax and not the search's own cost function
4931/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
4932/// control; below 1 a coded vector is charged less and `NEWMV` wins more
4933/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
4934pub(crate) fn mv_lambda_mult() -> f64 {
4935 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4936 crate::envflags::var("EC_AV1_MV_LAMBDA")
4937 .ok()
4938 .and_then(|v| v.parse().ok())
4939 .unwrap_or(MV_LAMBDA)
4940 });
4941 *M
4942}
4943
4944/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
4945const MV_LAMBDA: f64 = 1.0;
4946
4947/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
4948/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
4949/// which the RD cost multiplies by lambda). Zero at the default weight.
4950fn mv_rate_surcharge(mv_bits: f64) -> f64 {
4951 (mv_lambda_mult() - 1.0) * mv_bits
4952}
4953
4954/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
4955/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
4956/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
4957/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
4958/// cost it won by, 4 the summed cost it lost by, 5 the summed
4959/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
4960/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
4961/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
4962/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
4963/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
4964static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
4965 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
4966
4967/// Whether [`NEWMV_CENSUS`] is armed, read once.
4968pub(crate) fn newmv_census_on() -> bool {
4969 static ON: std::sync::LazyLock<bool> =
4970 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
4971 *ON
4972}
4973
4974/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
4975fn newmv_census_global(i: usize) {
4976 if newmv_census_on() {
4977 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4978 }
4979}
4980
4981/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
4982/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
4983/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
4984/// candidate's own; both `f64::INFINITY` is a block that offered neither.
4985fn newmv_census_block(
4986 side: usize,
4987 offered: bool,
4988 new_cost: f64,
4989 other_cost: f64,
4990 mv: (i32, i32),
4991 nearest: (i32, i32),
4992 mv_bits: f64,
4993) {
4994 if !newmv_census_on() {
4995 return;
4996 }
4997 use std::sync::atomic::Ordering::Relaxed;
4998 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
4999 let add = |i: usize, v: u64| {
5000 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
5001 };
5002 add(0, 1);
5003 if !offered {
5004 return;
5005 }
5006 add(1, 1);
5007 if new_cost < other_cost {
5008 add(2, 1);
5009 add(3, (other_cost - new_cost).max(0.0) as u64);
5010 } else {
5011 add(4, (new_cost - other_cost).max(0.0) as u64);
5012 }
5013 add(
5014 5,
5015 ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64,
5016 );
5017 if mv == nearest {
5018 add(6, 1);
5019 }
5020 add(7, (mv_bits * 64.0).max(0.0) as u64);
5021}
5022
5023/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
5024/// same guard [`dump_split_census`] rides (cumulative, so the last table a
5025/// run prints is the whole encode's).
5026pub(crate) fn dump_newmv_census() {
5027 use std::sync::atomic::Ordering::Relaxed;
5028 eprintln!(
5029 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
5030 mv_dist_q3 mv==nearest% mv_bits"
5031 );
5032 for side_idx in 0..4 {
5033 let base = side_idx * 8;
5034 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
5035 if v[0] == 0 {
5036 continue;
5037 }
5038 let off = v[1].max(1) as f64;
5039 eprintln!(
5040 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
5041 8 << side_idx,
5042 v[0],
5043 v[1],
5044 v[2],
5045 100.0 * v[2] as f64 / off,
5046 v[3] as f64 / v[2].max(1) as f64,
5047 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
5048 v[5] as f64 / off,
5049 100.0 * v[6] as f64 / off,
5050 v[7] as f64 / off / 64.0,
5051 );
5052 }
5053 // lane-hpmv: how many mv components this encode coded an eighth-pel bit
5054 // for, and how many of those named a vector no non-hp frame can code.
5055 let (hp_all, hp_eighth) = crate::tile::hp_symbols();
5056 eprintln!(
5057 "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)",
5058 100.0 * hp_eighth as f64 / hp_all.max(1) as f64,
5059 );
5060 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
5061 eprintln!(
5062 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
5063 leaf second reference {}/{} ({:.1}%)",
5064 g[1],
5065 g[0],
5066 100.0 * g[1] as f64 / g[0].max(1) as f64,
5067 g[3],
5068 g[2],
5069 100.0 * g[3] as f64 / g[2].max(1) as f64,
5070 );
5071 let [
5072 calls,
5073 evals,
5074 _subpel,
5075 rounds,
5076 near_pred,
5077 unmoved,
5078 widest,
5079 widest_moves,
5080 ] = crate::motion::take_census();
5081 let per = |n: u64| n as f64 / calls.max(1) as f64;
5082 eprintln!(
5083 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
5084 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
5085 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
5086 per(evals),
5087 per(rounds),
5088 100.0 * near_pred as f64 / calls.max(1) as f64,
5089 100.0 * unmoved as f64 / calls.max(1) as f64,
5090 100.0 * widest as f64 / calls.max(1) as f64,
5091 per(widest_moves),
5092 );
5093}
5094
5095/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
5096/// the intra witness's fire count stays its own.
5097pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
5098 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
5099
5100/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
5101/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
5102/// `0` compares types on reconstruction error alone, which is what separates
5103/// a rate-term calibration (class `rd-rate-term-calibration`) from a
5104/// distortion the trial mis-measures.
5105pub(crate) fn tx_type_lambda_mult() -> f64 {
5106 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
5107 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
5108 .ok()
5109 .and_then(|v| v.parse().ok())
5110 .unwrap_or(1.0)
5111 });
5112 *M
5113}
5114
5115/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
5116/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
5117/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
5118/// question needs: at weight 1 the five-type intra search spends 1.2% more
5119/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
5120/// of the type it picks.
5121pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
5122 if tx_type == TxType::DctDct {
5123 0.0
5124 } else {
5125 lambda * (tx_type_lambda_mult() - 1.0) * bits
5126 }
5127}
5128
5129/// lane-txrd instrument: over the FLAT inter luma decision, the summed
5130/// reconstruction error and priced bits of the type the search chose against
5131/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
5132/// integer counter. `EC_AV1_TXRD_CENSUS`.
5133pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
5134 std::sync::atomic::AtomicU64::new(0),
5135 std::sync::atomic::AtomicU64::new(0),
5136 std::sync::atomic::AtomicU64::new(0),
5137 std::sync::atomic::AtomicU64::new(0),
5138 std::sync::atomic::AtomicU64::new(0),
5139 std::sync::atomic::AtomicU64::new(0),
5140 std::sync::atomic::AtomicU64::new(0),
5141];
5142
5143/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
5144/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
5145#[cfg(test)]
5146pub(crate) fn take_txrd_stats() -> [u64; 7] {
5147 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5148}
5149
5150/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
5151#[cfg(test)]
5152pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
5153 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
5154}
5155
5156/// How many luma transform units resolved to each [`TxType`], indexed by the
5157/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
5158/// and the instrument that says which types the search actually reaches.
5159pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
5160 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
5161
5162/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
5163/// counts to its own encode.
5164#[cfg(test)]
5165pub(crate) fn take_tx_type_hits() -> [usize; 16] {
5166 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
5167}
5168
5169/// How many blocks resolved to each `tx_depth`, the fire count that says
5170/// whether the depth search below reaches its candidates at all.
5171static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
5172 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
5173
5174/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
5175/// to its own encode.
5176#[cfg(test)]
5177pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
5178 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5179}
5180
5181/// How many inter blocks resolved to each var-tx depth (0 = one transform
5182/// over the whole block, 1 = its four halves), the fire count a gate prints
5183/// to see the split search reach its candidates at all. Indexed
5184/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
5185/// says which of the four block classes the split reaches -- the 32x32 root
5186/// and the compound blocks are this lane's two new ones.
5187static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
5188 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5189
5190/// Whether a 32x32 inter winner searches its own var-tx depth (the four
5191/// 16x16 units against the flat transform) instead of coding depth 0 blind.
5192/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
5193///
5194/// Rejected three times on the bars rows of the native gate (flat to +0.3).
5195/// lane-av1resweep re-judged it on the two REAL film crops at
5196/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
5197/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
5198///
5199/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
5200/// |---|---|---|---|
5201/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
5202/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
5203/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
5204/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
5205/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
5206///
5207/// The bars rows are ~90% zero-intra-cost cells, so the split never had
5208/// residual to reach there -- the tool was being judged on content that
5209/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
5210fn tx32_depth_search() -> bool {
5211 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5212 crate::envflags::var("EC_AV1_TX32_DEPTH")
5213 .ok()
5214 .map(|v| !matches!(v.as_str(), "0" | "off"))
5215 });
5216 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
5217}
5218
5219/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
5220/// trial units have to be predicted from BOTH references
5221/// ([`mc_trial_compound`]) or the split would re-predict them by single-
5222/// reference translation, which is not what the decoder reconstructs.
5223/// ON by default (the table on [`tx32_depth_search`]: on real film it is
5224/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
5225/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
5226/// `EC_AV1_COMP_VARTX`.
5227fn compound_var_tx() -> bool {
5228 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5229 crate::envflags::var("EC_AV1_COMP_VARTX")
5230 .ok()
5231 .map(|v| !matches!(v.as_str(), "0" | "off"))
5232 });
5233 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
5234}
5235
5236/// How many 32x32-and-below inter blocks each reference frame won, indexed by
5237/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
5238/// fire count a gate prints to see an extra reference reach a block at all
5239/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
5240/// chosen is a pyramid that costs bytes and buys nothing).
5241static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
5242 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5243
5244/// Reads [`REF_FRAME_HITS`] and zeroes it.
5245#[cfg(test)]
5246pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
5247 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
5248}
5249
5250/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
5251#[cfg(test)]
5252pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
5253 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5254}
5255
5256/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
5257/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
5258/// is one flag, depth 1 is a split root plus one unsplit flag per child
5259/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
5260/// or a 4x4 sub-size).
5261fn txfm_split_bits(side: usize, depth: usize) -> f64 {
5262 let max_tx = side.min(64);
5263 let ctx = |tx: usize| {
5264 crate::decode::txfm_partition_ctx_rect(
5265 crate::decode::TXFM_CTX_INIT,
5266 crate::decode::TXFM_CTX_INIT,
5267 side,
5268 tx,
5269 tx,
5270 )
5271 };
5272 if depth == 0 {
5273 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
5274 }
5275 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
5276 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
5277}
5278
5279/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
5280/// type is never coded -- the decoder takes the LUMA type of the block's
5281/// chroma-reference position and reduces it to the set the chroma size allows
5282/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
5283/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
5284/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
5285/// basis they were never produced for: on the bars gate row the luma of the
5286/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
5287/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
5288/// collapse two lanes attributed to the type PRICE (class
5289/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
5290/// field the encoder never mirrored).
5291///
5292/// Re-codes the two chroma planes of a committed inter block at the type the
5293/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
5294/// the trials the caller already holds are right.
5295#[allow(clippy::too_many_arguments)]
5296fn recode_inter_chroma(
5297 chroma: &[Plane; 2],
5298 (x, y): (usize, usize),
5299 side: usize,
5300 mv: (i32, i32),
5301 refs: [(&[u16], usize, usize, usize); 2],
5302 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
5303 search: &Search,
5304 set: TxbSet,
5305 luma_tx_type: TxType,
5306 fctx: &crate::decode::FrameCtx,
5307) -> Option<[Trial; 2]> {
5308 let c = side / 2;
5309 let tx =
5310 crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
5311 if tx == TxType::DctDct {
5312 return None;
5313 }
5314 Some([0usize, 1].map(|p| match second {
5315 Some((mv1, r1)) => mc_trial_compound_typed(
5316 &chroma[p],
5317 x / 2,
5318 y / 2,
5319 c,
5320 (mv, mv1),
5321 false,
5322 refs[p],
5323 r1[p],
5324 search.base_q_idx,
5325 search.deadzone,
5326 set,
5327 tx,
5328 fctx,
5329 ),
5330 None => mc_trial_typed(
5331 &chroma[p],
5332 x / 2,
5333 y / 2,
5334 c,
5335 mv,
5336 false,
5337 refs[p].0,
5338 refs[p].1,
5339 refs[p].2,
5340 refs[p].3,
5341 false,
5342 search.base_q_idx,
5343 search.deadzone,
5344 set,
5345 tx,
5346 fctx,
5347 ),
5348 }))
5349}
5350
5351/// The inter block's own var-tx decision, once its motion vector is settled:
5352/// its residual as ONE transform over the whole block, or as the four
5353/// transforms of half the side the tree's first halving names. The prediction
5354/// is the same motion compensation either way, so the split trial
5355/// re-transforms the identical residual in four pieces -- it wins where four
5356/// small transforms carry a locally varying residual cheaper than one big
5357/// one. Commits the winner into `luma` and hands back its block-coordinate
5358/// levels, the depth the writer codes and the cost the winner adds to (or
5359/// takes off) the caller's already-computed flat cost.
5360///
5361/// Only for a block wholly inside the frame: past the true edge the reader's
5362/// var-tx recursion skips the units that fall outside
5363/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
5364/// leave the residual units this writes unpaired.
5365#[allow(clippy::too_many_arguments)]
5366fn commit_inter_luma(
5367 luma: &mut Plane,
5368 (x, y): (usize, usize),
5369 side: usize,
5370 mv: (i32, i32),
5371 reference: (&[u16], usize, usize, usize),
5372 search: &Search,
5373 flat: &Trial,
5374 skip: bool,
5375 // A COMPOUND winner's second half: the vector and reference planes the
5376 // trial units are blended from ([`mc_trial_compound`], the decoder's own
5377 // `comp_group_idx == 0` average). `None` is the single-reference block.
5378 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
5379 fctx: &crate::decode::FrameCtx,
5380) -> (Vec<i32>, u8, f64, Vec<TxType>) {
5381 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
5382 // type out of the two-type inter set the writer already codes a symbol
5383 // for, priced the same way the intra search is (sse + lambda * bits, the
5384 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
5385 // block codes no residual and the 64-point transform names no type.
5386 let mut flat_typed: Option<Trial> = None;
5387 let mut flat_type = TxType::DctDct;
5388 if !skip {
5389 // lane-intertx: on a `reduced_tx_set = 0` frame the search names the
5390 // Set1 alphabet the writer codes into ([`luma_set_for`], the shape
5391 // the intra search already takes), which is what makes the wider
5392 // seven-type candidate list below reachable -- and prices every
5393 // candidate, `IDTX` included, in the alphabet its symbol is really
5394 // coded into.
5395 if let Some(fset) = inter_luma_set(side).map(|set| luma_set_for(set, search.screen)) {
5396 let lambda = search.lambda * tx_type_lambda_mult();
5397 let cost = |t: &Trial| t.sse + lambda * t.bits;
5398 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
5399 if tx_type == TxType::DctDct {
5400 continue;
5401 }
5402 let candidate = match second {
5403 Some((mv1, ref1)) => mc_trial_compound_typed(
5404 luma,
5405 x,
5406 y,
5407 side,
5408 (mv, mv1),
5409 true,
5410 reference,
5411 ref1,
5412 search.base_q_idx,
5413 search.deadzone,
5414 fset,
5415 tx_type,
5416 fctx,
5417 ),
5418 None => mc_trial_typed(
5419 luma,
5420 x,
5421 y,
5422 side,
5423 mv,
5424 true,
5425 reference.0,
5426 reference.1,
5427 reference.2,
5428 reference.3,
5429 false,
5430 search.base_q_idx,
5431 search.deadzone,
5432 fset,
5433 tx_type,
5434 fctx,
5435 ),
5436 };
5437 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
5438 flat_type = tx_type;
5439 flat_typed = Some(candidate);
5440 }
5441 }
5442 }
5443 }
5444 // Counted at the return points, so the census names the types the block
5445 // really CODES -- a split unit's winner that the flat cost then beats was
5446 // never written (class `counter from refused stream`).
5447 let count = |types: &[TxType]| {
5448 for &t in types {
5449 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5450 }
5451 };
5452 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
5453 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
5454 use std::sync::atomic::Ordering::Relaxed;
5455 TXRD_STATS[0].fetch_add(1, Relaxed);
5456 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
5457 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
5458 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
5459 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
5460 // Is the `DCT_DCT` baseline the search compares against the trial
5461 // THIS function would build for the same block? A stale or
5462 // differently-predicted baseline is what would let a candidate win on
5463 // both terms at once (class `local-rd-on-references` vs a real
5464 // pricing defect); re-predicting it here is the only way to tell.
5465 if let Some(fset) = inter_luma_set(side) {
5466 let here = match second {
5467 Some((mv1, ref1)) => mc_trial_compound_typed(
5468 luma,
5469 x,
5470 y,
5471 side,
5472 (mv, mv1),
5473 true,
5474 reference,
5475 ref1,
5476 search.base_q_idx,
5477 search.deadzone,
5478 fset,
5479 TxType::DctDct,
5480 fctx,
5481 ),
5482 None => mc_trial_typed(
5483 luma,
5484 x,
5485 y,
5486 side,
5487 mv,
5488 true,
5489 reference.0,
5490 reference.1,
5491 reference.2,
5492 reference.3,
5493 false,
5494 search.base_q_idx,
5495 search.deadzone,
5496 fset,
5497 TxType::DctDct,
5498 fctx,
5499 ),
5500 };
5501 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
5502 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
5503 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
5504 let n = TXRD_STATS[0].load(Relaxed);
5505 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
5506 eprintln!(
5507 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
5508 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
5509 sse={:.0} bits={:.1}",
5510 second.is_some(),
5511 flat.sse,
5512 flat.bits,
5513 here.sse,
5514 here.bits,
5515 flat_ref.sse,
5516 flat_ref.bits,
5517 );
5518 }
5519 }
5520 }
5521 // What the caller's already-counted `flat` cost has to be corrected by
5522 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
5523 let flat_gain =
5524 (flat_ref.sse + search.lambda * flat_ref.bits) - (flat.sse + search.lambda * flat.bits);
5525 let eligible = tx_select()
5526 && tx_select_inter()
5527 && !skip
5528 && side >= 16
5529 && (second.is_none() || compound_var_tx())
5530 && (side != BLOCK || tx32_depth_search())
5531 && x + side <= luma.true_width
5532 && y + side <= luma.true_height;
5533 if !eligible {
5534 luma.commit(x, y, side, flat_ref);
5535 count(&[flat_type]);
5536 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
5537 }
5538 let tx = side / 2;
5539 let set = luma_set_for(
5540 if tx >= 32 {
5541 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
5542 TxbSet::Luma32Inter
5543 } else if tx >= 16 {
5544 TxbSet::Luma16Inter
5545 } else {
5546 TxbSet::Luma8Inter
5547 },
5548 search.screen,
5549 );
5550 let mut levels = vec![0i32; side * side];
5551 let (mut sse, mut bits) = (0.0, 0.0);
5552 let mut units = Vec::with_capacity(4);
5553 // The split units are smaller than their block, so their `txb_skip`
5554 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
5555 // each unit's own commit publishes what the next one reads, coding order.
5556 luma.ctx.tu_split = true;
5557 // One type per unit in the writer's own raster order (tile.rs
5558 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
5559 let mut split_types = vec![TxType::DctDct; 4];
5560 for tu_row in 0..2 {
5561 for tu_col in 0..2 {
5562 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
5563 let unit = |tx_type: TxType| match second {
5564 Some((mv1, ref1)) => mc_trial_compound_typed(
5565 luma,
5566 tu_x,
5567 tu_y,
5568 tx,
5569 (mv, mv1),
5570 true,
5571 reference,
5572 ref1,
5573 search.base_q_idx,
5574 search.deadzone,
5575 set,
5576 tx_type,
5577 fctx,
5578 ),
5579 None => mc_trial_typed(
5580 luma,
5581 tu_x,
5582 tu_y,
5583 tx,
5584 mv,
5585 true,
5586 reference.0,
5587 reference.1,
5588 reference.2,
5589 reference.3,
5590 false,
5591 search.base_q_idx,
5592 search.deadzone,
5593 set,
5594 tx_type,
5595 fctx,
5596 ),
5597 };
5598 let mut best: Option<(f64, TxType, Trial)> = None;
5599 for &tx_type in inter_tx_type_candidates(set, search.screen) {
5600 let candidate = unit(tx_type);
5601 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
5602 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
5603 best = Some((cost, tx_type, candidate));
5604 }
5605 }
5606 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
5607 split_types[tu_row * 2 + tu_col] = tx_type;
5608 sse += trial.sse;
5609 bits += trial.bits;
5610 for row in 0..tx {
5611 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
5612 .copy_from_slice(&trial.levels[row * tx..][..tx]);
5613 }
5614 units.push((tu_x, tu_y, trial));
5615 }
5616 }
5617 luma.ctx.tu_split = false;
5618 let split_rate = bits + txfm_split_bits(side, 1);
5619 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
5620 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
5621 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
5622 if split_census_on() {
5623 split_census(
5624 1,
5625 false,
5626 side,
5627 split_cost < flat_cost,
5628 (split_rate, sse),
5629 (flat_rate, flat_ref.sse),
5630 );
5631 }
5632 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
5633 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
5634 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
5635 // in the leaf row (class `gate-blind-to-feature`).
5636 let counted = side <= BLOCK;
5637 if split_cost < flat_cost {
5638 for (tu_x, tu_y, trial) in &units {
5639 luma.commit(*tu_x, *tu_y, tx, trial);
5640 }
5641 if counted {
5642 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5643 }
5644 count(&split_types);
5645 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
5646 }
5647 if counted {
5648 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5649 }
5650 luma.commit(x, y, side, flat_ref);
5651 count(&[flat_type]);
5652 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
5653}
5654
5655/// The largest distinct-colour count a block may hold and still be offered a
5656/// palette candidate at all: past it the k-means quantisation costs more
5657/// error than the map saves rate, and every trial is wasted wall.
5658///
5659/// Swept on the gate's own screen capture (lane-av1pal2, the
5660/// `unswept-decision-constants` class): 32 (the value this lane inherited)
5661/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
5662/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
5663/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
5664/// binds on nothing this content holds. 128 ships: best BD against both
5665/// references and no wall cost at all (6.1s, the same as at 32, because the
5666/// blocks it newly admits are ones the RD then keeps).
5667/// `EC_AV1_PAL_MAXCOLORS`.
5668fn palette_max_colors() -> usize {
5669 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5670 *N.get_or_init(|| {
5671 std::env::var("EC_AV1_PAL_MAXCOLORS")
5672 .ok()
5673 .and_then(|v| v.parse().ok())
5674 .unwrap_or(128)
5675 })
5676}
5677
5678/// The palettes worth trying for one block's luma, in the shape libaom's
5679/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
5680/// distinct colours takes them ALL (the prediction is then exact and the
5681/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
5682/// one-dimensional Lloyd iteration seeded evenly across its range -- both
5683/// offered, because which wins is an RD question the caller answers.
5684/// `block` is `side*side` source samples, row-major.
5685fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
5686 let mut histogram = [0u32; 256];
5687 for &v in block {
5688 histogram[usize::from(v)] += 1;
5689 }
5690 let present: Vec<u16> = (0..256u16)
5691 .filter(|&v| histogram[usize::from(v)] > 0)
5692 .collect();
5693 if present.len() < 2 {
5694 return Vec::new();
5695 }
5696 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
5697 let mut base = [0u16; 8];
5698 base[..colors.len()].copy_from_slice(colors);
5699 let map = block
5700 .iter()
5701 .map(|&v| {
5702 colors
5703 .iter()
5704 .enumerate()
5705 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
5706 .map(|(i, _)| i as u8)
5707 .expect("a palette holds at least two colours")
5708 })
5709 .collect();
5710 crate::tile::PaletteY {
5711 size: colors.len() as u8,
5712 colors: base,
5713 map,
5714 }
5715 };
5716 if present.len() <= 8 {
5717 return vec![exact(&present)];
5718 }
5719 if present.len() > palette_max_colors() {
5720 return Vec::new();
5721 }
5722 let (lo, hi) = (i32::from(present[0]), i32::from(present[present.len() - 1]));
5723 let mut out = Vec::with_capacity(2);
5724 for n in [8usize, 4] {
5725 // Even seeding across the block's own range, then four Lloyd passes
5726 // over the histogram (256 bins, not `side*side` pixels).
5727 let mut centres: Vec<f64> = (0..n)
5728 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
5729 .collect();
5730 for _ in 0..4 {
5731 let mut sums = vec![0f64; n];
5732 let mut counts = vec![0u32; n];
5733 for (v, &count) in histogram.iter().enumerate() {
5734 if count == 0 {
5735 continue;
5736 }
5737 let k = (0..n)
5738 .min_by(|&a, &b| {
5739 (centres[a] - v as f64)
5740 .abs()
5741 .total_cmp(&(centres[b] - v as f64).abs())
5742 })
5743 .expect("n >= 2");
5744 sums[k] += (v as u32 * count) as f64;
5745 counts[k] += count;
5746 }
5747 for k in 0..n {
5748 if counts[k] > 0 {
5749 centres[k] = sums[k] / f64::from(counts[k]);
5750 }
5751 }
5752 }
5753 let mut colors: Vec<u16> = centres
5754 .iter()
5755 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
5756 .collect();
5757 colors.sort_unstable();
5758 colors.dedup();
5759 if colors.len() >= 2 {
5760 out.push(exact(&colors));
5761 }
5762 }
5763 out
5764}
5765
5766#[allow(clippy::too_many_arguments)]
5767// ---------------------------------------------------------------------------
5768// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
5769// validity). A key frame that detected screen content and finds enough exact
5770// repeats in its own source sets `allow_intrabc`, which the spec forces every
5771// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
5772// its place when the copied blocks pay back the deblock/CDEF/LR the frame
5773// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
5774// ---------------------------------------------------------------------------
5775
5776/// Whether intra block copy is offered at all. **Off by default** --
5777/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
5778/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
5779/// but on the gate's real screen capture it MEASURED WORSE: setting
5780/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
5781/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
5782/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
5783/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
5784/// that detected no screen content.
5785fn intrabc_enabled() -> bool {
5786 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
5787 return forced;
5788 }
5789 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5790 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
5791}
5792
5793thread_local! {
5794 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
5795 /// probe runs both arms in one process, and the suite is one process, so
5796 /// an environment variable cannot separate them (same reason
5797 /// [`SCREEN_FORCE`] exists).
5798 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
5799}
5800
5801#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5802pub(crate) fn force_intrabc(value: Option<bool>) {
5803 INTRABC_FORCE.with(|c| c.set(value));
5804}
5805
5806/// How many of a screen frame's 16x16 blocks must have an exact repeat
5807/// somewhere else in the source before `allow_intrabc` is worth the in-loop
5808/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
5809/// constant class: `probe_intrabc_threshold` measures the arm at several
5810/// values.
5811fn intrabc_pct() -> usize {
5812 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5813 *N.get_or_init(|| {
5814 std::env::var("EC_AV1_INTRABC_PCT")
5815 .ok()
5816 .and_then(|v| v.parse().ok())
5817 .unwrap_or(10)
5818 })
5819}
5820
5821/// The pixel grid intrabc source positions are hashed on
5822/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
5823/// which keeps the block-hash table (and so the search) linear in the frame
5824/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
5825/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
5826/// bilinear interpolation decode.rs applies but this encoder does not.
5827fn intrabc_step() -> usize {
5828 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5829 *N.get_or_init(|| {
5830 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
5831 .ok()
5832 .and_then(|v| v.parse().ok())
5833 .unwrap_or(4);
5834 if n % 2 == 0 { n.max(2) } else { 4 }
5835 })
5836}
5837
5838/// The side of the luma square the block-hash table is keyed on.
5839const IBC_HASH: usize = 16;
5840
5841/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
5842/// the current one the source's bottom-right corner must already be. Under
5843/// 128 superblocks the same 256 pixels are two superblocks, which
5844/// [`Ibc::dv_valid`] derives from the size itself.
5845const INTRABC_DELAY_SB64: i32 = 4;
5846
5847/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
5848fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
5849 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
5850 for row in 0..IBC_HASH {
5851 let base = (y + row) * width + x;
5852 for &v in &plane[base..base + IBC_HASH] {
5853 h ^= u64::from(v);
5854 h = h.wrapping_mul(0x100_0000_01b3);
5855 }
5856 }
5857 h
5858}
5859
5860/// Every `intrabc_step()`-aligned position of `plane` inside
5861/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
5862fn ibc_index(
5863 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
5864 plane: &[u8],
5865 width: usize,
5866 (x0, y0): (usize, usize),
5867 (x1, y1): (usize, usize),
5868) {
5869 let step = intrabc_step();
5870 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
5871 return;
5872 }
5873 let mut y = y0.next_multiple_of(step);
5874 while y + IBC_HASH <= y1 {
5875 let mut x = x0.next_multiple_of(step);
5876 while x + IBC_HASH <= x1 {
5877 table
5878 .entry(ibc_hash(plane, width, x, y))
5879 .or_default()
5880 .push((x as u32, y as u32));
5881 x += step;
5882 }
5883 y += step;
5884 }
5885}
5886
5887/// Whether `screen`-detected source `y` repeats itself enough to be worth
5888/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
5889/// content appears at some other position, against [`intrabc_pct`]. Returns
5890/// the share as well, for the gate's own print.
5891fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
5892 if true_width < 4 * 64 || true_height < 2 * 64 {
5893 return (false, 0.0);
5894 }
5895 let mut table = std::collections::HashMap::new();
5896 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
5897 let (mut total, mut matched) = (0usize, 0usize);
5898 let mut by = 0;
5899 while by + IBC_HASH <= true_height {
5900 let mut bx = 0;
5901 while bx + IBC_HASH <= true_width {
5902 total += 1;
5903 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
5904 if hits
5905 .iter()
5906 .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by))
5907 {
5908 matched += 1;
5909 }
5910 }
5911 bx += IBC_HASH;
5912 }
5913 by += IBC_HASH;
5914 }
5915 let share = if total == 0 {
5916 0.0
5917 } else {
5918 matched as f64 / total as f64
5919 };
5920 (share * 100.0 >= intrabc_pct() as f64, share)
5921}
5922
5923/// One tile's intrabc search state: a block-hash table over the part of the
5924/// tile's own reconstruction that is already final (whole superblock rows --
5925/// the in-loop filters are off on this frame, so a coded superblock row never
5926/// changes again), plus the last DV chosen, which the RD price uses as its
5927/// predictor estimate.
5928struct Ibc {
5929 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
5930 /// source repeats exactly where a lossily coded reconstruction only
5931 /// nearly does, so an exact-match table over the reconstruction finds
5932 /// almost nothing. The candidate is then SCORED against the
5933 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
5934 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
5935 /// The tile's own luma rect, in samples.
5936 tile: (usize, usize, usize, usize),
5937 /// The DV the previous intrabc block of this tile took -- the *estimate*
5938 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
5939 /// against. The writer computes the true predictor off its own mi grid
5940 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
5941 /// a slightly mispriced candidate, never a wrong bitstream.
5942 last_dv: Option<(i32, i32)>,
5943 /// How many blocks took intrabc, and how many hash lookups found at least
5944 /// one valid candidate -- the gate's own fire counts.
5945 hits: usize,
5946 lookups: usize,
5947 found: usize,
5948}
5949
5950impl Ibc {
5951 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
5952 let mut table = std::collections::HashMap::new();
5953 ibc_index(
5954 &mut table,
5955 source,
5956 width,
5957 (tile.0, tile.1),
5958 (tile.2, tile.3),
5959 );
5960 Self {
5961 table,
5962 tile,
5963 last_dv: None,
5964 hits: 0,
5965 lookups: 0,
5966 found: 0,
5967 }
5968 }
5969
5970 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
5971 /// (1/8 pel), with this lane's own extra restriction on top: the source
5972 /// must lie entirely in a COMPLETED superblock row, which is exactly the
5973 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
5974 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
5975 /// wavefront's own diagonal) are legal and not searched; the upgrade path
5976 /// is to index the current row's finished superblocks too.
5977 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
5978 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
5979 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
5980 return false;
5981 }
5982 let (tx0, ty0, tx1, ty1) = (
5983 self.tile.0 as i32,
5984 self.tile.1 as i32,
5985 self.tile.2 as i32,
5986 self.tile.3 as i32,
5987 );
5988 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
5989 let (w, h) = (w as i32, h as i32);
5990 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
5991 return false;
5992 }
5993 // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
5994 // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
5995 // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
5996 // Counting 64s under a 128 superblock let the search take a source
5997 // from a 64 row the 128 visit order had not reconstructed yet.
5998 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
5999 let delay: i32 = if sb_log2 == 7 {
6000 INTRABC_DELAY_SB64 / 2
6001 } else {
6002 INTRABC_DELAY_SB64
6003 };
6004 let active_sb_row = (y as i32 - ty0) >> sb_log2;
6005 let active_sb_col = (x as i32 - tx0) >> sb_log2;
6006 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
6007 let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
6008 // This lane's own restriction (see the doc comment).
6009 if src_sb_row >= active_sb_row {
6010 return false;
6011 }
6012 let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
6013 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
6014 return false;
6015 }
6016 // libaom's wavefront: only the top-left cone of the frame is legal.
6017 let wf = (1 + delay) * (active_sb_row - src_sb_row);
6018 src_sb_col < active_sb_col - delay + wf
6019 }
6020}
6021
6022/// How many block searches ran, how many found at least one VALID candidate,
6023/// and how many won on rate-distortion -- the hash hit rate a gate prints
6024/// (class `gate-blind-to-feature`: "the search ran" and "the search found
6025/// something" and "the block took it" are three different claims).
6026static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
6027 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
6028
6029impl Drop for Ibc {
6030 fn drop(&mut self) {
6031 for (slot, n) in [self.lookups, self.found, self.hits]
6032 .into_iter()
6033 .enumerate()
6034 {
6035 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
6036 }
6037 }
6038}
6039
6040/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
6041/// its own encode.
6042#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6043pub(crate) fn take_intrabc_search() -> [usize; 3] {
6044 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
6045}
6046
6047/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
6048/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
6049/// infers rather than codes.
6050fn dv_component_bits(diff: i32) -> f64 {
6051 let z = diff.unsigned_abs() as i32 - 1;
6052 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
6053 let class = mv_class_of(z);
6054 bits += symbol_bits(&cdf::MV_CLASS, class);
6055 let local = z - mv_class_base(class);
6056 if class == 0 {
6057 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
6058 } else {
6059 let d = local >> 3;
6060 for i in 0..class {
6061 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
6062 }
6063 }
6064 bits
6065}
6066
6067/// What one block vector costs against `pred`, plus the `skip` and
6068/// `use_intrabc` flags the block carries and the ordinary intra block does
6069/// not pay in this currency.
6070fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
6071 let diff = (dv.0 - pred.0, dv.1 - pred.1);
6072 let joint = match (diff.0 != 0, diff.1 != 0) {
6073 (false, false) => 0,
6074 (false, true) => 1,
6075 (true, false) => 2,
6076 (true, true) => 3,
6077 };
6078 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
6079 if diff.0 != 0 {
6080 bits += dv_component_bits(diff.0);
6081 }
6082 if diff.1 != 0 {
6083 bits += dv_component_bits(diff.1);
6084 }
6085 bits
6086}
6087
6088/// The squared error of copying the `side`-square block at `(sx, sy)` of each
6089/// plane's reconstruction onto the source block at `(x, y)`, luma and both
6090/// chroma planes together -- what an intrabc block's whole (residual-free)
6091/// distortion is.
6092fn ibc_sse(
6093 luma: &Plane,
6094 chroma: &[Plane; 2],
6095 (x, y): (usize, usize),
6096 (sx, sy): (usize, usize),
6097 side: usize,
6098) -> f64 {
6099 // Inside the true frame only, for the reason [`Plane::block_sse`] is
6100 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
6101 // how well it copies the padding.
6102 let mut sse = 0.0f64;
6103 let clip = |whole: usize, inside: usize| match edge_sse() {
6104 true => whole.min(inside),
6105 false => whole,
6106 };
6107 let rows = clip(side, luma.true_height.saturating_sub(y));
6108 let cols = clip(side, luma.true_width.saturating_sub(x));
6109 for row in 0..rows {
6110 let src = &luma.source[(y + row) * luma.width + x..][..cols];
6111 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
6112 for (&s, &r) in src.iter().zip(rec) {
6113 let d = f64::from(i32::from(s) - i32::from(r));
6114 sse += d * d;
6115 }
6116 }
6117 let half = side / 2;
6118 for plane in chroma {
6119 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
6120 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
6121 for row in 0..rows {
6122 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
6123 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
6124 for (&s, &r) in src.iter().zip(rec) {
6125 let d = f64::from(i32::from(s) - i32::from(r));
6126 sse += d * d;
6127 }
6128 }
6129 }
6130 sse
6131}
6132
6133/// Copies the `side`-square block at `(sx, sy)` of each plane's
6134/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
6135/// since it carries no residual (`skip`). Full-pel in both planes by
6136/// construction ([`intrabc_step`] keeps every DV even), which is what makes
6137/// this a plain copy where decode.rs runs the bilinear kernel over the same
6138/// samples.
6139fn ibc_commit(
6140 luma: &mut Plane,
6141 chroma: &mut [Plane; 2],
6142 (x, y): (usize, usize),
6143 (sx, sy): (usize, usize),
6144 side: usize,
6145) {
6146 for row in 0..side {
6147 let from = (sy + row) * luma.width + sx;
6148 let to = (y + row) * luma.width + x;
6149 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
6150 luma.reconstruction[to..to + side].copy_from_slice(&copied);
6151 }
6152 let half = side / 2;
6153 for plane in chroma {
6154 for row in 0..half {
6155 let from = (sy / 2 + row) * plane.width + sx / 2;
6156 let to = (y / 2 + row) * plane.width + x / 2;
6157 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
6158 plane.reconstruction[to..to + half].copy_from_slice(&copied);
6159 }
6160 plane.commit_ctx_zero(x / 2, y / 2, half);
6161 }
6162 luma.commit_ctx_zero(x, y, side);
6163}
6164
6165/// Searches this block's own DV: every hash-table position whose 16x16 luma
6166/// square equals the block's source square, plus the previous block's DV as a
6167/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
6168/// the winning `(dv, cost)`, or `None` when nothing valid was found.
6169fn ibc_search(
6170 ibc: &mut Ibc,
6171 luma: &Plane,
6172 chroma: &[Plane; 2],
6173 (x, y): (usize, usize),
6174 side: usize,
6175 lambda: f64,
6176) -> Option<((i32, i32), f64, (usize, usize))> {
6177 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
6178 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
6179 let consider =
6180 |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
6181 let dv = ((sy as i32 - y as i32) * 8, (sx as i32 - x as i32) * 8);
6182 if !ibc.dv_valid(x, y, side, side, dv) {
6183 return;
6184 }
6185 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
6186 if best.as_ref().is_none_or(|b| cost < b.1) {
6187 *best = Some((dv, cost, (sx, sy)));
6188 }
6189 };
6190 ibc.lookups += 1;
6191 let key = ibc_hash(luma.source, luma.width, x, y);
6192 // The table is filled in raster order, so the entries BEFORE this block's
6193 // own position are exactly the already-coded ones -- and the nearest of
6194 // them costs the fewest DV bits. Walking backwards from the block's own
6195 // slot is what makes the search look up-and-left; taking the newest
6196 // entries outright only ever finds candidates below and to the right,
6197 // every one of which `dv_valid` rejects.
6198 let hits: Vec<(u32, u32)> = ibc
6199 .table
6200 .get(&key)
6201 .map(|h| {
6202 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
6203 h[..end].iter().rev().take(32).copied().collect()
6204 })
6205 .unwrap_or_default();
6206 for (hx, hy) in hits {
6207 consider(&*ibc, hx as usize, hy as usize, &mut best);
6208 }
6209 if let Some(dv) = ibc.last_dv {
6210 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
6211 if sx >= 0 && sy >= 0 {
6212 consider(&*ibc, sx as usize, sy as usize, &mut best);
6213 }
6214 }
6215 if best.is_some() {
6216 ibc.found += 1;
6217 }
6218 best
6219}
6220
6221fn code_square(
6222 luma: &mut Plane,
6223 chroma: &mut [Plane; 2],
6224 (x, y): (usize, usize),
6225 side: usize,
6226 search: &Search,
6227 mode_bits: &[f64; 13],
6228 // The frame header's `tx_mode == TxMode::Select`: the block then searches
6229 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
6230 // transform over its whole side.
6231 tx_select: bool,
6232 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
6233 // header did not set `allow_intrabc`.
6234 ibc: Option<&mut Ibc>,
6235 // Whether this is a KEY frame's block, read only by the split census
6236 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
6237 // which is this lane's whole finding.
6238 census_key: bool,
6239 fctx: &crate::decode::FrameCtx,
6240) -> (BlockCoeffs, f64) {
6241 let (luma_set, chroma_set) = if side == SUPERBLOCK {
6242 // A whole superblock coded as ONE intra block (lane-i64): one
6243 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
6244 // `code_from_prediction` hands back, and one TX_32X32 per chroma
6245 // plane -- the same three sets the key frame writer's
6246 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
6247 // uses (`search_skip_64`).
6248 (TxbSet::Luma64, TxbSet::Chroma32)
6249 } else if side == BLOCK {
6250 (TxbSet::Luma32, TxbSet::Chroma16)
6251 } else if side == 8 {
6252 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
6253 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
6254 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
6255 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
6256 // (this branch is still unreached), so leaving `Chroma8` here would
6257 // silently wire the wrong table the moment one does; `Chroma4` is
6258 // what a real caller needs.
6259 (TxbSet::Luma8, TxbSet::Chroma4)
6260 } else {
6261 (TxbSet::Luma16, TxbSet::Chroma8)
6262 };
6263 let at = At {
6264 x,
6265 y,
6266 side,
6267 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
6268 set: luma_set_for(luma_set, search.screen),
6269 };
6270 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
6271 luma.search_block(at, search, mode_bits, fctx);
6272 let mut luma_tx_types = vec![tx_type];
6273 // The depth search runs on the mode the whole-block transform picked --
6274 // libaom's own ordering, and the reason it costs one extra pass per depth
6275 // rather than one per (mode, depth) pair.
6276 let mut tx_depth = 0u8;
6277 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
6278 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
6279 // pays that zero exactly as a 32x32's depth search makes it pay
6280 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
6281 // below hands the root a symbol for free.
6282 if tx_select && side == SUPERBLOCK {
6283 cost += search.lambda * tx_depth_bits(side, 0);
6284 }
6285 if tx_select && max_tx_depth(side) > 0 {
6286 let mut best = (
6287 cost + search.lambda * tx_depth_bits(side, 0),
6288 0usize,
6289 luma.snapshot(x, y, side),
6290 luma_coeffs,
6291 );
6292 let mut best_types = std::mem::take(&mut luma_tx_types);
6293 // The census wants the flat arm's own (rate, distortion), which
6294 // `search_block` only hands back folded into one cost -- so under the
6295 // env flag alone it is re-coded at depth 0 and the plane restored.
6296 let census_flat = split_census_on().then(|| {
6297 let kept = luma.snapshot(x, y, side);
6298 let (_, sse, bits, _) =
6299 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
6300 luma.restore(x, y, side, &kept);
6301 (bits + tx_depth_bits(side, 0), sse)
6302 });
6303 let mut census_split: Option<(f64, f64)> = None;
6304 for depth in 1..=max_tx_depth(side) {
6305 let (levels, sse, bits, types) =
6306 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
6307 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
6308 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
6309 if census_flat.is_some() {
6310 let c = (bits + tx_depth_bits(side, depth), sse);
6311 if census_split
6312 .is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
6313 {
6314 census_split = Some(c);
6315 }
6316 }
6317 if cost_d < best.0 {
6318 best = (
6319 cost_d,
6320 depth,
6321 luma.snapshot(x, y, side),
6322 coeffs(&levels, side),
6323 );
6324 best_types = types;
6325 }
6326 }
6327 if let (Some(flat), Some(split)) = (census_flat, census_split) {
6328 split_census(0, census_key, side, best.1 > 0, split, flat);
6329 }
6330 luma_tx_types = best_types;
6331 luma.restore(x, y, side, &best.2);
6332 cost = best.0;
6333 tx_depth = best.1 as u8;
6334 luma_coeffs = best.3;
6335 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6336 }
6337 // The palette candidate is priced against the mode the luma search (and
6338 // its transform-depth search) already settled on, so a block only takes
6339 // one when it beats the best ordinary intra coding of the same pixels.
6340 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
6341 // prediction is the colour map, not the DC of its neighbours.
6342 let mut mode = mode;
6343 let mut angle_delta = angle_delta;
6344 let mut palette = None;
6345 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6346 let source: Vec<u8> = (y..y + side)
6347 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
6348 .collect();
6349 let kept = luma.snapshot(x, y, side);
6350 // spec 5.11.50: a block cut by the frame's right/bottom edge codes
6351 // its map over the ON-SCREEN corner only and the decoder replicates
6352 // that outward, so the searched map is folded the same way here --
6353 // the prediction priced, the reconstruction committed and the symbols
6354 // `write_color_index_map` writes are then one and the same map
6355 // (lane-palw).
6356 let on = (
6357 side.min(luma.true_width.saturating_sub(x)),
6358 side.min(luma.true_height.saturating_sub(y)),
6359 );
6360 for mut pal in palette_candidates(&source) {
6361 let n = usize::from(pal.size);
6362 crate::decode::palette_replicate(&mut pal.map, side, side, on);
6363 let prediction: Vec<u8> = pal
6364 .map
6365 .iter()
6366 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
6367 .collect();
6368 let trial = luma.code_from_prediction(
6369 x,
6370 y,
6371 side,
6372 &prediction,
6373 false,
6374 search.base_q_idx,
6375 search.deadzone,
6376 luma_set,
6377 );
6378 let cost_p = trial.sse
6379 + search.lambda
6380 * (trial.bits
6381 + mode_bits[DC_PRED as usize]
6382 + crate::tile::palette_bits(&pal, side, on)
6383 + if tx_select {
6384 tx_depth_bits(side, 0)
6385 } else {
6386 0.0
6387 });
6388 if cost_p < cost {
6389 cost = cost_p;
6390 mode = DC_PRED as u8;
6391 angle_delta = 0;
6392 tx_depth = 0;
6393 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
6394 luma.commit(x, y, side, &trial);
6395 palette = Some(pal);
6396 }
6397 }
6398 if palette.is_none() {
6399 luma.restore(x, y, side, &kept);
6400 }
6401 }
6402
6403 // The five recursive filter-intra modes (spec 5.11.14), priced against
6404 // whatever the mode, transform-depth and palette searches settled on --
6405 // the same "one candidate loop after the incumbent is known" shape the
6406 // palette above uses. A block that takes one is `DC_PRED` with no palette
6407 // by construction (`av1_filter_intra_allowed`), and its luma transform
6408 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
6409 //
6410 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
6411 // depth the ordinary intra search runs, each unit predicting recursively
6412 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
6413 // arm), so a block whose ordinary winner wanted a split transform is
6414 // compared against a filter arm that may split too.
6415 //
6416 // Measured (native BD table, lane-fitu): searching the depths on EVERY
6417 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
6418 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
6419 // locally cheaper reconstruction that the film rows go on to predict from
6420 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
6421 // content is where it pays, and a non-screen frame keeps the depth-0-only
6422 // arm, byte for byte.
6423 let mut filter_intra: Option<u8> = None;
6424 if filter_intra_on()
6425 && palette.is_none()
6426 && let Some(class) = crate::decode::filter_intra_size_class(side)
6427 {
6428 let row = &cdf::FILTER_INTRA[class];
6429 // With the sequence bit on, EVERY `DC_PRED` block without a luma
6430 // palette carries the flag, so the incumbent pays its zero before the
6431 // comparison -- otherwise the candidate is charged a bit the block
6432 // spends either way (class `price-the-narrowing-not-the-table`).
6433 if mode == DC_PRED {
6434 cost += search.lambda * symbol_bits(row, 0);
6435 }
6436 let one_bits = symbol_bits(row, 1);
6437 let kept = luma.snapshot(x, y, side);
6438 let max_depth = if tx_select && search.screen {
6439 max_tx_depth(side)
6440 } else {
6441 0
6442 };
6443 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
6444 for fi in 0..5u8 {
6445 for depth in 0..=max_depth {
6446 // A filter-intra block's units are coded through
6447 // `code_from_prediction`, which is `DCT_DCT` throughout, so
6448 // this arm keeps the empty (all-`DCT_DCT`) type list.
6449 let (levels, sse, bits, _) =
6450 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
6451 let cost_f = sse
6452 + search.lambda
6453 * (bits
6454 + mode_bits[DC_PRED as usize]
6455 + one_bits
6456 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
6457 + if tx_select {
6458 tx_depth_bits(side, depth)
6459 } else {
6460 0.0
6461 });
6462 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
6463 best = Some((
6464 cost_f,
6465 fi,
6466 depth,
6467 luma.snapshot(x, y, side),
6468 coeffs(&levels, side),
6469 ));
6470 }
6471 }
6472 }
6473 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
6474 cost = cost_f;
6475 mode = DC_PRED;
6476 angle_delta = 0;
6477 tx_depth = depth as u8;
6478 luma_coeffs = levels;
6479 luma.restore(x, y, side, &snapshot);
6480 filter_intra = Some(fi);
6481 } else {
6482 luma.restore(x, y, side, &kept);
6483 }
6484 }
6485
6486 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
6487 // planes; what it costs still counts towards the partition decision.
6488 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
6489 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
6490 cost += chroma_cost;
6491
6492 // The intrabc arm is priced against the WHOLE block -- luma and both
6493 // chroma planes, residual-free -- so it is compared after the chroma
6494 // search has added its own cost, not against the luma decision alone.
6495 if let Some(ibc) = ibc {
6496 if let Some((dv, cost_ibc, src)) =
6497 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
6498 {
6499 if cost_ibc < cost {
6500 ibc_commit(luma, chroma, (x, y), src, side);
6501 ibc.last_dv = Some(dv);
6502 ibc.hits += 1;
6503 return (
6504 BlockCoeffs {
6505 skip: true,
6506 dv: Some(dv),
6507 ..BlockCoeffs::default()
6508 },
6509 cost_ibc,
6510 );
6511 }
6512 }
6513 }
6514 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
6515 // (its levels came from `code_from_prediction`), so the searched types
6516 // belong to a block this one no longer is.
6517 if palette.is_some() || filter_intra.is_some() {
6518 luma_tx_types = Vec::new();
6519 }
6520 (
6521 BlockCoeffs {
6522 u,
6523 v,
6524 luma: luma_coeffs,
6525 mode,
6526 uv_mode,
6527 tx_depth,
6528 palette,
6529 palette_uv,
6530 filter_intra,
6531 cfl_alphas,
6532 angle_delta_y: angle_delta as i8,
6533 luma_tx_types,
6534 ..BlockCoeffs::default()
6535 },
6536 cost,
6537 )
6538}
6539
6540/// The chroma modes the search offers, and the only ones it may offer: each
6541/// predicts from the row directly above and the column directly to the left
6542/// and nothing further, so none of them needs the above-right/below-left
6543/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
6544/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
6545/// reconstruction and its own alpha syntax; both are left out here.
6546const CHROMA_MODES: [u8; 7] = [
6547 DC_PRED,
6548 V_PRED,
6549 H_PRED,
6550 SMOOTH_PRED,
6551 SMOOTH_V_PRED,
6552 SMOOTH_H_PRED,
6553 PAETH_PRED,
6554];
6555
6556/// The thirteen intra mode names, for the chroma fire count's print.
6557#[cfg(test)]
6558const UV_MODE_NAMES: [&str; 14] = [
6559 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", "SMOOTH_H",
6560 "PAETH", "CFL",
6561];
6562
6563/// How many blocks each chroma mode has won, indexed by the mode itself --
6564/// the fire count that says whether the search below reaches its candidates
6565/// at all (the `gate-blind-to-feature` class), printed once per gate run.
6566static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
6567 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
6568
6569/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
6570/// won, summed over both chroma planes -- the alpha histogram the gate prints
6571/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
6572/// magnitude only is a search that never left its first candidate).
6573static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
6574 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
6575
6576/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
6577/// zero on a CfL block", `1..=16` the magnitudes.
6578#[cfg(test)]
6579pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
6580 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6581}
6582
6583/// How many directional luma blocks won at each `angle_delta_y`, indexed
6584/// `delta + 3` -- the histogram that says whether the refinement below ever
6585/// leaves zero (`gate-blind-to-feature`).
6586static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
6587 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
6588
6589/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
6590#[cfg(test)]
6591pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
6592 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
6593}
6594
6595/// Whether the luma search refines a directional winner's `angle_delta_y`
6596/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
6597fn angle_delta_on() -> bool {
6598 static ENV: std::sync::LazyLock<Option<bool>> =
6599 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0"));
6600 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
6601}
6602
6603/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
6604/// switches it off, which is how the lane measured its own on/off pair).
6605fn cfl_on() -> bool {
6606 static ENV: std::sync::LazyLock<Option<bool>> =
6607 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0"));
6608 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
6609}
6610
6611/// Whether the intra search offers the five recursive filter-intra modes at
6612/// all, and with them whether the sequence header sets `enable_filter_intra`
6613/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
6614/// its own on/off pair -- and how every byte pin written before it still
6615/// reproduces). It is also a speed lever: on at preset 0, off above it.
6616// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
6617// it off for the whole process (a sequence-header field, so it cannot change
6618// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
6619// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
6620// this workspace.
6621
6622/// Whether a sequence codes 128x128 superblocks when the environment says
6623/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
6624/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
6625/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
6626/// 128x128 block in it every row of the native BD gate is down or flat on
6627/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
6628///
6629/// | row | 64 superblocks | 128 + the 128 root |
6630/// |---|---|---|
6631/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
6632/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
6633/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
6634/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
6635/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
6636///
6637/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
6638/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
6639///
6640/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
6641/// off (the delta_q unit at the 128 superblock, the superblock size travelling
6642/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
6643/// predictor and wavefront, and seven test harnesses that handed the encoder a
6644/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
6645pub(crate) const SB128_DEFAULT: bool = true;
6646
6647/// Whether this process's sequences code 128x128 superblocks. An ENCODER
6648/// knob (like `speed::SPEED`), never read by a decode: read through a
6649/// process-global (not a thread-local) because the tile writers run on
6650/// worker threads; `2` is "the environment has not been read yet".
6651static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
6652
6653/// Whether this process's sequences code 128x128 superblocks.
6654pub(crate) fn sb128_on() -> bool {
6655 use std::sync::atomic::Ordering::Relaxed;
6656 match ENC_SB128.load(Relaxed) {
6657 2 => {
6658 let on = crate::envflags::var("EC_AV1_SB128")
6659 .ok()
6660 .map_or(SB128_DEFAULT, |v| v != "0");
6661 ENC_SB128.store(u8::from(on), Relaxed);
6662 on
6663 }
6664 v => v == 1,
6665 }
6666}
6667
6668/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
6669/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
6670/// exactly like the speed-preset gates.
6671#[cfg(test)]
6672pub(crate) fn force_sb128(on: bool) {
6673 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
6674}
6675
6676/// The luma loop-restoration unit size this sequence codes: a 128 superblock
6677/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
6678/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
6679/// 128), which is the one filter parameter the superblock size moves.
6680pub(crate) fn lr_unit() -> u32 {
6681 if sb128_on() { 128 } else { 64 }
6682}
6683
6684pub(crate) fn filter_intra_on() -> bool {
6685 #[cfg(test)]
6686 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
6687 return forced;
6688 }
6689 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6690 crate::envflags::var("EC_AV1_FILTER_INTRA")
6691 .ok()
6692 .map(|v| v != "0")
6693 });
6694 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
6695}
6696
6697/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
6698/// to its own encode.
6699#[cfg(test)]
6700pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
6701 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6702}
6703
6704/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
6705/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
6706/// Returns each plane's levels, the mode, and what the pair cost (squared
6707/// error plus lambda times bits, the same currency the luma search speaks).
6708///
6709/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
6710/// which is what the luma mode decision was taken against, so what a
6711/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
6712/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
6713/// writer then has to code.
6714#[allow(clippy::too_many_arguments)]
6715/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
6716/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
6717/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
6718/// trials all seven, as before this lever.
6719///
6720/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
6721/// the search's largest trial population by far -- seven modes times two
6722/// planes for every intra block, against 3.7 luma trials -- and the RD
6723/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
6724/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
6725fn chroma_top_k() -> Option<usize> {
6726 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
6727 crate::envflags::var("EC_AV1_CHROMA_K")
6728 .ok()
6729 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
6730 });
6731 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
6732}
6733
6734/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
6735/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
6736/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
6737/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
6738/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
6739/// BD swings by about a point in either direction as near-tie chroma modes
6740/// flip, which is the measurement's own sensitivity, not a trend: nothing
6741/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
6742/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
6743/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
6744/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
6745pub(crate) const CHROMA_TOP_K: Option<usize> = None;
6746
6747fn search_chroma(
6748 chroma: &mut [Plane; 2],
6749 // The luma plane's RECONSTRUCTION under this block, already committed by
6750 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
6751 luma: &Plane,
6752 (x, y): (usize, usize),
6753 side: usize,
6754 set: TxbSet,
6755 search: &Search,
6756 luma_mode: u8,
6757 fctx: &crate::decode::FrameCtx,
6758) -> (
6759 [Vec<Coeff>; 2],
6760 u8,
6761 f64,
6762 Option<crate::tile::PaletteUv>,
6763 Option<(i32, i32)>,
6764) {
6765 let at = At {
6766 x: x / 2,
6767 y: y / 2,
6768 side: side / 2,
6769 reach: Reach::none(),
6770 set,
6771 };
6772 // The census's cheap proxy for a chroma mode: the SAD of its prediction
6773 // summed over both planes, ranked by the same rule the luma histogram
6774 // uses. Only built under `EC_AV1_CENSUS`.
6775 // The SAD of each mode's prediction, summed over both planes -- the
6776 // census's ranking rule, and what [`chroma_top_k`] prunes by.
6777 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
6778 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6779 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6780 u.iter()
6781 .zip(v.iter())
6782 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
6783 .collect()
6784 };
6785 let modes: Vec<u8> = match chroma_top_k() {
6786 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
6787 _ => CHROMA_MODES.to_vec(),
6788 };
6789 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
6790 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
6791 let ranking: Vec<(f64, u8)> = if census_on() {
6792 sad_scores(chroma)
6793 } else {
6794 Vec::new()
6795 };
6796 census_add(2, 1);
6797 census_add(3, modes.len());
6798 let mut best: Option<(f64, u8, Trial, Trial)> = None;
6799 for mode in modes {
6800 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
6801 if (V_PRED..=D67_PRED).contains(&mode) {
6802 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
6803 }
6804 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
6805 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
6806 // chroma of a 64x64 block is `DCT_DCT` whatever
6807 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
6808 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
6809 // points.
6810 let tx_type = if at.side >= 32 {
6811 TxType::DctDct
6812 } else {
6813 crate::decode::default_intra_tx_type(mode)
6814 };
6815 let u = chroma[0].trial_typed(
6816 at,
6817 mode,
6818 0,
6819 search.base_q_idx,
6820 search.deadzone,
6821 tx_type,
6822 fctx,
6823 );
6824 let v = chroma[1].trial_typed(
6825 at,
6826 mode,
6827 0,
6828 search.base_q_idx,
6829 search.deadzone,
6830 tx_type,
6831 fctx,
6832 );
6833 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
6834 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
6835 best = Some((cost, mode, u, v));
6836 }
6837 }
6838 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
6839 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
6840 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
6841 // what keeps `u_colors` ascending and distinct the way
6842 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
6843 // each cluster's own mean, since the colour-index map is SHARED by the
6844 // two planes. Priced against the best ordinary chroma mode above, so a
6845 // block only takes one when it beats it; a palette block's chroma mode is
6846 // `UV_DC_PRED` by construction.
6847 let mut palette_uv = None;
6848 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6849 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
6850 let plane_source = |p: &Plane| -> Vec<u8> {
6851 (at.y..at.y + at.side)
6852 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
6853 .collect()
6854 };
6855 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
6856 // The luma on-screen extent carried into this plane exactly as the
6857 // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
6858 let on_uv = crate::decode::palette_onscreen_uv(
6859 (side, side),
6860 (
6861 side.min(luma.true_width.saturating_sub(x)),
6862 side.min(luma.true_height.saturating_sub(y)),
6863 ),
6864 (at.side, at.side),
6865 // The encoder writes 4:2:0 only (`palette_uv_side` above).
6866 (1, 1),
6867 );
6868 for mut pal in palette_candidates(&u_source) {
6869 let n = usize::from(pal.size);
6870 crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
6871 // V's base colour per cluster: the mean of the samples the shared
6872 // map assigns to it (an empty cluster cannot happen -- every
6873 // colour `palette_candidates` returns is some pixel's nearest).
6874 let mut sums = [0u32; 8];
6875 let mut counts = [0u32; 8];
6876 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
6877 let k = usize::from(i).min(n - 1);
6878 sums[k] += u32::from(sample);
6879 counts[k] += 1;
6880 }
6881 let mut v_colors = [0u16; 8];
6882 for k in 0..n {
6883 v_colors[k] = if counts[k] > 0 {
6884 ((sums[k] + counts[k] / 2) / counts[k]) as u16
6885 } else {
6886 0
6887 };
6888 }
6889 let candidate = crate::tile::PaletteUv {
6890 size: pal.size,
6891 u_colors: pal.colors,
6892 v_colors,
6893 map: pal.map,
6894 };
6895 let predict = |colors: &[u16; 8]| -> Vec<u8> {
6896 candidate
6897 .map
6898 .iter()
6899 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
6900 .collect()
6901 };
6902 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
6903 let u_trial = chroma[0].code_from_prediction(
6904 at.x,
6905 at.y,
6906 at.side,
6907 &pu,
6908 false,
6909 search.base_q_idx,
6910 search.deadzone,
6911 set,
6912 );
6913 let v_trial = chroma[1].code_from_prediction(
6914 at.x,
6915 at.y,
6916 at.side,
6917 &pv,
6918 false,
6919 search.base_q_idx,
6920 search.deadzone,
6921 set,
6922 );
6923 let cost_p = u_trial.sse
6924 + v_trial.sse
6925 + search.lambda
6926 * (u_trial.bits
6927 + v_trial.bits
6928 + crate::tile::palette_uv_bits(&candidate, side, on_uv));
6929 if cost_p < cost {
6930 cost = cost_p;
6931 mode = DC_PRED;
6932 u = u_trial;
6933 v = v_trial;
6934 palette_uv = Some(candidate);
6935 }
6936 }
6937 }
6938 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
6939 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
6940 // nudges every sample by `alpha_q3` times the block's subsampled,
6941 // average-subtracted luma reconstruction. Offered only where
6942 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
6943 // and priced against the best ordinary chroma mode above, palette
6944 // included, so a block only takes it when it beats both.
6945 let mut cfl_alphas = None;
6946 if side <= 32 && cfl_on() {
6947 // The AC signal, through the decoder's own
6948 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
6949 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
6950 i32::from(luma.reconstruction[ly * luma.width + lx])
6951 });
6952 let dc_prediction = |plane: &Plane| -> Vec<u8> {
6953 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
6954 let (above, left, corner) =
6955 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
6956 let mut prediction = vec![0u8; at.side * at.side];
6957 intra_predict_u8(
6958 DC_PRED,
6959 0,
6960 above,
6961 left,
6962 corner,
6963 at.side,
6964 at.side,
6965 false,
6966 false,
6967 &mut prediction,
6968 fctx,
6969 );
6970 prediction
6971 };
6972 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
6973 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
6974 // add the residual -- which is what [`Plane::code_from_prediction`]
6975 // does with what this returns.
6976 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
6977 base.iter()
6978 .zip(ac.iter())
6979 .map(|(&b, &a)| {
6980 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
6981 })
6982 .collect()
6983 };
6984 // The least-squares alpha, then its two neighbours: minimising
6985 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
6986 // dot-product ratio, and the quantised optimum is one of the two
6987 // integers around it (the clamp and the Q6 rounding are what the SSE
6988 // check below re-decides). libaom sweeps all sixteen magnitudes under
6989 // full RD; three predictions per plane buy nearly the same alpha for a
6990 // thirtieth of the search.
6991 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
6992 let (mut num, mut den) = (0.0f64, 0.0f64);
6993 for row in 0..at.side {
6994 for col in 0..at.side {
6995 let i = row * at.side + col;
6996 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
6997 - f64::from(base[i]);
6998 num += d * f64::from(ac[i]);
6999 den += f64::from(ac[i]) * f64::from(ac[i]);
7000 }
7001 }
7002 if den == 0.0 {
7003 return 0;
7004 }
7005 let ideal = 64.0 * num / den;
7006 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
7007 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
7008 let alpha = alpha.clamp(-16, 16) as i32;
7009 if alpha == 0 {
7010 continue;
7011 }
7012 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
7013 if sse < best.0 {
7014 best = (sse, alpha);
7015 }
7016 }
7017 best.1
7018 };
7019 let picked = [
7020 pick_alpha(&chroma[0], &bases[0]),
7021 pick_alpha(&chroma[1], &bases[1]),
7022 ];
7023 if picked != [0, 0] {
7024 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
7025 let trial = |plane_idx: usize, alpha: i32| -> Trial {
7026 let prediction = if alpha == 0 {
7027 bases[plane_idx].clone()
7028 } else {
7029 apply(&bases[plane_idx], alpha)
7030 };
7031 chroma[plane_idx].code_from_prediction(
7032 at.x,
7033 at.y,
7034 at.side,
7035 &prediction,
7036 false,
7037 search.base_q_idx,
7038 search.deadzone,
7039 set,
7040 )
7041 };
7042 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
7043 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
7044 let combos: [(i32, i32); 3] = [(picked[0], picked[1]), (picked[0], 0), (0, picked[1])];
7045 for &(alpha_u, alpha_v) in &combos {
7046 if (alpha_u, alpha_v) == (0, 0) {
7047 continue;
7048 }
7049 let cu = trial(0, alpha_u);
7050 let cv = trial(1, alpha_v);
7051 let bits =
7052 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
7053 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
7054 if cost_cfl < cost {
7055 cost = cost_cfl;
7056 mode = crate::tile::UV_CFL_PRED as u8;
7057 u = cu;
7058 v = cv;
7059 palette_uv = None;
7060 cfl_alphas = Some((alpha_u, alpha_v));
7061 }
7062 }
7063 }
7064 }
7065 if let Some((alpha_u, alpha_v)) = cfl_alphas {
7066 for alpha in [alpha_u, alpha_v] {
7067 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
7068 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7069 }
7070 }
7071 if census_on() {
7072 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
7073 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7074 }
7075 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7076 chroma[0].commit(at.x, at.y, at.side, &u);
7077 chroma[1].commit(at.x, at.y, at.side, &v);
7078 (
7079 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
7080 mode,
7081 cost,
7082 palette_uv,
7083 cfl_alphas,
7084 )
7085}
7086
7087/// Codes one leaf of a straddling quadrant as whichever costs least of intra
7088/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
7089/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
7090/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
7091/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
7092/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
7093/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
7094/// attempted here: these leaves only ever fill the sliver of real content a
7095/// true edge lands in the middle of a larger block, not a leaf worth a full
7096/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
7097/// (see `write_inter_frame_leaf`'s doc comment).
7098#[allow(clippy::too_many_arguments)]
7099/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
7100/// as [`code_square_inter`] wants them: empty on a frame that codes no
7101/// `reference_select`, or when the leaf compound candidates are switched off.
7102/// One helper because THREE leaf call sites need it -- the split quadrants
7103/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
7104/// `&[]` and so coded no compound block anywhere along the frame's true edge.
7105#[allow(clippy::too_many_arguments)]
7106fn leaf_compound_stacks<'a>(
7107 grid: &MiGrid,
7108 mi_row: usize,
7109 mi_col: usize,
7110 bw4: usize,
7111 bh4: usize,
7112 mi_cols: usize,
7113 mi_rows: usize,
7114 reference_select: bool,
7115 golden: Option<&'a Picture>,
7116 altref: Option<&'a Picture>,
7117) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
7118 if !(reference_select && leaf_compound()) {
7119 return Vec::new();
7120 }
7121 [
7122 (crate::mvstack::GOLDEN_FRAME, golden),
7123 (crate::mvstack::ALTREF_FRAME, altref),
7124 ]
7125 .into_iter()
7126 .filter_map(|(r, pic)| {
7127 pic.map(|p| {
7128 (
7129 r,
7130 p,
7131 crate::mvstack::find_mv_stack_compound(
7132 grid,
7133 mi_row,
7134 mi_col,
7135 bw4,
7136 bh4,
7137 (crate::mvstack::LAST_FRAME, r),
7138 mi_cols,
7139 mi_rows,
7140 grid.sign_bias_table(),
7141 &[(0, 0); 7],
7142 None,
7143 ),
7144 )
7145 })
7146 })
7147 .collect()
7148}
7149
7150/// The OBMC prediction of one square single-reference block: this block's own
7151/// translation prediction (`mc::predict`) with every bordering above/left
7152/// neighbour blended into the overlap strips by the DECODER's own plan and
7153/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
7154/// the search prices is what a decoder reconstructs -- never a second
7155/// implementation of the blend. `None` when the block has no overlappable
7156/// neighbour at all (the writer would then code no `motion_mode` symbol) or
7157/// when the plan cannot be built (a neighbour naming a reference this encode
7158/// does not hold).
7159#[allow(clippy::too_many_arguments)]
7160fn obmc_prediction(
7161 grid: &MiGrid,
7162 (mi_row, mi_col): (usize, usize),
7163 (mi_rows, mi_cols): (usize, usize),
7164 (x, y): (usize, usize),
7165 side: usize,
7166 mv: (i32, i32),
7167 refs: &[Option<&Picture>; 8],
7168 // This block's OWN reference planes, luma then both chroma, each as
7169 // (samples, stride, true width, true height).
7170 ref_planes: [(&[u16], usize, usize, usize); 3],
7171 frame_width: usize,
7172 fctx: &crate::decode::FrameCtx,
7173) -> Option<[Vec<u8>; 3]> {
7174 let n4 = side / 4;
7175 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
7176 return None;
7177 }
7178 let refpix = crate::decode::RefPix::ready(*refs);
7179 let plan = crate::decode::obmc_plan(
7180 grid,
7181 &[],
7182 &[],
7183 mi_row,
7184 mi_col,
7185 n4,
7186 n4,
7187 mi_rows,
7188 mi_cols,
7189 side,
7190 side,
7191 side,
7192 crate::decode::ss_x(fctx),
7193 crate::decode::ss_y(fctx),
7194 side / 2,
7195 x,
7196 y,
7197 x / 2,
7198 y / 2,
7199 &refpix,
7200 Some(fctx.interp_filter.get()),
7201 frame_width,
7202 )
7203 .ok()?;
7204 let mut pred = [
7205 vec![0u16; side * side],
7206 vec![0u16; side * side / 4],
7207 vec![0u16; side * side / 4],
7208 ];
7209 for (i, r) in ref_planes.into_iter().enumerate() {
7210 let luma_plane = i == 0;
7211 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
7212 let s = if luma_plane { side } else { side / 2 };
7213 mc::predict(
7214 r.0,
7215 r.1,
7216 r.2,
7217 r.3,
7218 mv_to_q4(px, mv.1, luma_plane),
7219 mv_to_q4(py, mv.0, luma_plane),
7220 s,
7221 s,
7222 &mut pred[i],
7223 fctx,
7224 );
7225 }
7226 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
7227 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
7228 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
7229 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
7230}
7231
7232fn code_square_inter(
7233 luma: &mut Plane,
7234 chroma: &mut [Plane; 2],
7235 (x, y): (usize, usize),
7236 side: usize,
7237 search: &Search,
7238 mode_bits: &[f64; 13],
7239 reference: &Picture,
7240 stack: &MvStack,
7241 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
7242 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
7243 // `reference_select`, and at the straddling call sites).
7244 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
7245 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
7246 // (`record_mi`, in the writer's own coding order) and this leaf's place in
7247 // it -- what the OBMC candidate's eligibility walk and neighbour plan
7248 // read, the same state the tile writer reads when it codes the leaf's
7249 // `motion_mode` symbol.
7250 grid: &MiGrid,
7251 (mi_row, mi_col): (usize, usize),
7252 (mi_rows, mi_cols): (usize, usize),
7253 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
7254 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
7255 refs: &[Option<&Picture>; 8],
7256 fctx: &crate::decode::FrameCtx,
7257) -> (BlockCoeffs, f64) {
7258 // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra
7259 // candidate at all -- `intra_cost` stays at infinity, so every
7260 // comparison below takes an inter candidate and the fallback arm at the
7261 // tail is unreachable. The planes hold what the caller snapshotted until
7262 // the winner commits: the intra trial used to commit here and be
7263 // overwritten by the inter commit, so skipping it changes no committed
7264 // sample, only work.
7265 let (intra_block, intra_cost) = if search.arf_leaf_intra {
7266 code_square(
7267 luma,
7268 chroma,
7269 (x, y),
7270 side,
7271 search,
7272 mode_bits,
7273 tx_select() && tx_select_inter(),
7274 None,
7275 false,
7276 fctx,
7277 )
7278 } else {
7279 arfmode_hit(0);
7280 (BlockCoeffs::default(), f64::INFINITY)
7281 };
7282 let luma_set = if side == 8 {
7283 TxbSet::Luma8Inter
7284 } else {
7285 TxbSet::Luma16Inter
7286 };
7287 let chroma_set = if side == 8 {
7288 TxbSet::Chroma4
7289 } else {
7290 TxbSet::Chroma8
7291 };
7292
7293 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
7294 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
7295 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
7296 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
7297 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
7298 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
7299
7300 let mv = stack.nearest_mv;
7301 let ref_luma = (
7302 &reference.y,
7303 reference.width,
7304 luma.true_width,
7305 luma.true_height,
7306 );
7307 let ref_u = (
7308 &reference.u,
7309 reference.width / 2,
7310 chroma[0].true_width,
7311 chroma[0].true_height,
7312 );
7313 let ref_v = (
7314 &reference.v,
7315 reference.width / 2,
7316 chroma[1].true_width,
7317 chroma[1].true_height,
7318 );
7319 let luma_trial = mc_trial(
7320 luma,
7321 x,
7322 y,
7323 side,
7324 mv,
7325 true,
7326 ref_luma.0,
7327 ref_luma.1,
7328 ref_luma.2,
7329 ref_luma.3,
7330 false,
7331 search.base_q_idx,
7332 search.deadzone,
7333 luma_set,
7334 fctx,
7335 );
7336 let u = mc_trial(
7337 &chroma[0],
7338 x / 2,
7339 y / 2,
7340 side / 2,
7341 mv,
7342 false,
7343 ref_u.0,
7344 ref_u.1,
7345 ref_u.2,
7346 ref_u.3,
7347 false,
7348 search.base_q_idx,
7349 search.deadzone,
7350 chroma_set,
7351 fctx,
7352 );
7353 let v = mc_trial(
7354 &chroma[1],
7355 x / 2,
7356 y / 2,
7357 side / 2,
7358 mv,
7359 false,
7360 ref_v.0,
7361 ref_v.1,
7362 ref_v.2,
7363 ref_v.3,
7364 false,
7365 search.base_q_idx,
7366 search.deadzone,
7367 chroma_set,
7368 fctx,
7369 );
7370 let skip = luma_trial.levels.iter().all(|&l| l == 0)
7371 && u.levels.iter().all(|&l| l == 0)
7372 && v.levels.iter().all(|&l| l == 0);
7373 let inter_cost = luma_trial.sse
7374 + u.sse
7375 + v.sse
7376 + search.lambda
7377 * (skip_bits(skip)
7378 + intra_inter_bits(true)
7379 + single_ref_bits
7380 + mode_bits_inter
7381 + if skip {
7382 0.0
7383 } else {
7384 luma_trial.bits + u.bits + v.bits
7385 });
7386
7387 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
7388 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
7389 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
7390 // scan's own coverage already reached as far) but a real gap at 4-mi
7391 // leaf geometry. r3 ported the extended scan and, while proving it a
7392 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
7393 // `mvstack.rs`), found and fixed a second bug the extended scan's
7394 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
7395 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
7396 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
7397 // regardless of whether it also casts a ref-frame-matching vote) --
7398 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
7399 // branches), which is what made 8-mi geometry a true no-op instead of
7400 // one that only held when every neighbour happened to be inter.
7401 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
7402 // only ever took the stack's NEARESTMV candidate or went intra, so a
7403 // 32x32 block splitting because its four quarters MOVE differently could
7404 // not code the movement it split for. Same candidate `search_inter_block`
7405 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
7406 // a vector the residual syntax can name -- at this leaf's own side.
7407 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
7408 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
7409 // re-price below can hand it back as the winner's own mode info.
7410 let nearest_info = InterInfo {
7411 ref1: None,
7412 mv1: (0, 0),
7413 ref_frame: crate::mvstack::LAST_FRAME,
7414 mode: InterMode::NearestMv,
7415 mv,
7416 ref_mv_idx: 0,
7417 };
7418 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
7419 // syntax, apart from its residual: the OBMC candidate re-prices the same
7420 // syntax against a different prediction, so both sides of that comparison
7421 // carry it.
7422 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
7423 // This leaf's own `NEWMV` vector, kept whether or not it won the
7424 // single-reference comparison: it seeds the compound half-new candidate
7425 // below, exactly as `search_inter_block` seeds its own from the searches
7426 // it already ran.
7427 let mut searched_new: Option<(i32, i32)> = None;
7428 // What that search cost, kept for the second reference's own early-out
7429 // below (`None` when this leaf ran no search at all).
7430 let mut searched_new_cost: Option<f64> = None;
7431 let source_block = luma.source_block(x, y, side);
7432 if leaf_new_mv() {
7433 let (seeds, seed_n) = mv_seeds(stack);
7434 let found = motion::search(
7435 ref_luma.0,
7436 ref_luma.1,
7437 ref_luma.2,
7438 ref_luma.3,
7439 &source_block,
7440 x,
7441 y,
7442 side,
7443 side,
7444 stack.pred_mv,
7445 &seeds[..seed_n],
7446 search.lambda,
7447 fctx,
7448 1,
7449 );
7450 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
7451 searched_new_cost = Some(found.cost);
7452 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
7453 if mv_residual.is_none() {
7454 // lane-newmv: a vector the writer cannot name never reaches RD.
7455 newmv_census_block(
7456 side,
7457 false,
7458 f64::INFINITY,
7459 best.0,
7460 new_mv,
7461 stack.nearest_mv,
7462 0.0,
7463 );
7464 }
7465 if let Some(mv_bits) = mv_residual {
7466 searched_new = Some(new_mv);
7467 // Same reuse as `search_inter_block`: a NEWMV equal to the
7468 // stack's NEARESTMV is the same three trials, already run above.
7469 let (luma_new, u_new, v_new) = if new_mv == mv {
7470 (luma_trial.clone(), u.clone(), v.clone())
7471 } else {
7472 (
7473 mc_trial(
7474 luma,
7475 x,
7476 y,
7477 side,
7478 new_mv,
7479 true,
7480 ref_luma.0,
7481 ref_luma.1,
7482 ref_luma.2,
7483 ref_luma.3,
7484 false,
7485 search.base_q_idx,
7486 search.deadzone,
7487 luma_set,
7488 fctx,
7489 ),
7490 mc_trial(
7491 &chroma[0],
7492 x / 2,
7493 y / 2,
7494 side / 2,
7495 new_mv,
7496 false,
7497 ref_u.0,
7498 ref_u.1,
7499 ref_u.2,
7500 ref_u.3,
7501 false,
7502 search.base_q_idx,
7503 search.deadzone,
7504 chroma_set,
7505 fctx,
7506 ),
7507 mc_trial(
7508 &chroma[1],
7509 x / 2,
7510 y / 2,
7511 side / 2,
7512 new_mv,
7513 false,
7514 ref_v.0,
7515 ref_v.1,
7516 ref_v.2,
7517 ref_v.3,
7518 false,
7519 search.base_q_idx,
7520 search.deadzone,
7521 chroma_set,
7522 fctx,
7523 ),
7524 )
7525 };
7526 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
7527 && u_new.levels.iter().all(|&l| l == 0)
7528 && v_new.levels.iter().all(|&l| l == 0);
7529 let drl_bits = if stack.entries.len() > 1 {
7530 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
7531 } else {
7532 0.0
7533 };
7534 let cost_new = luma_new.sse
7535 + u_new.sse
7536 + v_new.sse
7537 + search.lambda
7538 * (skip_bits(skip_new)
7539 + intra_inter_bits(true)
7540 + single_ref_bits
7541 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7542 + drl_bits
7543 + mv_bits
7544 + mv_rate_surcharge(mv_bits)
7545 + if skip_new {
7546 0.0
7547 } else {
7548 luma_new.bits + u_new.bits + v_new.bits
7549 });
7550 newmv_census_block(
7551 side,
7552 true,
7553 cost_new,
7554 best.0,
7555 new_mv,
7556 stack.nearest_mv,
7557 mv_bits,
7558 );
7559 if cost_new < best.0 {
7560 single_syntax = intra_inter_bits(true)
7561 + single_ref_bits
7562 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7563 + drl_bits
7564 + mv_bits;
7565 best = (
7566 cost_new,
7567 Some((
7568 luma_new,
7569 u_new,
7570 v_new,
7571 skip_new,
7572 InterInfo {
7573 ref1: None,
7574 mv1: (0, 0),
7575 ref_frame: crate::mvstack::LAST_FRAME,
7576 mode: InterMode::NewMv,
7577 mv: new_mv,
7578 ref_mv_idx: 0,
7579 },
7580 )),
7581 );
7582 }
7583 }
7584 }
7585
7586 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
7587 // `search_inter_block` prices for a whole 32x32 block:
7588 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
7589 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
7590 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
7591 // too. Priced with the same static-CDF approximation, plus the
7592 // compound-only syntax the writer emits.
7593 if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() {
7594 // lane-arfmode: arm 4 drops this leaf's compound set (counted once
7595 // per leaf, not once per pair); the single-reference candidates
7596 // above stay.
7597 arfmode_hit(2);
7598 }
7599 for (ref1, g, cstack) in compound
7600 .iter()
7601 .filter(|_| leaf_compound() && search.arf_leaf_compound)
7602 {
7603 let (ref1, g) = (*ref1, *g);
7604 // The whole `comp_mode` + reference-pair tree at the writer's own
7605 // contexts, for THIS pair (lane-ctx).
7606 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
7607 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7608 let mode_bits_of =
7609 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7610 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7611 (
7612 cstack.nearest_mv,
7613 mode_bits_of(0),
7614 InterInfo {
7615 ref_frame: crate::mvstack::LAST_FRAME,
7616 mode: InterMode::NearestNearestMv,
7617 mv: cstack.nearest_mv.0,
7618 mv1: cstack.nearest_mv.1,
7619 ref1: Some(ref1),
7620 ref_mv_idx: 0,
7621 },
7622 ),
7623 (
7624 ((0, 0), (0, 0)),
7625 mode_bits_of(6),
7626 InterInfo {
7627 ref_frame: crate::mvstack::LAST_FRAME,
7628 mode: InterMode::GlobalGlobalMv,
7629 mv: (0, 0),
7630 mv1: (0, 0),
7631 ref1: Some(ref1),
7632 ref_mv_idx: 0,
7633 },
7634 ),
7635 ];
7636 // Every compound MV residual here is priced against compound stack
7637 // entry 0, which is what `assign_compound_mv` predicts from at
7638 // `ref_mv_idx = 0` -- so it is also what the second-reference search
7639 // below seeds from and rounds to, and no candidate it finds can then
7640 // fail `mv_residual_bits`.
7641 let cbase = cstack
7642 .entries
7643 .first()
7644 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
7645 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
7646 // it a leaf could only name a stack vector for the second half, and
7647 // screen capture showed the consequence: every leaf compound block
7648 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
7649 // extra-reference `NEWMV`, when this reference's own
7650 // `NEAREST_NEARESTMV` vector already prices `margin` times better
7651 // than the `LAST` search of this same leaf did -- one candidate
7652 // evaluation standing in for a whole search.
7653 let margin = leaf_second_new_margin();
7654 let mut second_new: Option<(i32, i32)> = None;
7655 if leaf_second_new_mv() {
7656 newmv_census_global(2);
7657 let skip = margin > 0.0
7658 && searched_new_cost.is_some_and(|last| {
7659 motion::cost_at(
7660 &g.y,
7661 g.width,
7662 luma.true_width,
7663 luma.true_height,
7664 &source_block,
7665 x,
7666 y,
7667 side,
7668 side,
7669 cstack.nearest_mv.1,
7670 cbase.1,
7671 search.lambda,
7672 fctx,
7673 ) * margin
7674 <= last
7675 });
7676 if skip {
7677 newmv_census_global(3);
7678 }
7679 if !skip {
7680 let mut seeds = [(0, 0); 4];
7681 let mut seed_n = 1;
7682 for e in cstack.entries.iter().take(3) {
7683 seeds[seed_n] = e.mv1;
7684 seed_n += 1;
7685 }
7686 let found = motion::search(
7687 &g.y,
7688 g.width,
7689 luma.true_width,
7690 luma.true_height,
7691 &source_block,
7692 x,
7693 y,
7694 side,
7695 side,
7696 cbase.1,
7697 &seeds[..seed_n],
7698 search.lambda,
7699 fctx,
7700 ref_distance(ref1),
7701 );
7702 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
7703 }
7704 }
7705 if let Some(new_mv) = searched_new {
7706 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
7707 ccands.push((
7708 (new_mv, cstack.nearest_mv.1),
7709 mode_bits_of(3) + b0,
7710 InterInfo {
7711 ref_frame: crate::mvstack::LAST_FRAME,
7712 mode: InterMode::NewNearestMv,
7713 mv: new_mv,
7714 mv1: cstack.nearest_mv.1,
7715 ref1: Some(ref1),
7716 ref_mv_idx: 0,
7717 },
7718 ));
7719 }
7720 }
7721 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
7722 // searches this leaf ran, each residual priced against `cbase`.
7723 if let Some(mv1) = second_new {
7724 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
7725 ccands.push((
7726 (cstack.nearest_mv.0, mv1),
7727 mode_bits_of(2) + b1,
7728 InterInfo {
7729 ref_frame: crate::mvstack::LAST_FRAME,
7730 mode: InterMode::NearestNewMv,
7731 mv: cstack.nearest_mv.0,
7732 mv1,
7733 ref1: Some(ref1),
7734 ref_mv_idx: 0,
7735 },
7736 ));
7737 if let Some((new_mv, b0)) =
7738 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
7739 {
7740 ccands.push((
7741 (new_mv, mv1),
7742 mode_bits_of(7) + b0 + b1,
7743 InterInfo {
7744 ref_frame: crate::mvstack::LAST_FRAME,
7745 mode: InterMode::NewNewMv,
7746 mv: new_mv,
7747 mv1,
7748 ref1: Some(ref1),
7749 ref_mv_idx: 0,
7750 },
7751 ));
7752 }
7753 }
7754 }
7755 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
7756 ccands.dedup_by_key(|c| c.0);
7757 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
7758 let g_u = (
7759 g.u.as_slice(),
7760 g.width / 2,
7761 chroma[0].true_width,
7762 chroma[0].true_height,
7763 );
7764 let g_v = (
7765 g.v.as_slice(),
7766 g.width / 2,
7767 chroma[1].true_width,
7768 chroma[1].true_height,
7769 );
7770 for (mvs, bits, info) in ccands {
7771 let luma_c = mc_trial_compound(
7772 luma,
7773 x,
7774 y,
7775 side,
7776 mvs,
7777 true,
7778 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7779 g_luma,
7780 search.base_q_idx,
7781 search.deadzone,
7782 luma_set,
7783 fctx,
7784 );
7785 let u_c = mc_trial_compound(
7786 &chroma[0],
7787 x / 2,
7788 y / 2,
7789 side / 2,
7790 mvs,
7791 false,
7792 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7793 g_u,
7794 search.base_q_idx,
7795 search.deadzone,
7796 chroma_set,
7797 fctx,
7798 );
7799 let v_c = mc_trial_compound(
7800 &chroma[1],
7801 x / 2,
7802 y / 2,
7803 side / 2,
7804 mvs,
7805 false,
7806 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7807 g_v,
7808 search.base_q_idx,
7809 search.deadzone,
7810 chroma_set,
7811 fctx,
7812 );
7813 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
7814 && u_c.levels.iter().all(|&l| l == 0)
7815 && v_c.levels.iter().all(|&l| l == 0);
7816 let cost_c = luma_c.sse
7817 + u_c.sse
7818 + v_c.sse
7819 + search.lambda
7820 * (skip_bits(skip_c)
7821 + intra_inter_bits(true)
7822 + bits
7823 + if skip_c {
7824 0.0
7825 } else {
7826 luma_c.bits + u_c.bits + v_c.bits
7827 });
7828 if cost_c < best.0 {
7829 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
7830 }
7831 }
7832 }
7833
7834 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
7835 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
7836 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
7837 // the writer codes no symbol for one. The prediction is the decoder's own
7838 // plan and blend over the neighbours this leaf's `grid` already carries
7839 // (published by `record_mi` in the writer's coding order), so the
7840 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
7841 // offered this only at 32x32, which is not where libaom cashes its OBMC
7842 // gain.
7843 let mut motion_won = 0u8;
7844 let single = match &best.1 {
7845 None => Some(nearest_info),
7846 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
7847 Some(_) => None,
7848 };
7849 if let Some(info) = single.filter(|i| {
7850 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
7851 && i.ref_frame == crate::mvstack::LAST_FRAME
7852 }) {
7853 let planes = [
7854 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7855 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7856 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7857 ];
7858 // Which alphabet this block's writer will code the symbol against
7859 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
7860 // 3-symbol one only under `allow_warped_motion` and at least one warp
7861 // sample. Mirrored here so the candidates are priced against the
7862 // table the tile really narrows.
7863 let warp_alphabet = warp_on()
7864 && crate::decode::num_proj_ref(
7865 grid,
7866 mi_row,
7867 mi_col,
7868 side / 4,
7869 side / 4,
7870 mi_cols,
7871 mi_rows,
7872 info.ref_frame,
7873 fctx,
7874 ) >= 1;
7875 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
7876 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
7877 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
7878 if let Some(pred) = obmc_prediction(
7879 grid,
7880 (mi_row, mi_col),
7881 (mi_rows, mi_cols),
7882 (x, y),
7883 side,
7884 info.mv,
7885 refs,
7886 planes,
7887 reference.width,
7888 fctx,
7889 ) {
7890 candidates.push((1, pred));
7891 }
7892 }
7893 if warp_alphabet {
7894 if let Some(pred) = warp_prediction(
7895 grid,
7896 (mi_row, mi_col),
7897 (mi_rows, mi_cols),
7898 (x, y),
7899 side,
7900 info.mv,
7901 info.ref_frame,
7902 planes,
7903 fctx,
7904 ) {
7905 candidates.push((2, pred));
7906 }
7907 }
7908 for (motion, pred) in candidates {
7909 let luma_o = luma.code_from_prediction(
7910 x,
7911 y,
7912 side,
7913 &pred[0],
7914 false,
7915 search.base_q_idx,
7916 search.deadzone,
7917 luma_set,
7918 );
7919 let u_o = chroma[0].code_from_prediction(
7920 x / 2,
7921 y / 2,
7922 side / 2,
7923 &pred[1],
7924 false,
7925 search.base_q_idx,
7926 search.deadzone,
7927 chroma_set,
7928 );
7929 let v_o = chroma[1].code_from_prediction(
7930 x / 2,
7931 y / 2,
7932 side / 2,
7933 &pred[2],
7934 false,
7935 search.base_q_idx,
7936 search.deadzone,
7937 chroma_set,
7938 );
7939 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
7940 && u_o.levels.iter().all(|&l| l == 0)
7941 && v_o.levels.iter().all(|&l| l == 0);
7942 let cost_o = luma_o.sse
7943 + u_o.sse
7944 + v_o.sse
7945 + search.lambda
7946 * (skip_bits(skip_o)
7947 + single_syntax
7948 + mm(motion)
7949 + if skip_o {
7950 0.0
7951 } else {
7952 luma_o.bits + u_o.bits + v_o.bits
7953 });
7954 // The incumbent pays the motion_mode symbol IT would code, so
7955 // both sides of the comparison carry that syntax.
7956 if cost_o < best.0 + search.lambda * mm(motion_won) {
7957 motion_won = motion;
7958 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
7959 }
7960 }
7961 }
7962
7963 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
7964 if cost < intra_cost {
7965 // A compound winner commits the flat trial it was priced from:
7966 // `commit_inter_luma`'s var-tx trial set is single-reference
7967 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
7968 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
7969 // predicting each half-side trial from BOTH references, verified
7970 // byte-identical to this when its split is disabled) and MEASURED
7971 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
7972 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
7973 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
7974 // compound block's residual is small enough that the four extra
7975 // per-unit txb_skip/eob symbols cost more ladder bytes than this
7976 // encoder's static-CDF estimate prices them at, so the local RD
7977 // win does not convert. lane-av1txbits REBUILT it on top of a
7978 // search that prices against the tables the frame is really
7979 // written with (`tile::arm_pricing_cdfs`, the estimate error on
7980 // these very blocks measured down from +31% to +3%) and measured
7981 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
7982 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
7983 // same build without it. The static-CDF estimate was NOT what
7984 // held the compound var-tx trial back. The flat trial stays.
7985 // An OBMC winner commits the flat trial too: `commit_inter_luma`
7986 // re-predicts each var-tx unit by plain translation, which is not
7987 // the prediction this candidate was priced from.
7988 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
7989 // 0.05 (both rejections above were measured at 0.1, the weight
7990 // the lambda lane showed was 2x too heavy): a compound winner is
7991 // offered the same var-tx split, its units predicted from BOTH
7992 // references (`mc_trial_compound`). RE-MEASURED native: film
7993 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
7994 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
7995 // one row 0.2 down, two flat, short of the two-down-one-flat keep
7996 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
7997 // rather than change the default on a single 0.2 row. It fires:
7998 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
7999 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
8000 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
8001 // 1.3/1.2 down there, which is where the upgrade path is if this
8002 // is picked up again.
8003 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
8004 refs[r as usize].map(|g| {
8005 (
8006 info.mv1,
8007 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
8008 )
8009 })
8010 });
8011 let (levels, tx_depth, dcost, luma_tx_types) =
8012 if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {
8013 luma.commit(x, y, side, &luma_new);
8014 (luma_new.levels.clone(), 0, 0.0, Vec::new())
8015 } else {
8016 commit_inter_luma(
8017 luma,
8018 (x, y),
8019 side,
8020 info.mv,
8021 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8022 search,
8023 &luma_new,
8024 skip_new,
8025 second,
8026 fctx,
8027 )
8028 };
8029 // lane-txrd: chroma follows the luma type the search just chose.
8030 let [u_new, v_new] = match luma_tx_types.first().copied() {
8031 Some(t) => recode_inter_chroma(
8032 chroma,
8033 (x, y),
8034 side,
8035 info.mv,
8036 [
8037 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
8038 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
8039 ],
8040 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
8041 refs[r as usize].map(|g| {
8042 (
8043 info.mv1,
8044 [
8045 (
8046 g.u.as_slice(),
8047 g.width / 2,
8048 chroma[0].true_width,
8049 chroma[0].true_height,
8050 ),
8051 (
8052 g.v.as_slice(),
8053 g.width / 2,
8054 chroma[1].true_width,
8055 chroma[1].true_height,
8056 ),
8057 ],
8058 )
8059 })
8060 }),
8061 search,
8062 chroma_set,
8063 t,
8064 fctx,
8065 )
8066 .unwrap_or([u_new, v_new]),
8067 None => [u_new, v_new],
8068 };
8069 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
8070 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
8071 return (
8072 BlockCoeffs {
8073 angle_delta_y: 0,
8074 cfl_alphas: None,
8075 filter_intra: None,
8076 luma: coeffs(&levels, side),
8077 u: coeffs(&u_new.levels, side / 2),
8078 v: coeffs(&v_new.levels, side / 2),
8079 mode: DC_PRED as u8,
8080 uv_mode: DC_PRED,
8081 skip: skip_new,
8082 eight: None,
8083 dv: None,
8084 palette: None,
8085 palette_uv: None,
8086 tx_depth,
8087 luma_tx_types,
8088 inter: Some(info),
8089 motion_mode: motion_won,
8090 },
8091 cost + dcost,
8092 );
8093 }
8094 }
8095
8096 census_add(8, 1);
8097 if skip {
8098 census_add(10, 1);
8099 }
8100 if inter_cost >= intra_cost {
8101 census_add(9, 1);
8102 }
8103 if inter_cost < intra_cost {
8104 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
8105 luma,
8106 (x, y),
8107 side,
8108 mv,
8109 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
8110 search,
8111 &luma_trial,
8112 skip,
8113 None,
8114 fctx,
8115 );
8116 // lane-txrd: chroma follows the luma type (this tail's block is
8117 // single-reference `NEARESTMV`, so no compound second half).
8118 let [u, v] = match luma_tx_types.first().copied() {
8119 Some(t) => recode_inter_chroma(
8120 chroma,
8121 (x, y),
8122 side,
8123 mv,
8124 [
8125 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
8126 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
8127 ],
8128 None,
8129 search,
8130 chroma_set,
8131 t,
8132 fctx,
8133 )
8134 .unwrap_or([u, v]),
8135 None => [u, v],
8136 };
8137 chroma[0].commit(x / 2, y / 2, side / 2, &u);
8138 chroma[1].commit(x / 2, y / 2, side / 2, &v);
8139 (
8140 BlockCoeffs {
8141 luma_tx_types,
8142 angle_delta_y: 0,
8143 cfl_alphas: None,
8144 filter_intra: None,
8145 luma: coeffs(&levels, side),
8146 u: coeffs(&u.levels, side / 2),
8147 v: coeffs(&v.levels, side / 2),
8148 mode: DC_PRED as u8,
8149 uv_mode: DC_PRED,
8150 skip,
8151 eight: None,
8152 dv: None,
8153 palette: None,
8154 palette_uv: None,
8155 tx_depth,
8156 motion_mode: 0,
8157 inter: Some(InterInfo {
8158 ref1: None,
8159 mv1: (0, 0),
8160 ref_frame: crate::mvstack::LAST_FRAME,
8161 mode: InterMode::NearestMv,
8162 mv,
8163 ref_mv_idx: 0,
8164 }),
8165 },
8166 inter_cost + dcost,
8167 )
8168 } else {
8169 (intra_block, intra_cost)
8170 }
8171}
8172
8173/// Publishes one coded inter-frame block into the `mi` grid the next block's
8174/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
8175/// block casts no vote but is still a coded cell (see `code_square_inter`'s
8176/// note on `processed_rows`/`processed_cols`).
8177fn record_mi(
8178 grid: &mut MiGrid,
8179 mi_row: usize,
8180 mi_col: usize,
8181 size: u8,
8182 inter: Option<InterInfo>,
8183 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
8184 // the RD pricer the two cells the writer's `skip_ctx` sums.
8185 skip: bool,
8186) {
8187 let info = match inter {
8188 Some(info) => MiInfo {
8189 is_inter: true,
8190 ref_frame: info.ref_frame,
8191 // A COMPOUND block votes with BOTH of its references and both of
8192 // its vectors, exactly as the tile writer publishes it: recording
8193 // a compound block as a single-reference one here left the
8194 // encoder's own grid disagreeing with the writer's from the first
8195 // compound block on, so every later stack it searched against was
8196 // not the stack the decoder derives.
8197 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8198 mv1: mv16(info.mv1),
8199 mv: mv16(info.mv),
8200 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
8201 // side, compound modes 2/3/7 on the other.
8202 is_new_mv: matches!(
8203 info.mode,
8204 InterMode::NewMv
8205 | InterMode::NewNewMv
8206 | InterMode::NearestNewMv
8207 | InterMode::NewNearestMv
8208 ),
8209 size,
8210 size_h: size,
8211 is_global_mv0: false,
8212 is_global_mv1: false,
8213 },
8214 None => MiInfo {
8215 is_inter: false,
8216 ref_frame: -1,
8217 ref_frame1: NO_REF1,
8218 mv1: (0, 0),
8219 mv: (0, 0),
8220 is_new_mv: false,
8221 size,
8222 size_h: size,
8223 is_global_mv0: false,
8224 is_global_mv1: false,
8225 },
8226 };
8227 for dr in 0..usize::from(size) {
8228 for dc in 0..usize::from(size) {
8229 grid.set(mi_row + dr, mi_col + dc, info);
8230 grid.set_skip(mi_row + dr, mi_col + dc, skip);
8231 }
8232 }
8233}
8234
8235/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
8236/// writer's own `write_inter_block_128_rect` makes, so the second half of a
8237/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
8238fn record_mi_rect(
8239 grid: &mut MiGrid,
8240 mi_row: usize,
8241 mi_col: usize,
8242 (w_mi, h_mi): (usize, usize),
8243 inter: Option<InterInfo>,
8244 skip: bool,
8245) {
8246 record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
8247 // `record_mi` stamped the square corner; widen it to the true footprint,
8248 // with the block's own (rect) size fields.
8249 let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
8250 info.size = w_mi as u8;
8251 info.size_h = h_mi as u8;
8252 for dr in 0..h_mi {
8253 for dc in 0..w_mi {
8254 grid.set(mi_row + dr, mi_col + dc, info);
8255 grid.set_skip(mi_row + dr, mi_col + dc, skip);
8256 }
8257 }
8258}
8259
8260/// The reconstructed samples one 32x32 square covers in all three planes, so
8261/// that a partition trial can be undone.
8262/// One square of a plane, row-major, the inverse of [`Plane::restore`].
8263///
8264/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
8265/// which allocated and freed a `Vec` per row of every block it copied --
8266/// `Plane::snapshot` runs once per partition trial.
8267fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
8268 let mut out = vec![0u8; side * side];
8269 for row in 0..side {
8270 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
8271 }
8272 out
8273}
8274
8275fn snapshot(
8276 luma: &Plane,
8277 chroma: &[Plane; 2],
8278 (x, y): (usize, usize),
8279 side: usize,
8280) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
8281 [
8282 luma.snapshot(x, y, side),
8283 chroma[0].snapshot(x / 2, y / 2, side / 2),
8284 chroma[1].snapshot(x / 2, y / 2, side / 2),
8285 ]
8286}
8287
8288/// Puts such a snapshot back.
8289fn restore(
8290 luma: &mut Plane,
8291 chroma: &mut [Plane; 2],
8292 (x, y): (usize, usize),
8293 side: usize,
8294 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
8295) {
8296 luma.restore(x, y, side, &saved[0]);
8297 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
8298 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
8299}
8300
8301/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
8302/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
8303/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
8304/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
8305/// rule shared with the key-frame path, not a second one that could diverge.
8306fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
8307 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
8308 let dc_entry = dc_pos.map(|i| scored.remove(i));
8309 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
8310 scored.truncate(if dc_entry.is_some() {
8311 top_k.saturating_sub(1)
8312 } else {
8313 top_k
8314 });
8315 if let Some(dc_entry) = dc_entry {
8316 scored.push(dc_entry);
8317 }
8318 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
8319 modes.iter().copied().filter(|m| keep.contains(m)).collect()
8320}
8321
8322fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
8323 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
8324 [INTRA_MODE_CTX[usize::from(left_mode)]];
8325 std::array::from_fn(|mode| {
8326 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
8327 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
8328 } else {
8329 0.0
8330 };
8331 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
8332 })
8333}
8334
8335/// What the luma mode search picks between, and under what terms.
8336#[derive(Clone, Copy)]
8337struct Search<'a> {
8338 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
8339 /// luma search then offers a palette candidate beside the intra modes.
8340 screen: bool,
8341 base_q_idx: u8,
8342 deadzone: f64,
8343 lambda: f64,
8344 modes: &'a [u8],
8345 /// How many of `modes` the full RD trial (forward transform, quantize,
8346 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
8347 /// pre-pass on the prediction residual alone plus DC (always kept, since
8348 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
8349 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
8350 /// mode through full RD, unchanged from before this lever.
8351 top_k: Option<usize>,
8352 /// lane-arfmode: the top ARF's offer set ([`crate::speed::ARFMODE`])
8353 /// -- `false` cuts the named candidate group from the whole-32 search
8354 /// ([`search_inter_block`]), the 16x16/8x8 leaf search
8355 /// ([`code_square_inter`]) and the 8x8 split offer, at the top ARF
8356 /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is
8357 /// the pre-lane behaviour: the mid and quarter hidden frames, the shown
8358 /// leaves and the flat path keep intra and compound, and the
8359 /// straddling-edge 8x8s are only mode-gated, never partition-gated.
8360 /// The probe's correction: with the leaf gate ALONE the film A stream
8361 /// was byte-identical to the control -- the ARF's intra area lives at
8362 /// the whole-32 level, so the intra arm must cut it there too.
8363 arf_leaf_intra: bool,
8364 arf_leaf8: bool,
8365 arf_leaf_compound: bool,
8366}
8367
8368/// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what
8369/// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the
8370/// shipped table -- 0, bit-exact with the pre-lane encoder).
8371fn arfmode() -> u8 {
8372 match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
8373 u8::MAX => {}
8374 n => return n,
8375 }
8376 static ENV: std::sync::LazyLock<Option<u8>> = std::sync::LazyLock::new(|| {
8377 crate::envflags::var("EC_AV1_ARFMODE")
8378 .ok()
8379 .and_then(|v| v.parse().ok())
8380 });
8381 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE))
8382}
8383
8384/// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.
8385static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
8386
8387/// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
8388/// process constant ([`crate::envflags`]), so an in-process witness needs
8389/// this to arm the lever.
8390#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
8391pub(crate) fn set_arfmode(n: Option<u8>) {
8392 ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed);
8393}
8394
8395/// How often each armed [`crate::speed::ARFMODE`] arm actually fired since
8396/// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded
8397/// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8
8398/// split the search would have offered and the arm refused, 2 = a top-ARF
8399/// leaf whose compound set was dropped. A green gate over counts of zero
8400/// proves nothing about the lever.
8401static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [
8402 std::sync::atomic::AtomicUsize::new(0),
8403 std::sync::atomic::AtomicUsize::new(0),
8404 std::sync::atomic::AtomicUsize::new(0),
8405];
8406
8407/// Records one such hit.
8408fn arfmode_hit(which: usize) {
8409 ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8410}
8411
8412/// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer
8413/// condition, so the counter only runs when every other prune let the split
8414/// through and the arm alone refuses it.
8415fn arfmode_hit_and_no() -> bool {
8416 arfmode_hit(1);
8417 false
8418}
8419
8420/// Takes (and clears) the counts. `pub` for `examples/enc_probe`, so a
8421/// probe point can print a non-zero engagement count under the env knob
8422/// itself -- the counter the gate BD numbers are read against.
8423pub fn take_arfmode_hits() -> [usize; 3] {
8424 [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
8425}
8426
8427fn prune_top_k() -> Option<usize> {
8428 #[cfg(test)]
8429 {
8430 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
8431 return k;
8432 }
8433 }
8434 let swept = std::env::var("EC_AV1_PRUNE_K")
8435 .ok()
8436 .and_then(|v| v.parse::<usize>().ok());
8437 match swept {
8438 Some(k) if cfg!(test) => Some(k),
8439 _ => crate::speed::at(&crate::speed::PRUNE_K),
8440 }
8441}
8442
8443// A per-thread override [`prune_top_k`] checks first, so one test can sweep
8444// `top_k` in-process without mutating the environment (forbidden here --
8445// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
8446#[cfg(test)]
8447thread_local! {
8448 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
8449 const { std::cell::Cell::new(None) };
8450}
8451
8452#[cfg(test)]
8453fn set_test_top_k_override(value: Option<usize>) {
8454 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
8455}
8456
8457/// The default: unpruned, thirteen full trials per block, same as before this
8458/// lever. Set from the sweep in the lane report if the quality gate clears it.
8459pub(crate) const PRUNE_TOP_K: Option<usize> = None;
8460
8461/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
8462/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
8463/// quality gates were measured separately and may land on different
8464/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
8465/// [`EC_AV1_PRUNE_K`] or the key-frame path.
8466fn prune_top_k_inter() -> Option<usize> {
8467 #[cfg(test)]
8468 {
8469 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
8470 return k;
8471 }
8472 }
8473 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
8474 .ok()
8475 .and_then(|v| v.parse::<usize>().ok());
8476 match swept {
8477 Some(k) if cfg!(test) => Some(k),
8478 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
8479 }
8480}
8481
8482// A per-thread override [`prune_top_k_inter`] checks first, same reason as
8483// [`TEST_TOP_K_OVERRIDE`].
8484#[cfg(test)]
8485thread_local! {
8486 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
8487 const { std::cell::Cell::new(None) };
8488}
8489
8490#[cfg(test)]
8491fn set_test_top_k_override_inter(value: Option<usize>) {
8492 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
8493}
8494
8495/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
8496/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
8497/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
8498/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
8499/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
8500/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
8501/// pruning them costs less quality here.
8502pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
8503
8504// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
8505// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
8506// inter frame's cost can be attributed to a bucket without changing what
8507// the search actually does. Index: 0 = whole-call time inside
8508// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
8509// [`crate::mc::predict`] (every call, from the motion search's own
8510// candidates and from a committed inter block's final prediction alike),
8511// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
8512#[cfg(test)]
8513thread_local! {
8514 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
8515 std::cell::Cell::new(0),
8516 std::cell::Cell::new(0),
8517 std::cell::Cell::new(0),
8518 std::cell::Cell::new(0),
8519 ];
8520}
8521
8522/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
8523/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
8524/// per transform trial and per `mc::predict` call whether or not anyone was
8525/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
8526/// The clock is now read only when [`crate::par::stage_times`] is on, which
8527/// is what prints the breakdown in the first place.
8528#[cfg(test)]
8529pub(crate) fn stage_start() -> Option<std::time::Instant> {
8530 crate::par::stage_times().then(std::time::Instant::now)
8531}
8532
8533#[cfg(test)]
8534pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
8535 if let Some(t) = t {
8536 stage_add(bucket, t.elapsed());
8537 }
8538}
8539
8540#[cfg(test)]
8541pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
8542 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
8543}
8544
8545#[cfg(test)]
8546fn stage_reset() {
8547 crate::par::set_stage_times(true);
8548 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
8549}
8550
8551#[cfg(test)]
8552fn stage_read() -> [std::time::Duration; 4] {
8553 crate::par::set_stage_times(false);
8554 STAGE_NS.with(|c| {
8555 c.each_ref()
8556 .map(|cell| std::time::Duration::from_nanos(cell.get()))
8557 })
8558}
8559
8560/// One mode's coding of one block, before it is committed.
8561#[derive(Clone)]
8562struct Trial {
8563 levels: Vec<i32>,
8564 reconstruction: Vec<u8>,
8565 sse: f64,
8566 bits: f64,
8567}
8568
8569/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
8570/// of a 64-point transform that is actually coded (everything outside it is
8571/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
8572fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
8573 let mut out = vec![0i32; to * to];
8574 for row in 0..to {
8575 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
8576 }
8577 out
8578}
8579
8580/// The non-zero levels of a block, as the tile writer takes them.
8581fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
8582 levels
8583 .iter()
8584 .enumerate()
8585 .filter(|&(_, &level)| level != 0)
8586 .map(|(i, &level)| Coeff {
8587 row: (i / side) as u8,
8588 col: (i % side) as u8,
8589 level,
8590 })
8591 .collect()
8592}
8593
8594thread_local! {
8595 /// The tile grid the next frame is coded with, as `(TileColsLog2,
8596 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
8597 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
8598 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
8599 /// one tile per frame, what every caller that never arms anything gets
8600 /// and what every stream this crate wrote before tiles existed carries.
8601 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
8602}
8603
8604/// Arms this thread's next frame encodes with a tile grid (log2 counts).
8605pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
8606 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
8607}
8608
8609fn armed_tiles() -> (u32, u32) {
8610 let armed = TILE_LOG2.with(std::cell::Cell::get);
8611 if armed != (0, 0) {
8612 return armed;
8613 }
8614 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
8615 // (which codes through `encode_sequence`, not the facade) can measure what
8616 // a tile grid costs without a knob of its own -- same shape as
8617 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
8618 match std::env::var("EC_AV1_TILES").ok() {
8619 Some(v) if cfg!(test) => {
8620 let mut f = v.split(':');
8621 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
8622 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
8623 (cols, rows)
8624 }
8625 _ => armed,
8626 }
8627}
8628
8629/// Codes a frame's `tiles` tiles, each entirely on its own (see
8630/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
8631/// the crate's own pool, and hands back their payloads in tile order plus
8632/// whatever `code` returned for tile `store` -- the CDF state
8633/// `context_update_tile_id` names. The result cannot depend on the thread
8634/// count: each job writes one tile from the frame's own starting tables into
8635/// its own slot.
8636fn write_tiles<F>(
8637 tiles: usize,
8638 store: usize,
8639 code: F,
8640) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
8641where
8642 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
8643{
8644 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
8645 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
8646 let threads = crate::par::tile_threads().min(tiles);
8647 let mut slots: Vec<Slot> = Vec::new();
8648 if threads <= 1 {
8649 for index in 0..tiles {
8650 slots.push(Some(code(index)));
8651 }
8652 } else {
8653 let done: std::sync::Mutex<Vec<Slot>> =
8654 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8655 {
8656 let batch = crate::par::Batch::new("ec-av1-tile");
8657 for (from, to) in crate::par::bands(tiles, threads) {
8658 let done = &done;
8659 let code = &code;
8660 batch.submit(move || {
8661 for index in from..to {
8662 let coded = code(index);
8663 done.lock().expect("tile slots")[index] = Some(coded);
8664 }
8665 });
8666 }
8667 }
8668 slots = done.into_inner().expect("tile slots");
8669 }
8670 let mut out = Vec::with_capacity(tiles);
8671 let mut stored = None;
8672 for (index, slot) in slots.into_iter().enumerate() {
8673 let (bytes, cdfs) = slot.expect("every tile was coded")?;
8674 if index == store {
8675 stored = cdfs;
8676 }
8677 out.push(bytes);
8678 }
8679 Ok((out, stored))
8680}
8681
8682/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
8683/// workers, and returns the results in tile order. The counterpart of
8684/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
8685/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
8686/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
8687/// availability is already tile-relative (`clip_planes_to_tile`,
8688/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
8689/// other tiles have run -- gated by
8690/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
8691/// covers the search as well as the write.
8692///
8693/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
8694/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
8695/// does it for the decoder's filter bands.
8696fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
8697where
8698 T: Send,
8699 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
8700{
8701 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
8702 let threads = crate::par::tile_threads().min(tiles);
8703 if threads <= 1 {
8704 return (0..tiles).map(|index| job(index, fctx)).collect();
8705 }
8706 type Slot<T> = Option<Result<T>>;
8707 let done: std::sync::Mutex<Vec<Slot<T>>> =
8708 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8709 {
8710 let batch = crate::par::Batch::new("ec-av1-tile-search");
8711 for (from, to) in crate::par::bands(tiles, threads) {
8712 let done = &done;
8713 let job = &job;
8714 let ctx = crate::decode::filter_ctx_copy(fctx);
8715 batch.submit(move || {
8716 for index in from..to {
8717 let searched = job(index, &ctx);
8718 done.lock().expect("tile slots")[index] = Some(searched);
8719 }
8720 });
8721 }
8722 }
8723 done.into_inner()
8724 .expect("tile slots")
8725 .into_iter()
8726 .map(|slot| slot.expect("every tile was searched"))
8727 .collect()
8728}
8729
8730/// One tile job's own copy of a plane: the frame's source, a blank
8731/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
8732/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
8733/// of the frame's reconstruction because a tile's prediction never reads a
8734/// sample outside its own rectangle, and every sample inside it is written
8735/// before it is read.
8736fn fresh_plane(
8737 source: &[u8],
8738 width: usize,
8739 height: usize,
8740 true_width: usize,
8741 true_height: usize,
8742) -> Plane<'_> {
8743 Plane {
8744 source,
8745 reconstruction: vec![128; source.len()],
8746 width,
8747 height,
8748 true_width,
8749 true_height,
8750 tile_x0: 0,
8751 tile_y0: 0,
8752 tile_x1: width,
8753 tile_y1: height,
8754 ctx: CoefCtxMap::default(),
8755 }
8756}
8757
8758/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
8759/// the frame's plane, through the [`crate::par::Shared`] every job holds.
8760///
8761/// corner-cut: the disjointness that makes the aliasing sound is the caller's
8762/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
8763/// rectangles partition it -- checked end-to-end by
8764/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
8765/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
8766/// row-range `split_at_mut` plumbing through `Plane`, which would have to
8767/// thread an origin offset through every prediction and transform call site
8768/// for the same bytes.
8769#[allow(unsafe_code)]
8770fn copy_rect(
8771 dst: crate::par::Shared<'_, Vec<u8>>,
8772 src: &[u8],
8773 stride: usize,
8774 x0: usize,
8775 y0: usize,
8776 x1: usize,
8777 y1: usize,
8778) {
8779 // SAFETY: this job touches only its own tile rectangle (see above).
8780 let dst = unsafe { dst.get() };
8781 for y in y0..y1 {
8782 let (a, b) = (y * stride + x0, y * stride + x1);
8783 dst[a..b].copy_from_slice(&src[a..b]);
8784 }
8785}
8786
8787/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
8788/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
8789/// tables the frame stores (spec 7.20), which is what
8790/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
8791/// below publish.
8792fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
8793 ec_av1_syntax::TileInfo {
8794 uniform_spacing: true,
8795 cols: layout.cols(),
8796 rows: layout.rows(),
8797 cols_log2: layout.cols_log2,
8798 rows_log2: layout.rows_log2,
8799 mi_col_starts: layout.mi_col_starts(),
8800 mi_row_starts: layout.mi_row_starts(),
8801 context_update_tile_id: layout.largest_tile() as u32,
8802 tile_size_bytes,
8803 }
8804}
8805
8806/// Clips the three planes' intra edge reads to `rect`, the tile the
8807/// superblock about to be searched belongs to (the encoder side of the
8808/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
8809/// raster order -- which is a linear extension of every tile's own coding
8810/// order, so a block still only ever predicts from samples already
8811/// reconstructed -- and only availability is tile-relative.
8812fn clip_planes_to_tile(
8813 luma: &mut Plane<'_>,
8814 chroma: &mut [Plane<'_>; 2],
8815 rect: crate::tile::TileRect,
8816) {
8817 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8818 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8819 luma.set_tile(x0, y0, x1, y1);
8820 for plane in chroma.iter_mut() {
8821 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
8822 }
8823}
8824
8825/// Encodes one picture as a key frame.
8826///
8827/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
8828/// picks its coefficient CDFs from one of four q contexts by that index.
8829/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
8830/// smaller values trade fidelity for rate.
8831///
8832/// The picture may be any even width and height: the encoder pads it by edge
8833/// replication to a whole number of 32x32 blocks internally, and the frame it
8834/// writes crops back to the picture's own size (`render_width`/
8835/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
8836/// own size, never the padded one.
8837///
8838/// # Errors
8839/// Returns an error when the picture's width or height is zero or odd, or
8840/// when its planes are not 4:2:0 of that size.
8841/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
8842/// stream. The per-frame decode state this needs lives for exactly this call.
8843///
8844/// # Errors
8845/// Returns an error under the same conditions
8846/// [`encode_key_frame_with_modes`] does.
8847pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
8848 encode_key_frame_with_ctx(
8849 picture,
8850 base_q_idx,
8851 deadzone,
8852 &crate::decode::FrameCtx::for_encoder(),
8853 )
8854}
8855
8856/// [`encode_key_frame`] with the per-block intra modes given rather than
8857/// searched.
8858///
8859/// # Errors
8860/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
8861/// is empty, or when a block's coefficients do not fit the coded frame.
8862pub fn encode_key_frame_with_modes(
8863 picture: &Picture,
8864 base_q_idx: u8,
8865 deadzone: f64,
8866 modes: &[u8],
8867) -> Result<Encoded> {
8868 encode_key_frame_with_modes_with_ctx(
8869 picture,
8870 base_q_idx,
8871 deadzone,
8872 modes,
8873 &crate::decode::FrameCtx::for_encoder(),
8874 )
8875}
8876
8877/// Codes `pictures` as one key frame followed by inter frames.
8878///
8879/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
8880/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
8881/// `show_existing_frame` header, so `stream` is in CODING order while
8882/// `frames` stays in display order (`EncodedSequence::coding_order` is the
8883/// map). Screen content codes flat, decided once per sequence by the same
8884/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
8885/// puts every stream back on the flat path for an A/B.
8886///
8887/// # Errors
8888/// Returns an error under the same conditions [`encode_key_frame`] and the
8889/// inter frame path do.
8890pub fn encode_sequence(
8891 pictures: &[Picture],
8892 base_q_idx: u8,
8893 deadzone: f64,
8894) -> Result<EncodedSequence> {
8895 encode_sequence_with_ctx(
8896 pictures,
8897 base_q_idx,
8898 deadzone,
8899 &crate::decode::FrameCtx::for_encoder(),
8900 )
8901}
8902
8903/// Codes one padded picture as a key frame whose HEADER declares
8904/// `frame_width` x `frame_height` -- a frame size the picture's own
8905/// `width`/`height` need not be, and in particular need not be even.
8906///
8907/// [`encode_key_frame`] derives the declared size from the picture and
8908/// refuses an odd one, which is a property of a 4:2:0 SOURCE (an odd luma
8909/// column has no chroma sample of its own to be fed), not of the format: a
8910/// 65-wide 4:2:0 frame is a legal AV1 frame, with
8911/// `ROUND_POWER_OF_TWO(65, 1) = 33` chroma columns (libaom
8912/// `av1_common_plane_width` / `ROUND_POWER_OF_TWO`, `av1/common/
8913/// av1_common_int.h`), and aomenc never emits one only because it rounds the
8914/// coded size down to even before it looks at the picture
8915/// (`av1enc_set_frame_size`). This is the entry that can produce one, and it
8916/// is what the odd-luma coverage fixture is built with: the caller hands
8917/// over a picture already padded to the block grid and names the size to
8918/// declare, so the block walk codes exactly the `mi_cols`/`mi_rows` a
8919/// decoder derives from the declared size (spec `compute_image_size`).
8920///
8921/// # Errors
8922/// Returns an error when `picture` is not a whole number of 32x32 blocks
8923/// ([`Picture::check`]'s own rule), when either declared size is zero or
8924/// larger than the padded picture's, or when the mode search fails -- the
8925/// same conditions [`encode_key_frame`] reports for a malformed picture.
8926pub fn encode_key_frame_at_size(
8927 picture: &Picture,
8928 frame_width: usize,
8929 frame_height: usize,
8930 base_q_idx: u8,
8931 deadzone: f64,
8932) -> Result<Encoded> {
8933 picture.check()?;
8934 if frame_width == 0
8935 || frame_height == 0
8936 || frame_width > picture.width
8937 || frame_height > picture.height
8938 {
8939 return Err(Error::unsupported(
8940 "AV1 encode",
8941 "the declared frame size must be nonzero and fit inside the padded picture",
8942 ));
8943 }
8944 let encoded = encode_key_frame_inner(
8945 picture,
8946 base_q_idx,
8947 deadzone,
8948 &KEY_FRAME_MODES,
8949 split_blocks(),
8950 (frame_width, frame_height),
8951 unspecified_color_config(),
8952 &crate::decode::FrameCtx::for_encoder(),
8953 )?;
8954 Ok(crop_encoded(&encoded, frame_width, frame_height))
8955}
8956
8957pub(crate) fn encode_key_frame_with_ctx(
8958 picture: &Picture,
8959 base_q_idx: u8,
8960 deadzone: f64,
8961 fctx: &crate::decode::FrameCtx,
8962) -> Result<Encoded> {
8963 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
8964}
8965
8966/// Encodes one picture as a key frame, choosing each block's luma mode from
8967/// `modes` alone.
8968///
8969/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
8970/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
8971/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
8972/// uses.
8973///
8974/// # Errors
8975/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
8976/// names a mode [`crate::intra::predict`] does not predict.
8977pub(crate) fn encode_key_frame_with_modes_with_ctx(
8978 picture: &Picture,
8979 base_q_idx: u8,
8980 deadzone: f64,
8981 modes: &[u8],
8982 fctx: &crate::decode::FrameCtx,
8983) -> Result<Encoded> {
8984 picture.check_even()?;
8985 let padded = picture.padded_to(BLOCK);
8986 let encoded = encode_key_frame_inner(
8987 &padded,
8988 base_q_idx,
8989 deadzone,
8990 modes,
8991 split_blocks(),
8992 (picture.width, picture.height),
8993 unspecified_color_config(),
8994 fctx,
8995 )?;
8996 Ok(crop_encoded(&encoded, picture.width, picture.height))
8997}
8998
8999/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
9000/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
9001/// already padded to a whole number of 32x32 blocks; `render` is the real
9002/// (pre-pad) size the frame header tells a decoder to crop back to.
9003pub(crate) fn encode_key_frame_inner(
9004 picture: &Picture,
9005 base_q_idx: u8,
9006 deadzone: f64,
9007 modes: &[u8],
9008 split_blocks: bool,
9009 render: (usize, usize),
9010 color_config: ColorConfig,
9011 fctx: &crate::decode::FrameCtx,
9012) -> Result<Encoded> {
9013 // lane-refs: an intra frame runs no motion compensation, and the
9014 // context is shared across the sequence -- put the kernel back to the
9015 // default so nothing reads the previous inter frame's.
9016 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
9017 picture.check()?;
9018 if modes.is_empty() {
9019 return Err(Error::unsupported(
9020 "AV1 encode",
9021 "a mode search needs at least one mode to choose from",
9022 ));
9023 }
9024 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
9025 return Err(Error::unsupported(
9026 "AV1 encode",
9027 format!("intra mode {bad} is not one the encoder predicts"),
9028 ));
9029 }
9030 // The header carries the frame's true (unpadded) size as `frame_width`/
9031 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
9032 // `mi_rows` derived from that same true size (spec `compute_image_size`).
9033 // `render_width`/`render_height` come out equal to it too, so
9034 // `render_and_frame_size_different` is false and no render_size bits are
9035 // written, mirroring libaom/rav1e: the padded `picture` below is only the
9036 // internal coding surface, never what the header names.
9037 // Screen-content detection runs on the SOURCE luma, before any header is
9038 // built: it decides this sequence's `seq_force_screen_content_tools` (and
9039 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
9040 // this frame's own `allow_screen_content_tools`.
9041 let screen = screen_content(
9042 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
9043 picture.width,
9044 (picture.width).min(render.0),
9045 (picture.height).min(render.1),
9046 );
9047 arm_seq_screen(screen);
9048 // A key frame's writer really does start from the defaults, and a search
9049 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
9050 // disarm, or a key frame's bits would depend on which thread searched it.
9051 crate::tile::arm_pricing_cdfs(None, false);
9052 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
9053 // forces deblocking, CDEF and loop restoration OFF for this frame
9054 // (frame.rs:194/210/252/272), so it is only set when the source repeats
9055 // itself enough for the copied blocks to pay that back
9056 // ([`intrabc_worth_it`]).
9057 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
9058 // grid across every tile while this writer builds one per tile, so a
9059 // multi-tile allow_intrabc frame would predict its DVs off a different
9060 // grid than the decoder does. corner-cut, ceiling named: the upgrade
9061 // path is a frame-scoped grid shared by the tile writers.
9062 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
9063 intrabc_worth_it(
9064 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
9065 picture.width,
9066 picture.width.min(render.0),
9067 picture.height.min(render.1),
9068 )
9069 } else {
9070 (false, 0.0)
9071 };
9072 IBC_SHARE.with(|c| c.set(ibc_share));
9073 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
9074 header.allow_screen_content_tools = screen;
9075 // lane-txi: the wider `tx_type` alphabets, gated by the same content
9076 // rule the type search itself stands behind ([`wide_tx_set`]).
9077 header.reduced_tx_set = !wide_tx_set(screen);
9078 header.allow_intrabc = allow_intrabc;
9079 header.render_width = render.0 as u32;
9080 header.render_height = render.1 as u32;
9081 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
9082 // its luma transform below its own side (`crate::tile::write_luma_select`).
9083 // Set here rather than in `key_frame_headers_colour` so the header
9084 // builders' other callers -- the hand-built tile writers, which code no
9085 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
9086 let tx_select = tx_select();
9087 if tx_select {
9088 header.tx_mode = TxMode::Select;
9089 }
9090 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
9091
9092 // Prediction reads no further than this, in each plane's own units --
9093 // see `Plane::true_width`/`true_height`.
9094 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
9095 // lane-palw: the encoder's own in-process reconstruct reads its palette
9096 // colour-index maps back through `decode::palette_onscreen`, which takes
9097 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
9098 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
9099 // them here so the reconstruct clamps a block cut by the frame edge
9100 // exactly as the writer now does.
9101 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
9102 fctx.seg_mi_dims.set(frame_mi_dims);
9103 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
9104 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
9105 // design (see `intra_predict_u8`'s doc comment), so narrow the source
9106 // once here.
9107 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
9108 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
9109 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
9110 let mut luma = Plane {
9111 source: &picture_y8,
9112 reconstruction: vec![128; picture_y8.len()],
9113 width: picture.width,
9114 height: picture.height,
9115 true_width,
9116 true_height,
9117 tile_x0: 0,
9118 tile_y0: 0,
9119 tile_x1: picture.width,
9120 tile_y1: picture.height,
9121 ctx: CoefCtxMap::default(),
9122 };
9123 let mut chroma = [
9124 Plane {
9125 source: &picture_u8,
9126 reconstruction: vec![128; picture_u8.len()],
9127 width: picture.width / 2,
9128 height: picture.height / 2,
9129 true_width: true_width / 2,
9130 true_height: true_height / 2,
9131 tile_x0: 0,
9132 tile_y0: 0,
9133 tile_x1: picture.width / 2,
9134 tile_y1: picture.height / 2,
9135 ctx: CoefCtxMap::default(),
9136 },
9137 Plane {
9138 source: &picture_v8,
9139 reconstruction: vec![128; picture_v8.len()],
9140 width: picture.width / 2,
9141 height: picture.height / 2,
9142 true_width: true_width / 2,
9143 true_height: true_height / 2,
9144 tile_x0: 0,
9145 tile_y0: 0,
9146 tile_x1: picture.width / 2,
9147 tile_y1: picture.height / 2,
9148 ctx: CoefCtxMap::default(),
9149 },
9150 ];
9151
9152 // The search trades a bit for the squared error it saves, in the units the
9153 // reconstruction is measured in: one step of the quantizer, squared.
9154 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
9155 let search = Search {
9156 base_q_idx,
9157 deadzone,
9158 lambda: lambda_scale() * key_lambda_factor() * step * step,
9159 modes,
9160 top_k: prune_top_k(),
9161 screen,
9162 arf_leaf_intra: true,
9163 arf_leaf8: true,
9164 arf_leaf_compound: true,
9165 };
9166
9167 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
9168 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
9169 // which may be fewer columns/rows than the padded picture has room for
9170 // -- a block whose origin sits past the true bound is not coded at all,
9171 // matching what a decoder derives from `frame_width`/`frame_height` and
9172 // so never visits either.
9173 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9174 let (cols, rows) = (cols as usize, rows as usize);
9175 // The luma mode of the block above and of the block to the left, which is
9176 // what picks the CDF the next block's mode is coded against -- the same
9177 // bookkeeping the tile writer keeps, so that the search is costing the
9178 // symbol the writer will actually write.
9179 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
9180 // because a 32x32 block may be split into four 16x16 ones.
9181 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9182 // This frame's tile grid (one tile unless the facade armed more).
9183 let layout = crate::tile::TileLayout::new(
9184 header.mi_cols,
9185 header.mi_rows,
9186 tile_cols_log2,
9187 tile_rows_log2,
9188 );
9189 header.tile_info = tile_info_of(&layout, 1);
9190 // The filter search re-decodes this frame's tiles; the decoder derives
9191 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
9192 // `mi_row_starts`), which is what makes the writer's rects and the
9193 // reader's the same rects.
9194 let header_tile_info = header.tile_info.clone();
9195 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
9196 // once over the whole frame. Each tile job builds its own reconstruction
9197 // planes and its own `above_mode`/`left_mode` bands, which is also what
9198 // the tile writer reads -- a tile resets its neighbour contexts (spec
9199 // 5.11.1), so a block at a tile's left edge must cost its mode against
9200 // the default context, not against whatever the tile to its west left in
9201 // that row. At one tile the bands are the frame's, exactly as before.
9202 let (frame_width, frame_height) = (picture.width, picture.height);
9203 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
9204 let [cb, cr] = &mut chroma;
9205 let chroma_out = [
9206 crate::par::Shared::new(&mut cb.reconstruction),
9207 crate::par::Shared::new(&mut cr.reconstruction),
9208 ];
9209 let search_tile = |index: usize,
9210 fctx: &crate::decode::FrameCtx|
9211 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
9212 crate::tile::arm_pricing_cdfs(None, false);
9213 let rect = layout.rect(index);
9214 let mut luma = fresh_plane(
9215 &picture_y8,
9216 frame_width,
9217 frame_height,
9218 true_width,
9219 true_height,
9220 );
9221 let mut chroma = [
9222 fresh_plane(
9223 &picture_u8,
9224 frame_width / 2,
9225 frame_height / 2,
9226 true_width / 2,
9227 true_height / 2,
9228 ),
9229 fresh_plane(
9230 &picture_v8,
9231 frame_width / 2,
9232 frame_height / 2,
9233 true_width / 2,
9234 true_height / 2,
9235 ),
9236 ];
9237 clip_planes_to_tile(&mut luma, &mut chroma, rect);
9238 let mut above_mode = vec![DC_PRED; cols * 2];
9239 let mut left_mode = vec![DC_PRED; rows * 2];
9240 let mut ibc = allow_intrabc.then(|| {
9241 Ibc::new(
9242 (
9243 rect.mi_col0 as usize * 4,
9244 rect.mi_row0 as usize * 4,
9245 (rect.mi_col1 as usize * 4).min(true_width),
9246 (rect.mi_row1 as usize * 4).min(true_height),
9247 ),
9248 &picture_y8,
9249 frame_width,
9250 )
9251 });
9252 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
9253 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
9254 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
9255 let mut modes = Vec::with_capacity(4);
9256 // The quadrants of a superblock are coded in the order the decoder
9257 // walks them, which for a 64x64 split into 32x32 blocks is raster
9258 // order among the quadrants that are inside the frame.
9259 let mut blocks = Vec::with_capacity(4);
9260 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
9261 // BEFORE its quadrants (so both start from the same
9262 // reconstruction) and compared against the four of them below --
9263 // the shape the inter frame's own 64 root takes
9264 // (`search_skip_64`). A frame that allows intrabc is refused
9265 // outright ([`I64_ROOT`]) because the quadrant searches below
9266 // carry DV state a discarded trial would desync.
9267 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
9268 // lane-corner LIFTED the two guards this root shipped with: the
9269 // frame no longer has to be a whole number of superblocks, and
9270 // the superblock no longer has to be wholly inside the frame.
9271 // The desync the guards were written for (a 248x152 corner's
9272 // chroma disagreeing three ways) does NOT reproduce at this
9273 // revision -- see
9274 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
9275 // which pins all three planes of the encoder's reconstruction,
9276 // our decoder and ffmpeg on four straddling sizes, three of them
9277 // cut on BOTH axes, with the edge fire count asserted. What the
9278 // guards cost was every key-frame root on an arbitrary export
9279 // size (the `aligned` line switched the whole feature off on, for
9280 // instance, a 1920x792 frame).
9281 let whole_inside =
9282 x64 + SUPERBLOCK <= luma.true_width && y64 + SUPERBLOCK <= luma.true_height;
9283 // lane-corner: and the superblock the true frame edge CUTS
9284 // THROUGH with more than half of each axis still inside, which is
9285 // all AV1 asks of a `PARTITION_NONE` root (spec
9286 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
9287 // key writer's `Superblock::Whole` arm checks) -- the shape the
9288 // inter root already takes ([`b64_edge`]).
9289 let edge_inside = edge_root_enabled()
9290 && crate::tile::has_half(
9291 sb_col as u32 * crate::tile::SB_MI,
9292 crate::tile::SB_MI,
9293 header.mi_cols,
9294 )
9295 && crate::tile::has_half(
9296 sb_row as u32 * crate::tile::SB_MI,
9297 crate::tile::SB_MI,
9298 header.mi_rows,
9299 );
9300 let sb64_legal = i64_root()
9301 && ibc.is_none()
9302 && sb_row * 2 + 1 < rows
9303 && sb_col * 2 + 1 < cols
9304 && (whole_inside || edge_inside);
9305 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
9306 if sb64_legal {
9307 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9308 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
9309 let (c64, r64) = (sb_col * 4, sb_row * 4);
9310 let (block, cost) = code_square(
9311 &mut luma,
9312 &mut chroma,
9313 (x64, y64),
9314 SUPERBLOCK,
9315 &search,
9316 &mode_bits(above_mode[c64], left_mode[r64]),
9317 tx_select,
9318 None,
9319 true,
9320 fctx,
9321 );
9322 let cost =
9323 cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
9324 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
9325 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
9326 sb64 = Some((cost, block, after));
9327 }
9328 // A superblock whose 64x64 trial already codes almost nothing per
9329 // pixel is taken outright and its quadrants are never searched --
9330 // `split_rd_breakout` one size up, at the threshold the inter
9331 // root clamps to ([`b64_breakout_threshold`]), where this lever
9332 // BUYS wall instead of spending it.
9333 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
9334 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
9335 });
9336 // What the four quadrants cost together, including the split
9337 // partition symbol at the superblock level, so the two arms are
9338 // one comparable number.
9339 let mut sb_cost = match sb64 {
9340 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
9341 None => 0.0,
9342 };
9343 for quadrant in 0..if early64 { 0 } else { 4 } {
9344 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
9345 if col >= cols || row >= rows {
9346 continue;
9347 }
9348 let (x, y) = (col * BLOCK, row * BLOCK);
9349 let (c0, r0) = (col * 2, row * 2);
9350 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
9351
9352 // spec `decode_partition`'s hasRows/hasCols recomputed at this
9353 // 32x32 block's own half (see `crate::tile::has_half`): the
9354 // true frame edge can fall inside a quadrant a superblock-level
9355 // check already let through. A quadrant that fails either may
9356 // not be left whole; a 16x16 sub-block that fails either (once
9357 // split) is a leaf this writer has no rectangular transform
9358 // for, so the search must not pick a split that would need one.
9359 let (has_cols32, has_rows32) = (
9360 crate::tile::has_half(
9361 col as u32 * crate::tile::BLOCK_MI,
9362 crate::tile::BLOCK_MI,
9363 header.mi_cols,
9364 ),
9365 crate::tile::has_half(
9366 row as u32 * crate::tile::BLOCK_MI,
9367 crate::tile::BLOCK_MI,
9368 header.mi_rows,
9369 ),
9370 );
9371 let whole_legal = has_cols32 && has_rows32;
9372 // A 16x16 sub-block's own hasCols/hasRows (spec
9373 // `decode_partition`, recomputed at this leaf's own half):
9374 // either axis false is a straddling leaf this writer codes as
9375 // the 8x8 leaves that are inside it
9376 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
9377 // false is the same split with the partition symbol inferred
9378 // rather than coded -- no rectangular transform is needed
9379 // (lane-av1rect).
9380 let sub_half = |sr: usize, sc: usize| {
9381 (
9382 crate::tile::has_half(
9383 sc as u32 * crate::tile::SUB_MI,
9384 crate::tile::SUB_MI,
9385 header.mi_cols,
9386 ),
9387 crate::tile::has_half(
9388 sr as u32 * crate::tile::SUB_MI,
9389 crate::tile::SUB_MI,
9390 header.mi_rows,
9391 ),
9392 )
9393 };
9394 // What the whole 32x32 costs, including the partition symbol
9395 // that says it is not split.
9396 let (whole, mut cost_whole) = code_square(
9397 &mut luma,
9398 &mut chroma,
9399 (x, y),
9400 BLOCK,
9401 &search,
9402 &mode_bits(above_mode[c0], left_mode[r0]),
9403 tx_select,
9404 ibc.as_mut(),
9405 true,
9406 fctx,
9407 );
9408 cost_whole += search.lambda * partition_bits(BLOCK, false);
9409 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
9410
9411 // What four 16x16 blocks cost instead, each searched against
9412 // the reconstruction the ones before it left.
9413 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
9414 let mut split = Vec::with_capacity(4);
9415 let mut cost_split = search.lambda
9416 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
9417 let mut split_modes = Vec::with_capacity(4);
9418 for sub in 0..4 {
9419 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
9420 // Same filter as the writer's `sub_positions` (spec
9421 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
9422 // return): a sub-block whose own origin sits past the
9423 // true frame is never coded, so it must not be searched
9424 // or pushed onto `split` either, or the writer's block
9425 // count will not match what it is prepared to name.
9426 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
9427 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
9428 {
9429 continue;
9430 }
9431 let (has_cols16, has_rows16) = sub_half(sr, sc);
9432 if has_cols16 && has_rows16 {
9433 let (block, cost) = code_square(
9434 &mut luma,
9435 &mut chroma,
9436 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
9437 SUB,
9438 &search,
9439 &mode_bits(above_mode[sc], left_mode[sr]),
9440 tx_select,
9441 ibc.as_mut(),
9442 true,
9443 fctx,
9444 );
9445 cost_split += cost;
9446 split_modes.push(block.mode);
9447 above_mode[sc] = block.mode;
9448 left_mode[sr] = block.mode;
9449 split.push(block);
9450 } else {
9451 // A straddling 16x16: two (or, at a true corner, one)
9452 // 8x8 leaves, in the raster order `write_leaf8`'s
9453 // caller expects. Both leaves cost against the SAME
9454 // enclosing-slot mode context (see
9455 // `crate::tile::write_leaf8`'s doc), and neither
9456 // updates `above_mode`/`left_mode` at this SUB slot --
9457 // the writer never does either, so the search must
9458 // not diverge from what it will actually read next.
9459 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
9460 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
9461 let mut leaves = Vec::with_capacity(2);
9462 for i in 0..4 {
9463 let leaf_x = x_sub + (i % 2) * 8;
9464 let leaf_y = y_sub + (i / 2) * 8;
9465 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
9466 continue;
9467 }
9468 let (leaf, cost) = code_square(
9469 &mut luma,
9470 &mut chroma,
9471 (leaf_x, leaf_y),
9472 8,
9473 &search,
9474 &leaf_mode_bits,
9475 tx_select,
9476 None,
9477 true,
9478 fctx,
9479 );
9480 cost_split += cost;
9481 split_modes.push(leaf.mode);
9482 leaves.push(leaf);
9483 }
9484 split.push(BlockCoeffs {
9485 eight: Some(leaves),
9486 ..BlockCoeffs::default()
9487 });
9488 }
9489 }
9490
9491 // A split whose subs are all whole 16x16 is a real quality
9492 // alternative to `whole`, exactly as before. Through r14, a
9493 // split carrying an 8x8-leaf sub was only ever forced
9494 // (`!whole_legal`), never chosen on cost, because the leaf
9495 // path was not yet proven against a real decoder; r15 proved
9496 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
9497 // the read path (`decode_leaf8`), so leaf8 can now win on
9498 // cost anywhere, same as any other split.
9499 if !whole_legal || (split_blocks && cost_split < cost_whole) {
9500 sb_cost += cost_split;
9501 modes.extend_from_slice(&split_modes);
9502 blocks.push(Quadrant::Split(split));
9503 } else {
9504 sb_cost += cost_whole;
9505 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
9506 for cell in 0..2 {
9507 above_mode[c0 + cell] = whole.mode;
9508 left_mode[r0 + cell] = whole.mode;
9509 }
9510 modes.push(whole.mode);
9511 blocks.push(Quadrant::Whole(whole));
9512 }
9513 }
9514 let index = sb_row * sb_cols + sb_col;
9515 match sb64 {
9516 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
9517 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
9518 for cell in 0..4 {
9519 above_mode[sb_col * 4 + cell] = block.mode;
9520 left_mode[sb_row * 4 + cell] = block.mode;
9521 }
9522 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9523 if !whole_inside {
9524 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9525 }
9526 let mode = block.mode;
9527 coded.push((index, Superblock::Whole(block), vec![mode]));
9528 }
9529 _ => coded.push((index, Superblock::Split(blocks), modes)),
9530 }
9531 }
9532 }
9533 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
9534 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
9535 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
9536 for (&out, tile) in chroma_out.iter().zip(&chroma) {
9537 copy_rect(
9538 out,
9539 &tile.reconstruction,
9540 frame_width / 2,
9541 x0 / 2,
9542 y0 / 2,
9543 x1.div_ceil(2),
9544 y1.div_ceil(2),
9545 );
9546 }
9547 Ok(coded)
9548 };
9549 let searched = search_tiles(layout.count(), fctx, search_tile)?;
9550 // Back into frame raster order: the tile writer indexes `superblocks` by
9551 // the frame's own superblock index, and `modes` is the coding order the
9552 // ablation drivers read.
9553 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> =
9554 (0..sb_cols * sb_rows).map(|_| None).collect();
9555 for (at, superblock, block_modes) in searched.into_iter().flatten() {
9556 in_order[at] = Some((superblock, block_modes));
9557 }
9558 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
9559 let mut modes = Vec::with_capacity(cols * rows);
9560 for slot in in_order {
9561 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
9562 superblocks.push(superblock);
9563 modes.extend_from_slice(&block_modes);
9564 }
9565
9566 #[cfg(test)]
9567 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(
9568 &superblocks,
9569 base_q_idx,
9570 ));
9571 // A key frame always starts from the defaults (`primary_ref_frame` is
9572 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
9573 // set, so what it stores into the slots it refreshes is exactly those
9574 // defaults again (spec 7.20's `started_from` arm) -- the first inter
9575 // frame after it therefore starts from the defaults too.
9576 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
9577 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
9578 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
9579 // from -- `Cdfs::txb` widens every luma set under it.
9580 cdfs.reduced_tx_set = header.reduced_tx_set;
9581 let start_cdfs = CdfSnapshot(cdfs);
9582 // The luma restoration-unit grid this frame's `lr_params` implies
9583 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
9584 // swallowed by the one before it), for the tile writer's own per-unit
9585 // walk.
9586 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
9587 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
9588 // Every tile is coded from this frame's OWN starting tables and leaves
9589 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
9590 // loop-restoration reference and its neighbour contexts), so the tiles
9591 // are independent of each other and of the order they are written in.
9592 let code_tiles = |bits: u8,
9593 sb_cols: usize,
9594 grid: &[u8],
9595 units: &[Option<crate::restoration::WienerInfo>]|
9596 -> Result<Vec<Vec<u8>>> {
9597 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
9598 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
9599 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
9600 crate::tile::arm_sb128(sb128_on());
9601 let mut cdfs = start_cdfs.0.clone();
9602 crate::tile::arm_screen(screen);
9603 crate::tile::arm_frame_mi_dims(frame_mi_dims);
9604 crate::tile::arm_filter_intra(filter_intra_on());
9605 crate::tile::arm_intrabc(allow_intrabc);
9606 crate::tile::arm_pricing_cdfs(None, false);
9607 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
9608 mi_cols,
9609 mi_rows,
9610 base_q_idx,
9611 &superblocks,
9612 tx_select,
9613 &mut cdfs,
9614 layout.rect(index),
9615 )?;
9616 Ok((bytes, None))
9617 })?;
9618 Ok(out)
9619 };
9620 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
9621 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
9622 // the tile just coded back to the decoder under each candidate (see
9623 // `crate::filter_search`), and keep the filtered picture that wins as
9624 // the reconstruction -- what a decoder outputs, and what the next
9625 // frame predicts from.
9626 pick_and_apply_filters(
9627 &mut header,
9628 &mut luma,
9629 &mut chroma,
9630 [&picture_y8, &picture_u8, &picture_v8],
9631 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
9632 // and loop restoration off and codes none of their parameters
9633 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
9634 // the encoder's reconstruction is already what a decoder produces.
9635 !allow_intrabc,
9636 &mut tiles,
9637 search.lambda,
9638 fctx,
9639 // A key frame codes no 128x128 root block (the writer has no intra
9640 // path at that size), so every unit carries its own literal.
9641 &[],
9642 // Every re-code starts from this frame's OWN starting tables, never
9643 // from where the first write left them: the second tile is the same
9644 // symbol sequence plus new ones, so it must adapt from the same
9645 // point the decoder will.
9646 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
9647 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
9648 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
9649 crate::decode::decode_key_frame_tiles_lr(
9650 &payloads,
9651 &header_tile_info,
9652 h.mi_cols,
9653 h.mi_rows,
9654 base_q_idx,
9655 h.frame_width,
9656 h.frame_height,
9657 seq.enable_filter_intra,
9658 cdef,
9659 lf,
9660 tx_select,
9661 h.reduced_tx_set,
9662 h.allow_screen_content_tools,
9663 h.allow_intrabc,
9664 lr,
9665 fctx,
9666 )
9667 },
9668 )?;
9669 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
9670 header.tile_info.tile_size_bytes = tile_size_bytes;
9671 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
9672 let mut stream = temporal_delimiter();
9673 stream.extend_from_slice(&sequence_header_obu(&seq)?);
9674 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
9675
9676 let [u, v] = chroma;
9677 Ok(Encoded {
9678 stream,
9679 modes,
9680 inter_block_share: 0.0,
9681 reconstruction: Picture {
9682 width: luma.width,
9683 height: luma.height,
9684 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9685 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9686 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9687 },
9688 tile,
9689 mi_cols: header.mi_cols,
9690 mi_rows: header.mi_rows,
9691 base_q_idx,
9692 tx_select,
9693 // A key frame codes no inter block, so no motion_mode symbol.
9694 switchable_motion_mode: false,
9695 screen,
9696 reduced_tx_set: header.reduced_tx_set,
9697 next_cdfs: start_cdfs.clone(),
9698 start_cdfs,
9699 loop_filter: header.loop_filter,
9700 cdef: header.cdef,
9701 loop_restoration: header.loop_restoration,
9702 allow_intrabc,
9703 delta: header.delta.clone(),
9704 })
9705}
9706
9707/// Chooses this frame's deblocking levels and CDEF strengths, writes them
9708/// into `header` and
9709/// replaces the frame's own region of the encoder's reconstruction with the
9710/// filtered picture the decoder produced under them
9711/// ([`crate::filter_search::pick_deblock`]).
9712///
9713/// `search == false` leaves the header at level 0 (deblocking off) and the
9714/// reconstruction untouched: the caller's stream is one this crate's own
9715/// decoder cannot read back, so there is nothing to search against.
9716///
9717/// # Errors
9718/// The decoder's own error, when it refuses the tile the encoder just wrote
9719/// -- that is an encoder defect, not a filter one, so it is propagated
9720/// rather than swallowed into "no deblocking".
9721fn pick_and_apply_filters(
9722 header: &mut FrameHeader,
9723 luma: &mut Plane<'_>,
9724 chroma: &mut [Plane<'_>; 2],
9725 source: [&[u8]; 3],
9726 search: bool,
9727 // The coded tiles, one payload per tile of the frame's grid, replaced in
9728 // place when the search chooses a per-64x64 `cdef_idx` list
9729 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
9730 // tile is written a second time under `recode` and the winner
9731 // re-decoded from them.
9732 tiles: &mut Vec<Vec<u8>>,
9733 lambda: f64,
9734 fctx: &crate::decode::FrameCtx,
9735 // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles
9736 // carry -- empty (the identity map) for a frame whose every block covers
9737 // one 64x64 CDEF unit.
9738 cdef_owner: &[u32],
9739 recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<Vec<u8>>>,
9740 decode: impl Fn(
9741 &LoopFilterParams,
9742 &CdefParams,
9743 &FrameHeader,
9744 &[Vec<u8>],
9745 &LoopRestorationParams,
9746 ) -> Result<Picture>,
9747) -> Result<()> {
9748 if !search {
9749 return Ok(());
9750 }
9751 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
9752 let hdr = header.clone();
9753 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
9754 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
9755 let damping = 3 + (header.quantization.base_q_idx >> 6);
9756 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9757 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
9758 let none_lr = LoopRestorationParams::default();
9759 // Every candidate scores the same coded tile: decode it once and re-run
9760 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
9761 // the encoder's profile before this). The per-64x64 error the CDEF
9762 // preset search reads comes off the REPLAYED picture, which is the same
9763 // picture a decode produces -- that is what the replay is pinned on.
9764 crate::decode::clear_filter_replay();
9765 // lane-av1fpar: the per-tile search is over, so every core is idle from
9766 // here to the end of the frame -- band each candidate's deblock/CDEF
9767 // replay, the capture decode's own filter chain and the loop-restoration
9768 // passes across the same workers the search used.
9769 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
9770 let ft = crate::par::timer(crate::par::S_FILTER);
9771 let search_result = crate::filter_search::pick_filters(
9772 |lf, cdef| {
9773 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
9774 return Ok(picture);
9775 }
9776 crate::decode::arm_filter_replay();
9777 let _t = crate::par::timer(crate::par::S_FIRST);
9778 decode(lf, cdef, &hdr, tiles, &none_lr)
9779 },
9780 source,
9781 luma.width,
9782 (fw, fh),
9783 damping,
9784 (sb_cols, sb_rows),
9785 lambda,
9786 cdef_owner,
9787 );
9788 drop(ft);
9789 let (lf, cdef, idx_grid, picture) = search_result?;
9790 header.loop_filter = lf;
9791 header.cdef = cdef;
9792 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
9793 // in the frame header, so a re-decode under candidate parameters cannot
9794 // search them the way deblocking and CDEF are searched above. What the
9795 // decoder hands back instead is its own filter chain's intermediates
9796 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
9797 // those, through the decoder's own Wiener kernel.
9798 //
9799 // The capture rides the decode this stage was already going to do: the
9800 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
9801 // decode of the tile as it stands. That decode's header still says
9802 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
9803 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
9804 // an approximation inside the SEARCH only; the reconstruction this
9805 // function ends up splicing is always a real decode of the real tile.
9806 let lr_on = restoration_enabled();
9807 // The `cdef_idx` literals live in the tile payload, so a frame that
9808 // chose a per-64x64 preset list codes its tiles a second time.
9809 if !idx_grid.is_empty() {
9810 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
9811 }
9812 // lane-av1cap: that re-coded tile used to be DECODED here as well --
9813 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
9814 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
9815 // and the picture this function splices. Both come out of ONE more
9816 // replay of the winning parameters on the same captured pre-filter
9817 // planes every candidate was scored on: the same two filter kernels, on
9818 // the same input, in the same order, so the same bytes. Re-coding the
9819 // tile does not move the reconstruction the replay holds -- `cdef_idx`
9820 // is an equiprobable literal, so it adapts no CDF and changes no
9821 // residual.
9822 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
9823 #[cfg(test)]
9824 let replay_was_used = replayed.is_some();
9825 let (mut filtered, mut stages) = match replayed {
9826 Some((picture, stages)) => (picture, stages),
9827 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
9828 // refuses): every candidate was a full decode, so the winner's own
9829 // picture stands, and the stages still need a capturing decode.
9830 None => {
9831 fctx.capture_stages.set(lr_on);
9832 let picture = if idx_grid.is_empty() && !lr_on {
9833 picture
9834 } else {
9835 let _t = crate::par::timer(crate::par::S_CAPTURE);
9836 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
9837 };
9838 fctx.capture_stages.set(false);
9839 (picture, crate::decode::take_filter_stages(fctx))
9840 }
9841 };
9842 #[cfg(test)]
9843 if crate::decode::verify_final_replay() && replay_was_used {
9844 fctx.capture_stages.set(lr_on);
9845 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
9846 fctx.capture_stages.set(false);
9847 let want_stages = crate::decode::take_filter_stages(fctx);
9848 assert!(
9849 (want.width, want.height) == (filtered.width, filtered.height)
9850 && want.y == filtered.y
9851 && want.u == filtered.u
9852 && want.v == filtered.v,
9853 "the final filter replay is not the capture decode it stands in for",
9854 );
9855 // Only the frame's own cropped region: the plane is padded to the
9856 // superblock grid and the columns past the mi extent are written by
9857 // nothing (the decoder's plane pool leaves whatever the last frame
9858 // put there), while the restoration search reads strictly inside
9859 // `fw x fh` -- `restoration::lr_sample` clamps its column to
9860 // `plane_w - 1` and its row to the frame's, and
9861 // `filter_search::pick_restoration`'s own SSE walk never leaves the
9862 // crop either.
9863 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
9864 for row in 0..h {
9865 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
9866 assert!(
9867 x == y,
9868 "{what}: the replayed filter stages are not the ones the capture \
9869 decode returns (row {row} of {h}, width {w}, stride {stride})",
9870 );
9871 }
9872 };
9873 match (&want_stages, &stages) {
9874 (Some(a), Some(b)) => {
9875 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
9876 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9877 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
9878 region(
9879 &a.deblocked[i],
9880 &b.deblocked[i],
9881 a.stride[i],
9882 w,
9883 h,
9884 "deblocked",
9885 );
9886 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
9887 }
9888 }
9889 (None, None) => {}
9890 _ => panic!("one path captured filter stages and the other did not"),
9891 }
9892 }
9893 // lane-av1cap2: the capture stays live past the restoration search --
9894 // `crate::decode::replay_restoration` filters the same post-CDEF plane
9895 // rather than decoding the re-coded tile. Cleared at the end instead.
9896 let mut lr = LoopRestorationParams::default();
9897 if lr_on {
9898 let unit = lr_unit();
9899 let mut want = LoopRestorationParams {
9900 loop_restoration_size: [unit, unit, unit],
9901 uses_lr: true,
9902 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
9903 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
9904 lr_unit_shift: u8::from(unit == 128),
9905 ..LoopRestorationParams::default()
9906 };
9907 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
9908 let lrt = crate::par::timer(crate::par::S_LR);
9909 let units = match stages.take() {
9910 Some(stages) => crate::filter_search::pick_restoration(
9911 &stages,
9912 source[0],
9913 luma.width,
9914 (fw, fh),
9915 &want,
9916 lambda,
9917 fctx,
9918 ),
9919 None => Vec::new(),
9920 };
9921 // A frame no unit restores keeps `RESTORE_NONE` on every plane
9922 // rather than paying ~1 bit per 64x64 for a tile full of
9923 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
9924 // clip whose units never take a filter).
9925 drop(lrt);
9926 if units.iter().any(Option::is_some) {
9927 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
9928 let _t = crate::par::timer(crate::par::S_CAPTURE);
9929 // lane-av1cap2: that re-coded tile used to be DECODED here to
9930 // reach the restored reference frame -- 5.6% of a 4K frame,
9931 // for a filter that reads nothing of the tile but the per-unit
9932 // Wiener filters this stage just chose. Run the decoder's own
9933 // restoration kernel on the replay's post-CDEF plane instead
9934 // (`crate::decode::replay_restoration`), with the real
9935 // post-deblock stripe borders.
9936 match crate::decode::replay_restoration(&want, &units, fctx) {
9937 Some(y) => {
9938 #[cfg(test)]
9939 let margin = fctx
9940 .last_frame_wide_margin
9941 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
9942 #[cfg(test)]
9943 if crate::decode::verify_final_replay() {
9944 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
9945 assert!(
9946 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
9947 && want_pic.u == filtered.u
9948 && want_pic.v == filtered.v,
9949 "the restoration replay moved a chroma plane or the picture size",
9950 );
9951 assert!(
9952 want_pic.y == y,
9953 "the restoration replay is not the decode of the re-coded tile",
9954 );
9955 assert!(
9956 fctx.last_frame_wide_margin
9957 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
9958 == margin,
9959 "the restoration replay's wide-margin luma is not the decode's",
9960 );
9961 }
9962 filtered.y = y;
9963 }
9964 // Nothing captured: the winner came out of a full decode,
9965 // so this one does too.
9966 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
9967 }
9968 *tiles = coded;
9969 lr = want;
9970 }
9971 }
9972 crate::decode::clear_filter_replay();
9973 header.loop_restoration = lr;
9974 let dec_cw = filtered.width.div_ceil(2);
9975 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9976 crate::filter_search::splice(
9977 &mut luma.reconstruction,
9978 luma.width,
9979 &filtered.y,
9980 filtered.width,
9981 fw,
9982 fh,
9983 );
9984 crate::filter_search::splice(
9985 &mut chroma[0].reconstruction,
9986 chroma[0].width,
9987 &filtered.u,
9988 dec_cw,
9989 cw,
9990 ch,
9991 );
9992 crate::filter_search::splice(
9993 &mut chroma[1].reconstruction,
9994 chroma[1].width,
9995 &filtered.v,
9996 dec_cw,
9997 cw,
9998 ch,
9999 );
10000 Ok(())
10001}
10002
10003/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
10004/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
10005/// since every block this crate's inter tile writer codes is 32x32.
10006const SIZE_GROUP_32: usize = 3;
10007
10008/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
10009/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
10010/// stack this encoder builds is ever asked to predict against.
10011const LAST_FRAME: i8 = 1;
10012
10013/// What an inter frame's intra branch spends to name each of the thirteen
10014/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
10015/// context, since an inter frame's intra blocks do not read their
10016/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
10017/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
10018/// state, so it is built once per frame.
10019fn inter_mode_bits() -> [f64; 13] {
10020 std::array::from_fn(|mode| {
10021 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
10022 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
10023 } else {
10024 0.0
10025 };
10026 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
10027 + angle
10028 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
10029 })
10030}
10031
10032/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
10033/// [`mc::predict`] takes, in the units of the plane it predicts into.
10034///
10035/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
10036/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
10037/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
10038/// domain. `luma` picks which.
10039fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
10040 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
10041}
10042
10043/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
10044/// that module): the magnitude an `MV_CLASS_n` component's own bits start
10045/// counting from.
10046fn mv_class_base(class: usize) -> i32 {
10047 if class == 0 { 0 } else { 2i32 << (class + 2) }
10048}
10049
10050/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
10051/// `tile::mv_class_of`.
10052fn mv_class_of(z: i32) -> usize {
10053 let mut class = 0;
10054 while class < 10 && mv_class_base(class + 1) <= z {
10055 class += 1;
10056 }
10057 class
10058}
10059
10060/// What [`crate::tile::write_mv_component`] (private to that module) would
10061/// spend coding one non-zero motion vector component, against the same
10062/// static default CDFs the writer starts a frame from — the same
10063/// static-table approximation [`mode_bits`] costs the luma mode symbol
10064/// through, not the tile writer's own adapting state, which this encoder has
10065/// no way to read without duplicating it block for block.
10066///
10067/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
10068/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
10069/// exists to avoid ever happening.
10070fn mv_component_bits(diff: i32) -> Option<f64> {
10071 let hp_frame = crate::tile::high_precision_mv();
10072 let mag = diff.unsigned_abs() as i32;
10073 let z = mag - 1;
10074 if !hp_frame && z & 1 == 0 {
10075 return None;
10076 }
10077 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
10078 let class = mv_class_of(z);
10079 bits += symbol_bits(&cdf::MV_CLASS, class);
10080 let local = z - mv_class_base(class);
10081 let hp = (local & 1) as usize;
10082 if class == 0 {
10083 let bit = (local >> 3) & 1;
10084 let fr = (local >> 1) & 3;
10085 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
10086 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
10087 // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
10088 // frame, so the pricer charges for it there and only there.
10089 if hp_frame {
10090 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
10091 }
10092 } else {
10093 let d = local >> 3;
10094 let fr = (local >> 1) & 3;
10095 for i in 0..class {
10096 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
10097 }
10098 bits += symbol_bits(&cdf::MV_FR, fr as usize);
10099 if hp_frame {
10100 bits += symbol_bits(&cdf::MV_HP, hp);
10101 }
10102 }
10103 Some(bits)
10104}
10105
10106/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
10107/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
10108/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
10109/// value without the second motion search's wall.
10110fn last2_new_mv() -> bool {
10111 match std::env::var("EC_AV1_LAST2_NEW").ok() {
10112 Some(v) => v != "0",
10113 None => true,
10114 }
10115}
10116
10117/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
10118/// own -- a second motion search per block against that reference's picture,
10119/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
10120/// off in a test build (what the lane measured both arms with).
10121fn extra_ref_new_mv() -> bool {
10122 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
10123 Some(v) if cfg!(test) => v != "0",
10124 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
10125 }
10126}
10127
10128/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
10129/// flat slot plan (`inter_frame_headers_slots`): every reference but
10130/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
10131/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
10132/// frame two back when there is one (otherwise it, too, names the key frame's
10133/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
10134pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
10135 let last = order_hint.wrapping_sub(1) & 0x7f;
10136 let alt = if has_altref {
10137 order_hint.wrapping_sub(2) & 0x7f
10138 } else {
10139 key_hint
10140 };
10141 [last, last, last, key_hint, last, last, alt]
10142}
10143
10144/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
10145/// header bit that lets each block choose between a single and a compound
10146/// reference. Off by default until compound prediction is measured to pay;
10147/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
10148/// runs as), and every block still codes SINGLE, so the only cost is one
10149/// `comp_mode` symbol per inter block.
10150pub(crate) const REFERENCE_SELECT: bool = true;
10151
10152/// [`REFERENCE_SELECT`], with the test-build environment override.
10153pub(crate) fn reference_select() -> bool {
10154 match std::env::var("EC_AV1_COMPOUND").ok() {
10155 Some(v) if cfg!(test) => v != "0",
10156 _ => crate::speed::at(&crate::speed::COMPOUND),
10157 }
10158}
10159
10160/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
10161/// per entry past `start`, `1` to advance and `0` to stop, at most two.
10162fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
10163 let mut bits = 0.0;
10164 let mut idx = start;
10165 while idx < start + 2 && stack.entries.len() > idx + 1 {
10166 let advance = idx < target;
10167 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
10168 if !advance {
10169 break;
10170 }
10171 idx += 1;
10172 }
10173 bits
10174}
10175
10176/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
10177/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
10178/// `assign_mv`), so the same vector costs a different residual from each.
10179fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
10180 let mut best: Option<(f64, u8)> = None;
10181 for idx in 0..3usize {
10182 if idx > 0 && stack.entries.len() <= idx {
10183 break;
10184 }
10185 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
10186 if let Some(b) = mv_residual_bits(mv, base) {
10187 let total = b + drl_bits_for(stack, 0, idx);
10188 if best.is_none_or(|(t, _)| total < t) {
10189 best = Some((total, idx as u8));
10190 }
10191 }
10192 }
10193 best
10194}
10195
10196/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
10197/// zero vector and the stack's own candidates. A neighbour block's vector is
10198/// where this block's motion most often already is, which is what pays for
10199/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
10200/// vs libaom for 0.2 s off a 6 s ladder).
10201fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
10202 let mut seeds = [(0, 0); 4];
10203 let mut n = 1;
10204 for e in stack.entries.iter().take(3) {
10205 seeds[n] = e.mv;
10206 n += 1;
10207 }
10208 (seeds, n)
10209}
10210
10211/// What [`crate::tile::write_mv`] (private to that module) would spend
10212/// coding `mv` as a residual against `pred`: the joint symbol naming which
10213/// components differ, then each differing component. `None` under the same
10214/// condition [`mv_component_bits`] returns `None`.
10215/// How many frames back `ref_frame` sits from the frame being coded, off the
10216/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
10217/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
10218/// what [`crate::motion::search`] scales its starting step by.
10219fn ref_distance(ref_frame: i8) -> u32 {
10220 let (bits, order_hint, hints) = crate::tile::order_hints();
10221 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
10222 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
10223 .unsigned_abs()
10224 .max(1);
10225 if crate::envflags::env_flag!("EC_TRACE_DIST") {
10226 eprintln!(
10227 "EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}",
10228 hints[i]
10229 );
10230 }
10231 d
10232}
10233
10234fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
10235 let diff = (mv.0 - pred.0, mv.1 - pred.1);
10236 let joint = match (diff.0 != 0, diff.1 != 0) {
10237 (false, false) => 0,
10238 (false, true) => 1,
10239 (true, false) => 2,
10240 (true, true) => 3,
10241 };
10242 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
10243 for d in [diff.0, diff.1] {
10244 if d != 0 {
10245 bits += mv_component_bits(d)?;
10246 }
10247 }
10248 Some(bits)
10249}
10250
10251/// Rounds `mv` so that its residual against `pred` is one
10252/// [`crate::tile::write_mv_component`] can actually code: each component's
10253/// difference is either zero or has an even magnitude (the eighth-pel bit
10254/// `allow_high_precision_mv` off always infers as one forces the coded
10255/// magnitude odd one step further in, which comes out even here since this
10256/// crate's motion search works in whole units of that same step). Rounding
10257/// down keeps every coded MV — and so every `nearest_mv` a later block's
10258/// stack votes with — built from an even displacement from `(0, 0)`, so the
10259/// invariant holds without this function seeing the whole stack.
10260/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
10261/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
10262/// always), the shape [`set_frame_interp`] has: the witness that has to see
10263/// `mv_hp` symbols coded turns it on through this while holding
10264/// [`crate::speed::knob_write`].
10265static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
10266
10267/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
10268#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
10269pub(crate) fn set_high_precision_mv(on: Option<bool>) {
10270 HP_MV_OVERRIDE.store(
10271 on.map_or(u8::MAX, u8::from),
10272 std::sync::atomic::Ordering::Relaxed,
10273 );
10274}
10275
10276/// The qindex below which an inter frame codes `allow_high_precision_mv`
10277/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
10278/// crate's shipped value, i.e. high-precision motion vectors off in every
10279/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
10280pub(crate) const HP_MV_QTHRESH: u8 = 0;
10281
10282/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
10283/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
10284/// always, any number as the threshold) so the BD gate can sweep the policy
10285/// without a rebuild.
10286pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
10287 match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
10288 0 => return false,
10289 1 => return true,
10290 _ => {}
10291 }
10292 static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
10293 let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
10294 Some("all" | "always") => 256,
10295 Some("0" | "off") => 0,
10296 Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
10297 None => u16::from(HP_MV_QTHRESH),
10298 });
10299 u16::from(base_q_idx) < threshold
10300}
10301
10302fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
10303 // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
10304 // residual is codable and there is nothing to round away.
10305 if crate::tile::high_precision_mv() {
10306 return mv;
10307 }
10308 let round = |m: i32, p: i32| {
10309 let diff = m - p;
10310 let mag = diff.unsigned_abs() as i32;
10311 let even = mag - mag % 2;
10312 if even == 0 {
10313 p
10314 } else {
10315 p + even * diff.signum()
10316 }
10317 };
10318 (round(mv.0, pred.0), round(mv.1, pred.1))
10319}
10320
10321/// Predicts one `side`-square block by motion compensation from `reference`
10322/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
10323#[allow(clippy::too_many_arguments)]
10324fn mc_trial(
10325 plane: &Plane,
10326 x: usize,
10327 y: usize,
10328 side: usize,
10329 mv: (i32, i32),
10330 luma: bool,
10331 reference: &[u16],
10332 stride: usize,
10333 ref_width: usize,
10334 ref_height: usize,
10335 skip: bool,
10336 base_q_idx: u8,
10337 deadzone: f64,
10338 set: TxbSet,
10339 fctx: &crate::decode::FrameCtx,
10340) -> Trial {
10341 mc_trial_typed(
10342 plane,
10343 x,
10344 y,
10345 side,
10346 mv,
10347 luma,
10348 reference,
10349 stride,
10350 ref_width,
10351 ref_height,
10352 skip,
10353 base_q_idx,
10354 deadzone,
10355 set,
10356 TxType::DctDct,
10357 fctx,
10358 )
10359}
10360
10361/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
10362#[allow(clippy::too_many_arguments)]
10363fn mc_trial_typed(
10364 plane: &Plane,
10365 x: usize,
10366 y: usize,
10367 side: usize,
10368 mv: (i32, i32),
10369 luma: bool,
10370 reference: &[u16],
10371 stride: usize,
10372 ref_width: usize,
10373 ref_height: usize,
10374 skip: bool,
10375 base_q_idx: u8,
10376 deadzone: f64,
10377 set: TxbSet,
10378 tx_type: TxType,
10379 fctx: &crate::decode::FrameCtx,
10380) -> Trial {
10381 let x_q4 = mv_to_q4(x, mv.1, luma);
10382 let y_q4 = mv_to_q4(y, mv.0, luma);
10383 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
10384 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
10385 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
10386 // lane-av1speed: both buffers are per-candidate scratch on the hottest
10387 // path in the encoder, so they live on the stack -- `side` is at most
10388 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
10389 // per motion-compensated trial otherwise.
10390 let mut prediction16 = [0u16; BLOCK * BLOCK];
10391 let prediction16 = &mut prediction16[..side * side];
10392 mc::predict(
10393 reference,
10394 stride,
10395 ref_width,
10396 ref_height,
10397 x_q4,
10398 y_q4,
10399 side,
10400 side,
10401 prediction16,
10402 fctx,
10403 );
10404 let mut prediction = [0u8; BLOCK * BLOCK];
10405 let prediction = &mut prediction[..side * side];
10406 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
10407 *dst = src as u8;
10408 }
10409 plane.code_from_prediction_typed(
10410 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
10411 )
10412}
10413
10414/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
10415/// references predict into the `CONV_BUF` intermediate domain
10416/// ([`mc::predict_compound_intermediate`]) and are blended by
10417/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
10418/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
10419/// block, so the encoder's reconstruction is the decoder's.
10420#[allow(clippy::too_many_arguments)]
10421fn mc_trial_compound(
10422 plane: &Plane,
10423 x: usize,
10424 y: usize,
10425 side: usize,
10426 mvs: ((i32, i32), (i32, i32)),
10427 luma: bool,
10428 ref0: (&[u16], usize, usize, usize),
10429 ref1: (&[u16], usize, usize, usize),
10430 base_q_idx: u8,
10431 deadzone: f64,
10432 set: TxbSet,
10433 fctx: &crate::decode::FrameCtx,
10434) -> Trial {
10435 mc_trial_compound_typed(
10436 plane,
10437 x,
10438 y,
10439 side,
10440 mvs,
10441 luma,
10442 ref0,
10443 ref1,
10444 base_q_idx,
10445 deadzone,
10446 set,
10447 TxType::DctDct,
10448 fctx,
10449 )
10450}
10451
10452/// [`mc_trial_compound`] coding its residual with a named transform type
10453/// (lane-txset2).
10454#[allow(clippy::too_many_arguments)]
10455fn mc_trial_compound_typed(
10456 plane: &Plane,
10457 x: usize,
10458 y: usize,
10459 side: usize,
10460 (mv0, mv1): ((i32, i32), (i32, i32)),
10461 luma: bool,
10462 ref0: (&[u16], usize, usize, usize),
10463 ref1: (&[u16], usize, usize, usize),
10464 base_q_idx: u8,
10465 deadzone: f64,
10466 set: TxbSet,
10467 tx_type: TxType,
10468 fctx: &crate::decode::FrameCtx,
10469) -> Trial {
10470 let mut inter0 = [0i32; BLOCK * BLOCK];
10471 let mut inter1 = [0i32; BLOCK * BLOCK];
10472 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
10473 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
10474 mc::predict_compound_intermediate(
10475 r.0,
10476 r.1,
10477 r.2,
10478 r.3,
10479 mv_to_q4(x, mv.1, luma),
10480 mv_to_q4(y, mv.0, luma),
10481 mc::REF_NO_SCALE,
10482 side,
10483 side,
10484 fctx.interp_filter.get(),
10485 fctx.interp_filter.get(),
10486 dst,
10487 fctx,
10488 );
10489 }
10490 let mut blended16 = [0u16; BLOCK * BLOCK];
10491 let blended16 = &mut blended16[..side * side];
10492 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
10493 let mut prediction = [0u8; BLOCK * BLOCK];
10494 let prediction = &mut prediction[..side * side];
10495 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
10496 *dst = src as u8;
10497 }
10498 plane.code_from_prediction_typed(
10499 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
10500 )
10501}
10502
10503/// Codes one 32x32 block of an inter frame as whichever costs least of: each
10504/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
10505/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
10506/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
10507/// coding a real residual (`skip: false`) whenever one prices out cheaper
10508/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
10509/// missing inter `tx_type` symbol (the desync this function's candidates
10510/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
10511/// fixed.
10512///
10513/// The symbol costs this ranks candidates by use fixed contexts (0) for
10514/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
10515/// contexts for those come from its own neighbour bookkeeping
10516/// (`tile::Neighbours`), which is private to that module and not worth
10517/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
10518/// `drl_mode` contexts come straight from `stack`, which is exact, because
10519/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
10520/// the tile writer derives from the same grid state.
10521#[allow(clippy::too_many_arguments)]
10522/// One prediction of `side` x `side` samples from `reference`, as `u8` --
10523/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
10524/// four times the stack scratch that function sizes for [`BLOCK`].
10525fn predict_u8(
10526 reference: &[u16],
10527 stride: usize,
10528 ref_width: usize,
10529 ref_height: usize,
10530 (x, y): (usize, usize),
10531 side: usize,
10532 mv: (i32, i32),
10533 luma: bool,
10534 fctx: &crate::decode::FrameCtx,
10535) -> Vec<u8> {
10536 let mut prediction = vec![0u16; side * side];
10537 mc::predict(
10538 reference,
10539 stride,
10540 ref_width,
10541 ref_height,
10542 mv_to_q4(x, mv.1, luma),
10543 mv_to_q4(y, mv.0, luma),
10544 side,
10545 side,
10546 &mut prediction,
10547 fctx,
10548 );
10549 prediction.iter().map(|&v| v as u8).collect()
10550}
10551
10552/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
10553/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
10554/// references predict into the `CONV_BUF` intermediate domain and are blended
10555/// at the simple-average split `(8, 8)`, the same path (and so the same
10556/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
10557fn predict_compound_u8(
10558 ref0: (&[u16], usize, usize, usize),
10559 ref1: (&[u16], usize, usize, usize),
10560 (x, y): (usize, usize),
10561 side: usize,
10562 (mv0, mv1): ((i32, i32), (i32, i32)),
10563 luma: bool,
10564 fctx: &crate::decode::FrameCtx,
10565) -> Vec<u8> {
10566 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
10567 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
10568 mc::predict_compound_intermediate(
10569 r.0,
10570 r.1,
10571 r.2,
10572 r.3,
10573 mv_to_q4(x, mv.1, luma),
10574 mv_to_q4(y, mv.0, luma),
10575 mc::REF_NO_SCALE,
10576 side,
10577 side,
10578 fctx.interp_filter.get(),
10579 fctx.interp_filter.get(),
10580 dst,
10581 fctx,
10582 );
10583 }
10584 let mut blended = vec![0u16; side * side];
10585 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
10586 blended.iter().map(|&v| v as u8).collect()
10587}
10588
10589/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
10590/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
10591/// one motion vector where the four 64x64 roots below spend four of each.
10592///
10593/// SKIP only (`residual: false`): a 128x128 block's residual is four
10594/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
10595/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
10596/// path for -- offering one here would price a block
10597/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
10598/// the same reason: the compound arm at this size is untested against the
10599/// writer's own `write_compound_block` window.
10600///
10601/// Only a root whose whole 128x128 lies inside the true frame AND inside
10602/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
10603/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
10604/// block would have to be ranked over its inside part alone.
10605///
10606/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
10607/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
10608/// against the four superblocks plus the SPLIT symbol.
10609#[allow(clippy::too_many_arguments)]
10610fn search_root_128(
10611 luma: &mut Plane,
10612 chroma: &mut [Plane; 2],
10613 grid: &crate::mvstack::MiGrid,
10614 (root_r, root_c): (usize, usize),
10615 // The 32x32-block grid this tile's `blocks` vector is indexed on.
10616 (rows, cols): (usize, usize),
10617 // The frame's own mode-info grid, which bounds the root.
10618 (mi_cols, mi_rows): (u32, u32),
10619 search: Search<'_>,
10620 tpl_factors: &Option<Vec<f64>>,
10621 sb_q: Option<&Vec<u8>>,
10622 sb_cols: usize,
10623 tpl_cells_x: usize,
10624 base_q_idx: u8,
10625 // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
10626 // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
10627 dq_res: i32,
10628 reference: &Picture,
10629 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
10630 // built by the caller off the same grid the tile writer rebuilds its
10631 // stack from (empty unless the frame carries `reference_select` and
10632 // [`b128_compound`] is on).
10633 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10634 fctx: &crate::decode::FrameCtx,
10635) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
10636 const SIDE: usize = SUPERBLOCK * 2;
10637 const SIDE_MI: usize = SIDE / 4;
10638 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10639 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10640 if root_r * 2 + 3 >= rows
10641 || root_c * 2 + 3 >= cols
10642 || (mi_row + SIDE_MI) as u32 > mi_rows
10643 || (mi_col + SIDE_MI) as u32 > mi_cols
10644 || x128 + SIDE > luma.true_width
10645 || y128 + SIDE > luma.true_height
10646 {
10647 return None;
10648 }
10649 // One lambda for the whole root, the mean of what its four superblocks
10650 // would each be searched at -- the 128-vs-four comparison weighs one cost
10651 // against four, so both sides have to be priced at the same lambda (the
10652 // same rule the 64 root's own mean-of-sixteen tpl cells follows).
10653 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10654 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10655 (None, Some(f)) => {
10656 let mean = (0..16)
10657 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10658 .sum::<f64>()
10659 / 16.0;
10660 search.lambda * mean
10661 }
10662 (None, None) => search.lambda,
10663 };
10664 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10665 .iter()
10666 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10667 .sum::<f64>()
10668 / 4.0;
10669 // The qindex this root is really quantized at: the delta_q unit is the
10670 // 128 superblock, so the root's own top-left cell is the one coded
10671 // (lane-b128m), and the residual arm below has to quantize at exactly it.
10672 let root_search = Search {
10673 lambda,
10674 ..match sb_q {
10675 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10676 None => search,
10677 }
10678 };
10679 let stack = find_mv_stack(
10680 grid,
10681 mi_row,
10682 mi_col,
10683 SIDE_MI,
10684 SIDE_MI,
10685 LAST_FRAME,
10686 mi_cols as usize,
10687 mi_rows as usize,
10688 );
10689 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10690 let found = search_skip_64(
10691 luma,
10692 chroma,
10693 (x128, y128),
10694 (SIDE, SIDE),
10695 &root_search,
10696 false,
10697 reference,
10698 &stack,
10699 compound,
10700 fctx,
10701 );
10702 let (mut cost, mut block) = found?;
10703 if block.inter.is_some_and(|i| i.ref1.is_some()) {
10704 B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10705 }
10706 // lane-b128r: the same prediction with a REAL residual, priced against
10707 // the skip arm the search just committed to the planes (which IS the
10708 // winner's prediction, sample for sample). The block's residual is four
10709 // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
10710 // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
10711 // sides the forward network already reaches, never as one 128-point
10712 // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
10713 //
10714 // The four `txfm_partition` symbols the writer codes for them are not
10715 // priced, exactly as the 64 root does not price its own (their contexts
10716 // are only known at write time); at four symbols a root this is under a
10717 // bit against residuals of hundreds.
10718 if b128_residual() && block.skip {
10719 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10720 // only its top-left corner), packed per plane into one 64-wide grid
10721 // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
10722 // `write_inter_block_128` slices back out in the same chunk order.
10723 let mut packed = [
10724 vec![0i32; 64 * 64],
10725 vec![0i32; 64 * 64],
10726 vec![0i32; 64 * 64],
10727 ];
10728 let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
10729 let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
10730 for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
10731 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10732 let (cx, cy) = (px / 2, py / 2);
10733 let half = SUPERBLOCK / 2;
10734 let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
10735 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10736 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10737 sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
10738 + chroma[0].block_sse(cx, cy, half, &pred_u)
10739 + chroma[1].block_sse(cx, cy, half, &pred_v);
10740 let trials = [
10741 luma.code_from_prediction(
10742 px,
10743 py,
10744 SUPERBLOCK,
10745 &pred_y,
10746 false,
10747 root_search.base_q_idx,
10748 root_search.deadzone,
10749 TxbSet::Luma64,
10750 ),
10751 chroma[0].code_from_prediction(
10752 cx,
10753 cy,
10754 half,
10755 &pred_u,
10756 false,
10757 root_search.base_q_idx,
10758 root_search.deadzone,
10759 TxbSet::Chroma32,
10760 ),
10761 chroma[1].code_from_prediction(
10762 cx,
10763 cy,
10764 half,
10765 &pred_v,
10766 false,
10767 root_search.base_q_idx,
10768 root_search.deadzone,
10769 TxbSet::Chroma32,
10770 ),
10771 ];
10772 for (plane, trial) in trials.iter().enumerate() {
10773 sse_res += trial.sse;
10774 coeff_bits += trial.bits;
10775 for row in 0..32 {
10776 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10777 .copy_from_slice(&trial.levels[row * 32..][..32]);
10778 }
10779 }
10780 chunks.push(((cr, cc), trials));
10781 }
10782 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
10783 // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
10784 // coefficients.
10785 let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
10786 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10787 if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
10788 B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10789 for ((cr, cc), trials) in &chunks {
10790 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10791 let half = SUPERBLOCK / 2;
10792 luma.commit(px, py, SUPERBLOCK, &trials[0]);
10793 chroma[0].commit(px / 2, py / 2, half, &trials[1]);
10794 chroma[1].commit(px / 2, py / 2, half, &trials[2]);
10795 }
10796 cost = res_cost;
10797 block.skip = false;
10798 block.tx_depth = 0;
10799 block.luma_tx_types = Vec::new();
10800 block.luma = coeffs(&packed[0], 64);
10801 block.u = coeffs(&packed[1], 64);
10802 block.v = coeffs(&packed[2], 64);
10803 }
10804 }
10805 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10806 restore(luma, chroma, (x128, y128), SIDE, &base);
10807 // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
10808 // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
10809 // residual arm above codes it like every other block does.
10810 let dq = if block.skip {
10811 0.0
10812 } else {
10813 delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
10814 };
10815 Some((
10816 cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
10817 lambda,
10818 block,
10819 after,
10820 ))
10821}
10822
10823/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
10824/// arm the caller's [`search_skip_64`] just committed to the planes (which
10825/// IS the winner's prediction, sample for sample -- the same rule
10826/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
10827/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
10828/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
10829/// each trial at sides the forward network already reaches, never a
10830/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
10831/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
10832///
10833/// The depth-0 `txfm_partition` symbols the writer codes for the units are
10834/// not priced, exactly as [`search_root_128`] does not price its four (their
10835/// contexts are only known at write time); at two symbols a half this is
10836/// under a bit against residuals of hundreds. On a win (or under the witness
10837/// force) the trials are committed to the planes, `block` is flipped to
10838/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
10839/// slices back out, and the new cost is returned; otherwise `cost` passes
10840/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
10841#[allow(clippy::too_many_arguments)]
10842fn search_rect_residual(
10843 luma: &mut Plane,
10844 chroma: &mut [Plane; 2],
10845 // The piece's own top-left, in luma samples.
10846 (px, py): (usize, usize),
10847 // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
10848 (w, h): (usize, usize),
10849 cost: f64,
10850 lambda: f64,
10851 search: &Search<'_>,
10852 // The piece's own mv stack, for the skip symbol's cost either way.
10853 stack: &crate::mvstack::MvStack,
10854 block: &mut BlockCoeffs,
10855) -> f64 {
10856 /// The 64x64 "mu" chunk side, luma; chroma halves it.
10857 const MU: usize = SUPERBLOCK;
10858 let chunks: [(usize, usize); 2] = match (w, h) {
10859 (128, 64) => [(0, 0), (0, 1)],
10860 (64, 128) => [(0, 0), (1, 0)],
10861 _ => [(0, 0), (0, 0)],
10862 };
10863 let n = if w.max(h) > MU { 2 } else { 1 };
10864 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10865 // only its top-left corner), packed per plane into one 64-wide grid with
10866 // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
10867 // back out in the same chunk order.
10868 let mut packed = [
10869 vec![0i32; 64 * 64],
10870 vec![0i32; 64 * 64],
10871 vec![0i32; 64 * 64],
10872 ];
10873 let mut sse_skip = 0.0f64;
10874 let mut sse_res = 0.0f64;
10875 let mut coeff_bits = 0.0f64;
10876 let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
10877 for &(cr, cc) in &chunks[..n] {
10878 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10879 let (cx, cy) = (cxx / 2, cyy / 2);
10880 let half = MU / 2;
10881 let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
10882 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10883 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10884 sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
10885 + chroma[0].block_sse(cx, cy, half, &pred_u)
10886 + chroma[1].block_sse(cx, cy, half, &pred_v);
10887 let trials = [
10888 luma.code_from_prediction(
10889 cxx,
10890 cyy,
10891 MU,
10892 &pred_y,
10893 false,
10894 search.base_q_idx,
10895 search.deadzone,
10896 TxbSet::Luma64,
10897 ),
10898 chroma[0].code_from_prediction(
10899 cx,
10900 cy,
10901 half,
10902 &pred_u,
10903 false,
10904 search.base_q_idx,
10905 search.deadzone,
10906 TxbSet::Chroma32,
10907 ),
10908 chroma[1].code_from_prediction(
10909 cx,
10910 cy,
10911 half,
10912 &pred_v,
10913 false,
10914 search.base_q_idx,
10915 search.deadzone,
10916 TxbSet::Chroma32,
10917 ),
10918 ];
10919 for (plane, trial) in trials.iter().enumerate() {
10920 sse_res += trial.sse;
10921 coeff_bits += trial.bits;
10922 for row in 0..32 {
10923 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10924 .copy_from_slice(&trial.levels[row * 32..][..32]);
10925 }
10926 }
10927 trials_per_chunk.push(trials);
10928 }
10929 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
10930 // pays the same syntax with `skip` coded 0 instead of 1, plus its
10931 // coefficients.
10932 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10933 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10934 if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
10935 for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
10936 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10937 let (cx, cy) = (cxx / 2, cyy / 2);
10938 let half = MU / 2;
10939 luma.commit(cxx, cyy, MU, &trials[0]);
10940 chroma[0].commit(cx, cy, half, &trials[1]);
10941 chroma[1].commit(cx, cy, half, &trials[2]);
10942 }
10943 block.skip = false;
10944 block.tx_depth = 0;
10945 block.luma_tx_types = Vec::new();
10946 block.luma = coeffs(&packed[0], 64);
10947 block.u = coeffs(&packed[1], 64);
10948 block.v = coeffs(&packed[2], 64);
10949 B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10950 res_cost
10951 } else {
10952 cost
10953 }
10954}
10955
10956/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
10957/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
10958/// shipped NONE machinery halved. Skip-only by default, single reference or
10959/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
10960/// ([`search_rect_residual`]) -- exactly what
10961/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
10962/// reads at `sb128_rect`.
10963///
10964/// The FIRST half is published into `grid` before the second is searched --
10965/// the writer publishes it too, so a second half searched against the stale
10966/// grid would be priced (and its mv predicted) off a stack the decoder never
10967/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
10968/// both planes are put back before returning; the caller re-applies the
10969/// winner.
10970///
10971/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
10972/// carrying the root's own partition symbol so it ranks against
10973/// [`search_root_128`] and against the four superblocks below.
10974#[allow(clippy::too_many_arguments)]
10975fn search_root_128_rect(
10976 luma: &mut Plane,
10977 chroma: &mut [Plane; 2],
10978 grid: &mut crate::mvstack::MiGrid,
10979 (root_r, root_c): (usize, usize),
10980 (rows, cols): (usize, usize),
10981 (mi_cols, mi_rows): (u32, u32),
10982 search: Search<'_>,
10983 tpl_factors: &Option<Vec<f64>>,
10984 sb_q: Option<&Vec<u8>>,
10985 sb_cols: usize,
10986 tpl_cells_x: usize,
10987 base_q_idx: u8,
10988 // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
10989 dq_res: i32,
10990 reference: &Picture,
10991 // The `LAST` + extra-reference pairs offered at this root; only the
10992 // reference and its picture are read here, since each HALF derives its
10993 // own compound stack at its own rectangular window.
10994 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10995 horz: bool,
10996 fctx: &crate::decode::FrameCtx,
10997) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10998 const SIDE: usize = SUPERBLOCK * 2;
10999 const SIDE_MI: usize = SIDE / 4;
11000 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
11001 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
11002 if root_r * 2 + 3 >= rows
11003 || root_c * 2 + 3 >= cols
11004 || (mi_row + SIDE_MI) as u32 > mi_rows
11005 || (mi_col + SIDE_MI) as u32 > mi_cols
11006 || x128 + SIDE > luma.true_width
11007 || y128 + SIDE > luma.true_height
11008 {
11009 return None;
11010 }
11011 // The root's own lambda, the mean of its four superblocks' -- the same
11012 // one [`search_root_128`] prices with, so the three root candidates and
11013 // the four-superblock arm are all comparable.
11014 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
11015 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
11016 (None, Some(f)) => {
11017 let mean = (0..16)
11018 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
11019 .sum::<f64>()
11020 / 16.0;
11021 search.lambda * mean
11022 }
11023 (None, None) => search.lambda,
11024 };
11025 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
11026 .iter()
11027 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
11028 .sum::<f64>()
11029 / 4.0;
11030 let root_search = Search {
11031 lambda,
11032 ..match sb_q {
11033 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
11034 None => search,
11035 }
11036 };
11037 let (w, h) = if horz {
11038 (SIDE, SUPERBLOCK)
11039 } else {
11040 (SUPERBLOCK, SIDE)
11041 };
11042 let (w_mi, h_mi) = (w / 4, h / 4);
11043 let base = snapshot(luma, chroma, (x128, y128), SIDE);
11044 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
11045 let mut cost = 0.0f64;
11046 let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
11047 for i in 0..2usize {
11048 let (mr, mc) = if horz {
11049 (mi_row + i * 16, mi_col)
11050 } else {
11051 (mi_row, mi_col + i * 16)
11052 };
11053 let stack = find_mv_stack(
11054 grid,
11055 mr,
11056 mc,
11057 w_mi,
11058 h_mi,
11059 LAST_FRAME,
11060 mi_cols as usize,
11061 mi_rows as usize,
11062 );
11063 let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
11064 .iter()
11065 .map(|&(r, pic, _)| {
11066 (
11067 r,
11068 pic,
11069 crate::mvstack::find_mv_stack_compound(
11070 grid,
11071 mr,
11072 mc,
11073 w_mi,
11074 h_mi,
11075 (LAST_FRAME, r),
11076 mi_cols as usize,
11077 mi_rows as usize,
11078 grid.sign_bias_table(),
11079 &[(0, 0); 7],
11080 None,
11081 ),
11082 )
11083 })
11084 .collect();
11085 let found = search_skip_64(
11086 luma,
11087 chroma,
11088 (mc * 4, mr * 4),
11089 (w, h),
11090 &root_search,
11091 false,
11092 reference,
11093 &stack,
11094 &half_compound,
11095 fctx,
11096 );
11097 match found {
11098 Some((mut c, mut block)) => {
11099 // lane-rectres: the same prediction with a REAL residual,
11100 // priced against the skip arm the search just committed to
11101 // the planes -- two 64x64 mu chunks for a half.
11102 if rectres() && block.skip {
11103 c = search_rect_residual(
11104 luma,
11105 chroma,
11106 (mc * 4, mr * 4),
11107 (w, h),
11108 c,
11109 root_search.lambda,
11110 &root_search,
11111 &stack,
11112 &mut block,
11113 );
11114 }
11115 cost += c;
11116 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
11117 halves.push(block);
11118 }
11119 None => {
11120 restore(luma, chroma, (x128, y128), SIDE, &base);
11121 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11122 return None;
11123 }
11124 }
11125 }
11126 let after = snapshot(luma, chroma, (x128, y128), SIDE);
11127 restore(luma, chroma, (x128, y128), SIDE, &base);
11128 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11129 let symbol = if horz { 1 } else { 2 };
11130 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
11131 // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
11132 // codes the delta_q group whether it is skipped or not
11133 // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
11134 // half is at a non-origin mi and codes none.
11135 let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
11136 Some((
11137 cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
11138 lambda,
11139 [b0, b1],
11140 after,
11141 ))
11142}
11143
11144/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
11145/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
11146/// decoder's own). Each piece is priced through the same `search_skip_64`
11147/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
11148/// into `grid` before the next is searched -- the writer publishes it too, so
11149/// a later piece searched against a stale grid would be priced (and its mv
11150/// predicted) off a stack the decoder never derives (class
11151/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
11152/// are put back before returning; the caller re-applies the winner.
11153///
11154/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
11155/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
11156/// libaom's own AB shapes earn their keep.
11157///
11158/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
11159/// already carrying the root's own partition symbol so it ranks against the
11160/// other root candidates and against the four superblocks below.
11161#[allow(clippy::too_many_arguments)]
11162fn search_root_128_ab(
11163 luma: &mut Plane,
11164 chroma: &mut [Plane; 2],
11165 grid: &mut crate::mvstack::MiGrid,
11166 (root_r, root_c): (usize, usize),
11167 (rows, cols): (usize, usize),
11168 (mi_cols, mi_rows): (u32, u32),
11169 search: Search<'_>,
11170 tpl_factors: &Option<Vec<f64>>,
11171 sb_q: Option<&Vec<u8>>,
11172 sb_cols: usize,
11173 tpl_cells_x: usize,
11174 base_q_idx: u8,
11175 reference: &Picture,
11176 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11177 // The partition symbol, 4..=7.
11178 symbol: usize,
11179 fctx: &crate::decode::FrameCtx,
11180) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
11181 const SIDE: usize = SUPERBLOCK * 2;
11182 const SIDE_MI: usize = SIDE / 4;
11183 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
11184 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
11185 if root_r * 2 + 3 >= rows
11186 || root_c * 2 + 3 >= cols
11187 || (mi_row + SIDE_MI) as u32 > mi_rows
11188 || (mi_col + SIDE_MI) as u32 > mi_cols
11189 || x128 + SIDE > luma.true_width
11190 || y128 + SIDE > luma.true_height
11191 {
11192 return None;
11193 }
11194 // The root's own lambda, the mean of its four superblocks' -- the same one
11195 // [`search_root_128`] prices with, so every root candidate and the
11196 // four-superblock arm are comparable.
11197 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
11198 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
11199 (None, Some(f)) => {
11200 let mean = (0..16)
11201 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
11202 .sum::<f64>()
11203 / 16.0;
11204 search.lambda * mean
11205 }
11206 (None, None) => search.lambda,
11207 };
11208 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
11209 .iter()
11210 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
11211 .sum::<f64>()
11212 / 4.0;
11213 let root_search = Search {
11214 lambda,
11215 ..match sb_q {
11216 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
11217 None => search,
11218 }
11219 };
11220 let base = snapshot(luma, chroma, (x128, y128), SIDE);
11221 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
11222 let mut cost = 0.0f64;
11223 let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
11224 for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
11225 let (w_mi, h_mi) = (w / 4, h / 4);
11226 let stack = find_mv_stack(
11227 grid,
11228 mr,
11229 mc,
11230 w_mi,
11231 h_mi,
11232 LAST_FRAME,
11233 mi_cols as usize,
11234 mi_rows as usize,
11235 );
11236 let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
11237 .iter()
11238 .map(|&(r, pic, _)| {
11239 (
11240 r,
11241 pic,
11242 crate::mvstack::find_mv_stack_compound(
11243 grid,
11244 mr,
11245 mc,
11246 w_mi,
11247 h_mi,
11248 (LAST_FRAME, r),
11249 mi_cols as usize,
11250 mi_rows as usize,
11251 grid.sign_bias_table(),
11252 &[(0, 0); 7],
11253 None,
11254 ),
11255 )
11256 })
11257 .collect();
11258 let found = search_skip_64(
11259 luma,
11260 chroma,
11261 (mc * 4, mr * 4),
11262 (w, h),
11263 &root_search,
11264 false,
11265 reference,
11266 &stack,
11267 &piece_compound,
11268 fctx,
11269 );
11270 match found {
11271 Some((mut c, mut block)) => {
11272 // lane-rectres: the same prediction with a REAL residual,
11273 // priced against the skip arm the search just committed to
11274 // the planes -- one mu chunk for a 64x64 square, two for a
11275 // half. The 64x64 squares are where libaom's own AB shapes
11276 // earn their keep.
11277 if rectres() && block.skip {
11278 c = search_rect_residual(
11279 luma,
11280 chroma,
11281 (mc * 4, mr * 4),
11282 (w, h),
11283 c,
11284 root_search.lambda,
11285 &root_search,
11286 &stack,
11287 &mut block,
11288 );
11289 }
11290 cost += c;
11291 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
11292 pieces.push(block);
11293 }
11294 None => {
11295 restore(luma, chroma, (x128, y128), SIDE, &base);
11296 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11297 return None;
11298 }
11299 }
11300 }
11301 let after = snapshot(luma, chroma, (x128, y128), SIDE);
11302 restore(luma, chroma, (x128, y128), SIDE, &base);
11303 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
11304 let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
11305 Some((
11306 cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
11307 lambda,
11308 [b0, b1, b2],
11309 after,
11310 ))
11311}
11312
11313/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
11314/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
11315/// SKIP, priced through the same `symbol_bits` path every other candidate
11316/// uses. The winner's prediction is committed to the planes (it IS the
11317/// reconstruction -- a skip block has no residual); the caller restores them
11318/// if the four quadrants come out cheaper.
11319///
11320/// `None` when no candidate could be coded at all (a `NEWMV` residual the
11321/// writer cannot name is simply not offered, and the other modes always are,
11322/// so this only happens if every candidate is refused).
11323fn search_skip_64(
11324 luma: &mut Plane,
11325 chroma: &mut [Plane; 2],
11326 (x, y): (usize, usize),
11327 // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
11328 // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
11329 // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
11330 // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
11331 // side (one square when it is square, two otherwise), and the residual
11332 // arm is only ever asked for at 64 -- a 128 block's residual is four
11333 // TX_64X64 units the writer has no path for.
11334 (bw, bh): (usize, usize),
11335 search: &Search,
11336 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
11337 // screen content -- see that function's doc).
11338 residual: bool,
11339 reference: &Picture,
11340 stack: &MvStack,
11341 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
11342 // superblock's 16x16-mi window, built off the same grid the tile writer
11343 // rebuilds it from (empty unless the frame carries `reference_select`).
11344 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11345 fctx: &crate::decode::FrameCtx,
11346) -> Option<(f64, BlockCoeffs)> {
11347 debug_assert!(
11348 (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
11349 "only a 64 root has a residual arm"
11350 );
11351 // The square units every trial below is taken on: the block itself when
11352 // it is square, its two halves otherwise. Luma first (in raster order),
11353 // then each chroma plane over the same tiling at half the side -- which is
11354 // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
11355 let sq = bw.min(bh);
11356 let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
11357 .flat_map(|plane| {
11358 let (ox, oy, s) = if plane == 0 {
11359 (x, y, sq)
11360 } else {
11361 (x / 2, y / 2, sq / 2)
11362 };
11363 (0..bh / sq).flat_map(move |j| {
11364 (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
11365 })
11366 })
11367 .collect();
11368 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11369 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11370 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11371 // What every candidate pays whatever its vector: `skip` coded 1, then
11372 // `is_inter` coded 1, then the LAST chain above.
11373 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
11374 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
11375 ref1: None,
11376 mv1: (0, 0),
11377 ref_frame: crate::mvstack::LAST_FRAME,
11378 mode,
11379 mv,
11380 ref_mv_idx,
11381 };
11382 let mut cands: Vec<(f64, InterInfo)> = vec![
11383 (
11384 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11385 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
11386 ),
11387 (
11388 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11389 info_of(InterMode::GlobalMv, (0, 0), 0),
11390 ),
11391 ];
11392 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11393 for idx in 1..=2usize {
11394 if let Some(e) = stack.entries.get(idx) {
11395 cands.push((
11396 near_bits + drl_bits_for(stack, 1, idx),
11397 info_of(InterMode::NearMv, e.mv, idx as u8),
11398 ));
11399 }
11400 }
11401 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
11402 // candidate below to pair with the second reference's NEAREST half.
11403 let mut last_new_mv: Option<(i32, i32)> = None;
11404 if leaf_new_mv() {
11405 let source_block = luma.source_block_rect(x, y, bw, bh);
11406 let (seeds, seed_n) = mv_seeds(stack);
11407 let found = motion::search(
11408 &reference.y,
11409 reference.width,
11410 luma.true_width,
11411 luma.true_height,
11412 &source_block,
11413 x,
11414 y,
11415 bw,
11416 bh,
11417 stack.pred_mv,
11418 &seeds[..seed_n],
11419 search.lambda,
11420 fctx,
11421 1,
11422 );
11423 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
11424 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
11425 last_new_mv = Some(mv);
11426 cands.push((
11427 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
11428 info_of(InterMode::NewMv, mv, ref_mv_idx),
11429 ));
11430 }
11431 }
11432
11433 let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
11434 for (bits, info) in cands {
11435 let trials: Vec<Trial> = units
11436 .iter()
11437 .map(|&(plane, px, py, s, is_luma)| {
11438 let (samples, stride, w, h) = match plane {
11439 0 => (
11440 &reference.y,
11441 reference.width,
11442 luma.true_width,
11443 luma.true_height,
11444 ),
11445 1 => (
11446 &reference.u,
11447 reference.width / 2,
11448 chroma[0].true_width,
11449 chroma[0].true_height,
11450 ),
11451 _ => (
11452 &reference.v,
11453 reference.width / 2,
11454 chroma[1].true_width,
11455 chroma[1].true_height,
11456 ),
11457 };
11458 let prediction =
11459 predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
11460 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
11461 // `skip` true: the trial is the prediction itself plus its SSE,
11462 // so no transform of any size is involved (the reason a 64x64
11463 // root can be coded at all before a forward TX_64X64 exists).
11464 target.code_from_prediction(
11465 px,
11466 py,
11467 s,
11468 &prediction,
11469 true,
11470 search.base_q_idx,
11471 search.deadzone,
11472 TxbSet::Luma32Inter,
11473 )
11474 })
11475 .collect();
11476 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
11477 if best.as_ref().is_none_or(|b| cost < b.0) {
11478 best = Some((cost, fixed + bits, info, trials));
11479 }
11480 }
11481
11482 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
11483 // superblock can form without a second motion search ([`b64_compound`]),
11484 // priced through the same `symbol_bits` path -- `fixed` minus the single
11485 // reference's tree, plus the pair tree and the compound mode.
11486 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
11487 let (ref1, g) = (*ref1, *g);
11488 // The whole `comp_mode` + reference-pair tree at the writer's own
11489 // contexts, for THIS pair (lane-ctx).
11490 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
11491 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
11492 let mode_bits_of =
11493 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
11494 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
11495 ref1: Some(ref1),
11496 mv1: mvs.1,
11497 ref_frame: crate::mvstack::LAST_FRAME,
11498 mode,
11499 mv: mvs.0,
11500 ref_mv_idx: 0,
11501 };
11502 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
11503 (
11504 cstack.nearest_mv,
11505 mode_bits_of(0),
11506 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
11507 ),
11508 (
11509 ((0, 0), (0, 0)),
11510 mode_bits_of(6),
11511 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
11512 ),
11513 ];
11514 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
11515 // above, its residual priced against compound stack entry 0 -- what
11516 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
11517 let cbase = cstack
11518 .entries
11519 .first()
11520 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
11521 if let Some(new_mv) = last_new_mv
11522 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
11523 {
11524 let mvs = (new_mv, cstack.nearest_mv.1);
11525 ccands.push((
11526 mvs,
11527 mode_bits_of(3) + b0,
11528 compound_info(InterMode::NewNearestMv, mvs),
11529 ));
11530 }
11531 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
11532 ccands.dedup_by_key(|c| c.0);
11533 for (mvs, bits, info) in ccands {
11534 let trials: Vec<Trial> = units
11535 .iter()
11536 .map(|&(plane, px, py, s, is_luma)| {
11537 let (r0, r1) = match plane {
11538 0 => (
11539 (
11540 reference.y.as_slice(),
11541 reference.width,
11542 luma.true_width,
11543 luma.true_height,
11544 ),
11545 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11546 ),
11547 1 => (
11548 (
11549 reference.u.as_slice(),
11550 reference.width / 2,
11551 chroma[0].true_width,
11552 chroma[0].true_height,
11553 ),
11554 (
11555 g.u.as_slice(),
11556 g.width / 2,
11557 chroma[0].true_width,
11558 chroma[0].true_height,
11559 ),
11560 ),
11561 _ => (
11562 (
11563 reference.v.as_slice(),
11564 reference.width / 2,
11565 chroma[1].true_width,
11566 chroma[1].true_height,
11567 ),
11568 (
11569 g.v.as_slice(),
11570 g.width / 2,
11571 chroma[1].true_width,
11572 chroma[1].true_height,
11573 ),
11574 ),
11575 };
11576 let prediction = predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
11577 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
11578 target.code_from_prediction(
11579 px,
11580 py,
11581 s,
11582 &prediction,
11583 true,
11584 search.base_q_idx,
11585 search.deadzone,
11586 TxbSet::Luma32Inter,
11587 )
11588 })
11589 .collect();
11590 let syntax = fixed - ref_bits + bits;
11591 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
11592 if best.as_ref().is_none_or(|b| cost < b.0) {
11593 best = Some((cost, syntax, info, trials));
11594 }
11595 }
11596 }
11597
11598 let (skip_cost, syntax, info, skip_trials) = best?;
11599
11600 // The winner's prediction coded with a REAL residual (lane-tx64): one
11601 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
11602 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
11603 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
11604 // the skip arm already chose is re-coded: the prediction with the lowest
11605 // SSE is also the cheapest residual to code, and a second 64x64 motion
11606 // search per superblock is the wall this root was taken to SAVE.
11607 //
11608 // Priced against the skip arm through the same `symbol_bits` path, so the
11609 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
11610 // arm charges 0 instead and adds its three planes' coefficient bits.
11611 let mut chosen = (skip_cost, true, skip_trials);
11612 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
11613 // into the plane, so the tail below does not commit over its units.
11614 let mut luma_committed = false;
11615 // The residual arm's luma levels and the `txfm_split` depth the writer
11616 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
11617 // four TX_32X32 units in 64x64 ones.
11618 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
11619 if residual {
11620 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
11621 // Square by construction (the `debug_assert` above), so `units` is
11622 // one entry per plane and `chosen.2[plane]` is that plane's trial.
11623 let residual_trials = [0usize, 1, 2].map(|plane| {
11624 let (target, px, py, s) = if plane == 0 {
11625 (&*luma, x, y, bw)
11626 } else {
11627 (&chroma[plane - 1], x / 2, y / 2, bw / 2)
11628 };
11629 target.code_from_prediction(
11630 px,
11631 py,
11632 s,
11633 &chosen.2[plane].reconstruction,
11634 false,
11635 search.base_q_idx,
11636 search.deadzone,
11637 sets[plane],
11638 )
11639 });
11640 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
11641 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
11642 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
11643 // four TX_32X32 units of `txfm_split = 1`, taken by the same
11644 // `commit_inter_luma` every other inter block's is (it commits the
11645 // winner and hands back the cost it took off the flat arm).
11646 let (levels, depth, gain, tx_types) = if b64_var_tx() {
11647 let second = info.ref1.and_then(|r1| {
11648 compound
11649 .iter()
11650 .find(|(r, _, _)| *r == r1)
11651 .map(|&(_, g, _)| {
11652 (
11653 info.mv1,
11654 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11655 )
11656 })
11657 });
11658 luma_committed = true;
11659 commit_inter_luma(
11660 luma,
11661 (x, y),
11662 bw,
11663 info.mv,
11664 (
11665 &reference.y,
11666 reference.width,
11667 luma.true_width,
11668 luma.true_height,
11669 ),
11670 search,
11671 &residual_trials[0],
11672 false,
11673 second,
11674 fctx,
11675 )
11676 } else {
11677 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
11678 };
11679 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
11680 + search.lambda * (syntax + unskip + coeff_bits)
11681 + gain;
11682 if cost < skip_cost {
11683 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11684 if depth == 1 {
11685 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11686 }
11687 luma_levels = Some((levels, depth, tx_types));
11688 chosen = (cost, false, residual_trials.to_vec());
11689 }
11690 }
11691
11692 let (cost, skip, trials) = chosen;
11693 // `commit_inter_luma` already wrote the residual arm's luma (its four
11694 // split units are not one 64-sided trial); a skip winner overwrites it.
11695 for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
11696 match plane {
11697 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
11698 0 => {}
11699 _ => chroma[plane - 1].commit(px, py, s, trial),
11700 }
11701 }
11702 Some((
11703 cost,
11704 BlockCoeffs {
11705 skip,
11706 inter: Some(info),
11707 // The chroma grids are whole TX_32X32; the luma one is the
11708 // 64-point transform's coded 32x32 corner at depth 0 and the
11709 // whole 64-sided block at depth 1 (lane-b64b).
11710 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
11711 luma_tx_types: match (skip, &luma_levels) {
11712 (false, Some((_, _, types))) => types.clone(),
11713 _ => Vec::new(),
11714 },
11715 luma: match (skip, &luma_levels) {
11716 (true, _) => Vec::new(),
11717 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
11718 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
11719 (false, None) => coeffs(&trials[0].levels, BLOCK),
11720 },
11721 u: if skip {
11722 Vec::new()
11723 } else {
11724 coeffs(&trials[1].levels, bw / 2)
11725 },
11726 v: if skip {
11727 Vec::new()
11728 } else {
11729 coeffs(&trials[2].levels, bw / 2)
11730 },
11731 ..BlockCoeffs::default()
11732 },
11733 ))
11734}
11735
11736fn search_inter_block(
11737 luma: &mut Plane,
11738 chroma: &mut [Plane; 2],
11739 (x, y): (usize, usize),
11740 search: &Search,
11741 mode_bits: &[f64; 13],
11742 reference: &Picture,
11743 stack: &MvStack,
11744 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
11745 // for the whole GOP, with the stack this block derives against it. Only
11746 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
11747 // second motion search would double the wall of the stage that already
11748 // owns most of it.
11749 extra: &[(i8, &Picture, &MvStack)],
11750 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
11751 // the caller off the same MI grid the tile writer will (empty unless the
11752 // frame carries `reference_select`).
11753 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
11754 // lane-av1obmc: the mi grid this search's neighbours were published into
11755 // (`record_mi`) and this block's own place in it -- what the OBMC
11756 // candidate's eligibility walk and neighbour plan read, the same state
11757 // the tile writer will read when it codes the `motion_mode` symbol.
11758 grid: &MiGrid,
11759 (mi_row, mi_col): (usize, usize),
11760 (mi_rows, mi_cols): (usize, usize),
11761 fctx: &crate::decode::FrameCtx,
11762) -> (BlockCoeffs, f64) {
11763 // `luma_set` is the INTRA candidates' table; the two inter candidates
11764 // below price their coefficients through `TxbSet::Luma32Inter`, which is
11765 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
11766 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
11767 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
11768 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
11769
11770 // skip / intra_inter symbol costs at a fixed context -- see this
11771 // function's doc comment.
11772 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
11773 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
11774
11775 struct Candidate {
11776 cost: f64,
11777 luma: Trial,
11778 u: Trial,
11779 v: Trial,
11780 mode: u8,
11781 skip: bool,
11782 inter: Option<InterInfo>,
11783 /// The mode/mv syntax this candidate pays for, apart from its
11784 /// residual -- what the OBMC candidate below has to re-pay when it
11785 /// re-prices the winner's prediction.
11786 mode_bits: f64,
11787 }
11788 let mut best: Option<Candidate> = None;
11789 let mut consider = |candidate: Candidate| {
11790 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
11791 best = Some(candidate);
11792 }
11793 };
11794
11795 // The chroma trial an intra candidate prices does not depend on `mode`
11796 // at all -- both planes always code `DC_PRED` here (a coding choice this
11797 // search inherited, not this loop's to second-guess) at the same `reach:
11798 // Reach::none()` -- so it is the same call with the same inputs on every
11799 // one of the thirteen iterations below; run it once and reuse the result
11800 // rather than repeat an already-priced transform/quantize/entropy call
11801 // twelve times for nothing (bit-identical: the value each iteration
11802 // reads back is exactly what it used to recompute).
11803 let u_trial = chroma[0].trial(
11804 At {
11805 x: x / 2,
11806 y: y / 2,
11807 side: BLOCK / 2,
11808 reach: Reach::none(),
11809 set: chroma_set,
11810 },
11811 DC_PRED,
11812 0,
11813 search.base_q_idx,
11814 search.deadzone,
11815 fctx,
11816 );
11817 let v_trial = chroma[1].trial(
11818 At {
11819 x: x / 2,
11820 y: y / 2,
11821 side: BLOCK / 2,
11822 reach: Reach::none(),
11823 set: chroma_set,
11824 },
11825 DC_PRED,
11826 0,
11827 search.base_q_idx,
11828 search.deadzone,
11829 fctx,
11830 );
11831
11832 let intra_modes: Vec<u8> = match search.top_k {
11833 Some(k) if k < search.modes.len() => {
11834 let scored = luma.intra_scores(
11835 At {
11836 x,
11837 y,
11838 side: BLOCK,
11839 reach,
11840 set: luma_set,
11841 },
11842 search.modes,
11843 mode_bits,
11844 search.lambda,
11845 fctx,
11846 );
11847 prune_by_sad(search.modes, scored, k)
11848 }
11849 _ => search.modes.to_vec(),
11850 };
11851 census_add(5, 1);
11852 census_add(
11853 6,
11854 if search.arf_leaf_intra {
11855 intra_modes.len()
11856 } else {
11857 0
11858 },
11859 );
11860 // lane-arfmode: arm 1 drops the whole-32 block's intra candidates at the
11861 // top ARF too -- the probe proved the ARF's intra AREA lives HERE, not at
11862 // the leaves (film A arm 1 vs control byte-identical with the leaf gate
11863 // alone), so "the 32x32 whole keeps intra as the scene-cut hatch" was a
11864 // hatch nothing else was using. Counted once per block.
11865 if search.arf_leaf_intra {
11866 for &mode in &intra_modes {
11867 let luma_trial = luma.trial(
11868 At {
11869 x,
11870 y,
11871 side: BLOCK,
11872 reach,
11873 set: luma_set,
11874 },
11875 mode,
11876 0,
11877 search.base_q_idx,
11878 search.deadzone,
11879 fctx,
11880 );
11881 let u = u_trial.clone();
11882 let v = v_trial.clone();
11883 let cost = luma_trial.sse
11884 + u.sse
11885 + v.sse
11886 + search.lambda
11887 * (luma_trial.bits
11888 + u.bits
11889 + v.bits
11890 + mode_bits[usize::from(mode)]
11891 + skip_bits(false)
11892 + intra_inter_bits(false));
11893 consider(Candidate {
11894 cost,
11895 luma: luma_trial,
11896 u,
11897 v,
11898 mode,
11899 skip: false,
11900 inter: None,
11901 mode_bits: mode_bits[usize::from(mode)],
11902 });
11903 }
11904 } else {
11905 arfmode_hit(0);
11906 }
11907
11908 // The reference frame buffer a spec decoder holds is exactly the true
11909 // (unpadded) coded extent -- a superblock whose partition stops early at
11910 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
11911 // beyond it, so those samples are never part of the decoded picture.
11912 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
11913 // reference sample position clamp), not to this crate's own
11914 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
11915 // here would let a fractional-pel read past the true edge pick up this
11916 // encoder's own uncoded padding instead of the true edge's replicated
11917 // value a decoder computes.
11918 let ref_luma = (
11919 &reference.y,
11920 reference.width,
11921 luma.true_width,
11922 luma.true_height,
11923 );
11924 let ref_u = (
11925 &reference.u,
11926 reference.width / 2,
11927 chroma[0].true_width,
11928 chroma[0].true_height,
11929 );
11930 let ref_v = (
11931 &reference.v,
11932 reference.width / 2,
11933 chroma[1].true_width,
11934 chroma[1].true_height,
11935 );
11936 // Every single-reference mode the writer can code (spec 5.11.24's symbol
11937 // chain, mirrored by `tile::write_inter_mode`), priced with the static
11938 // CDFs at this block's own stack contexts. A candidate is a motion
11939 // vector plus the cheapest syntax that reaches it, so two modes landing
11940 // on the same vector share one set of trials: the added modes cost
11941 // mode-bit arithmetic, not another motion compensation.
11942 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11943 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11944 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
11945 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
11946 // the loop cannot reach is never offered below -- every candidate's
11947 // index is one this same loop walks to.
11948 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
11949 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11950 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
11951 (
11952 stack.nearest_mv,
11953 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11954 InterInfo {
11955 ref1: None,
11956 mv1: (0, 0),
11957 ref_frame: crate::mvstack::LAST_FRAME,
11958 mode: InterMode::NearestMv,
11959 mv: stack.nearest_mv,
11960 ref_mv_idx: 0,
11961 },
11962 ),
11963 // GLOBALMV is the identity model's zero vector -- this encoder writes
11964 // no `gm_params` -- and the cheapest syntax of the four on the static
11965 // content where that vector is also the right one.
11966 (
11967 (0, 0),
11968 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11969 InterInfo {
11970 ref1: None,
11971 mv1: (0, 0),
11972 ref_frame: crate::mvstack::LAST_FRAME,
11973 mode: InterMode::GlobalMv,
11974 mv: (0, 0),
11975 ref_mv_idx: 0,
11976 },
11977 ),
11978 ];
11979 let near_bits =
11980 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11981 for idx in 1..=2usize {
11982 if let Some(e) = stack.entries.get(idx) {
11983 cands.push((
11984 e.mv,
11985 near_bits + drl_bits(1, idx),
11986 InterInfo {
11987 ref1: None,
11988 mv1: (0, 0),
11989 ref_frame: crate::mvstack::LAST_FRAME,
11990 mode: InterMode::NearMv,
11991 mv: e.mv,
11992 ref_mv_idx: idx as u8,
11993 },
11994 ));
11995 }
11996 }
11997
11998 let source_block = luma.source_block(x, y, BLOCK);
11999 let (seeds, seed_n) = mv_seeds(stack);
12000 #[cfg(test)]
12001 let t = stage_start();
12002 let found = motion::search(
12003 ref_luma.0,
12004 ref_luma.1,
12005 ref_luma.2,
12006 ref_luma.3,
12007 &source_block,
12008 x,
12009 y,
12010 BLOCK,
12011 BLOCK,
12012 stack.pred_mv,
12013 &seeds[..seed_n],
12014 search.lambda,
12015 fctx,
12016 1,
12017 );
12018 #[cfg(test)]
12019 stage_since(0, t);
12020 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
12021 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
12022 // costs, for the census below (`None` when the writer cannot name it).
12023 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
12024 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
12025 // the same vector costs a different residual from each: take the index
12026 // whose residual plus DRL bits is cheapest, not entry 0 by default.
12027 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
12028 newmv_syntax = Some((mv, bits));
12029 cands.push((
12030 mv,
12031 last_ref_bits
12032 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
12033 + bits
12034 + mv_rate_surcharge(bits),
12035 InterInfo {
12036 ref1: None,
12037 mv1: (0, 0),
12038 ref_frame: crate::mvstack::LAST_FRAME,
12039 mode: InterMode::NewMv,
12040 mv,
12041 ref_mv_idx,
12042 },
12043 ));
12044 }
12045
12046 // Each extra reference's own `NEWMV` vector, for the compound
12047 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
12048 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
12049 for &(ref_frame, g, gstack) in extra {
12050 let g_ref_bits = single_ref_bits(ref_frame, gstack);
12051 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
12052 cands.push((
12053 gstack.nearest_mv,
12054 g_ref_bits
12055 + g_not_new
12056 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
12057 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
12058 InterInfo {
12059 ref1: None,
12060 mv1: (0, 0),
12061 ref_frame,
12062 mode: InterMode::NearestMv,
12063 mv: gstack.nearest_mv,
12064 ref_mv_idx: 0,
12065 },
12066 ));
12067 cands.push((
12068 (0, 0),
12069 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
12070 InterInfo {
12071 ref1: None,
12072 mv1: (0, 0),
12073 ref_frame,
12074 mode: InterMode::GlobalMv,
12075 mv: (0, 0),
12076 ref_mv_idx: 0,
12077 },
12078 ));
12079 // A motion search of this reference's own: without it, GOLDEN/ALTREF
12080 // can only be coded at a vector some neighbour already found, which
12081 // is why they carried a third of the inter blocks at their two
12082 // search-free modes alone.
12083 // The search is skipped when this reference's own NEARESTMV already
12084 // prices out `margin` times better than LAST's best vector does --
12085 // one candidate evaluation (`motion::cost_at`) standing in for a
12086 // whole search of ~50.
12087 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
12088 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
12089 // neighbour already found, which is how GOLDEN/ALTREF were offered
12090 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
12091 // own value from the second motion search's wall.
12092 let searched =
12093 extra_ref_new_mv() && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
12094 let margin = extra_new_skip_margin();
12095 if searched {
12096 newmv_census_global(0);
12097 }
12098 let skip_search = searched
12099 && margin > 0.0
12100 && motion::cost_at(
12101 &g.y,
12102 g.width,
12103 luma.true_width,
12104 luma.true_height,
12105 &source_block,
12106 x,
12107 y,
12108 BLOCK,
12109 BLOCK,
12110 gstack.nearest_mv,
12111 gstack.pred_mv,
12112 search.lambda,
12113 fctx,
12114 ) * margin
12115 <= found.cost;
12116 if skip_search {
12117 newmv_census_global(1);
12118 }
12119 if searched && !skip_search {
12120 let (gseeds, gn) = mv_seeds(gstack);
12121 #[cfg(test)]
12122 let t = stage_start();
12123 let gfound = motion::search(
12124 &g.y,
12125 g.width,
12126 luma.true_width,
12127 luma.true_height,
12128 &source_block,
12129 x,
12130 y,
12131 BLOCK,
12132 BLOCK,
12133 gstack.pred_mv,
12134 &gseeds[..gn],
12135 search.lambda,
12136 fctx,
12137 ref_distance(ref_frame),
12138 );
12139 #[cfg(test)]
12140 stage_since(0, t);
12141 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
12142 extra_new_mvs.push((ref_frame, gmv));
12143 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
12144 cands.push((
12145 gmv,
12146 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
12147 InterInfo {
12148 ref1: None,
12149 mv1: (0, 0),
12150 ref_frame,
12151 mode: InterMode::NewMv,
12152 mv: gmv,
12153 ref_mv_idx,
12154 },
12155 ));
12156 }
12157 }
12158 }
12159
12160 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
12161 // trial set each: both references predict the block and the two
12162 // predictions are averaged, which is what pays on content where neither
12163 // reference alone is right. Priced with the same static-CDF approximation
12164 // the single-reference candidates use, plus the compound-only symbols
12165 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
12166 // The two compound-mode arms, each measured alone on the BD gate before
12167 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
12168 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
12169 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
12170 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
12171 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
12172 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
12173 // the keep rule. Still behind the knob.
12174 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
12175 let half_new = true;
12176 for (ref1, g, cstack) in compound {
12177 let (ref1, g) = (*ref1, *g);
12178 // The whole `comp_mode` + reference-pair tree at the writer's own
12179 // contexts, for THIS pair (lane-ctx).
12180 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
12181 let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
12182 let mode_bits_of =
12183 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
12184 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
12185 (
12186 cstack.nearest_mv,
12187 mode_bits_of(0),
12188 InterInfo {
12189 ref_frame: crate::mvstack::LAST_FRAME,
12190 mode: InterMode::NearestNearestMv,
12191 mv: cstack.nearest_mv.0,
12192 mv1: cstack.nearest_mv.1,
12193 ref1: Some(ref1),
12194 ref_mv_idx: 0,
12195 },
12196 ),
12197 (
12198 ((0, 0), (0, 0)),
12199 mode_bits_of(6),
12200 InterInfo {
12201 ref_frame: crate::mvstack::LAST_FRAME,
12202 mode: InterMode::GlobalGlobalMv,
12203 mv: (0, 0),
12204 mv1: (0, 0),
12205 ref1: Some(ref1),
12206 ref_mv_idx: 0,
12207 },
12208 ),
12209 ];
12210 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
12211 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
12212 // the stack is deep enough for that walk to read one.
12213 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
12214 let drl = if cstack.entries.len() > 2 {
12215 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
12216 } else {
12217 0.0
12218 };
12219 ccands.push((
12220 (e.mv0, e.mv1),
12221 mode_bits_of(1) + drl,
12222 InterInfo {
12223 ref_frame: crate::mvstack::LAST_FRAME,
12224 mode: InterMode::NearNearMv,
12225 mv: e.mv0,
12226 mv1: e.mv1,
12227 ref1: Some(ref1),
12228 ref_mv_idx: 0,
12229 },
12230 ));
12231 }
12232 // The half-new modes and `NEW_NEWMV`, all seeded from the two
12233 // single-reference searches this block already ran -- no joint search
12234 // of its own. Every residual is priced against stack entry 0, which
12235 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
12236 let cbase = cstack
12237 .entries
12238 .first()
12239 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
12240 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
12241 ccands.push((
12242 (mv, cstack.nearest_mv.1),
12243 mode_bits_of(3) + b0,
12244 InterInfo {
12245 ref_frame: crate::mvstack::LAST_FRAME,
12246 mode: InterMode::NewNearestMv,
12247 mv,
12248 mv1: cstack.nearest_mv.1,
12249 ref1: Some(ref1),
12250 ref_mv_idx: 0,
12251 },
12252 ));
12253 }
12254 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
12255 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
12256 ccands.push((
12257 (cstack.nearest_mv.0, mv1),
12258 mode_bits_of(2) + b1,
12259 InterInfo {
12260 ref_frame: crate::mvstack::LAST_FRAME,
12261 mode: InterMode::NearestNewMv,
12262 mv: cstack.nearest_mv.0,
12263 mv1,
12264 ref1: Some(ref1),
12265 ref_mv_idx: 0,
12266 },
12267 ));
12268 }
12269 let base = cbase;
12270 if let (Some(b0), Some(b1)) =
12271 (mv_residual_bits(mv, base.0), mv_residual_bits(mv1, base.1))
12272 {
12273 ccands.push((
12274 (mv, mv1),
12275 mode_bits_of(7) + b0 + b1,
12276 InterInfo {
12277 ref_frame: crate::mvstack::LAST_FRAME,
12278 mode: InterMode::NewNewMv,
12279 mv,
12280 mv1,
12281 ref1: Some(ref1),
12282 ref_mv_idx: 0,
12283 },
12284 ));
12285 }
12286 }
12287 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
12288 ccands.dedup_by_key(|c| c.0);
12289 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
12290 let g_u = (
12291 g.u.as_slice(),
12292 g.width / 2,
12293 chroma[0].true_width,
12294 chroma[0].true_height,
12295 );
12296 let g_v = (
12297 g.v.as_slice(),
12298 g.width / 2,
12299 chroma[1].true_width,
12300 chroma[1].true_height,
12301 );
12302 for (mvs, bits, info) in ccands {
12303 let luma_trial = mc_trial_compound(
12304 luma,
12305 x,
12306 y,
12307 BLOCK,
12308 mvs,
12309 true,
12310 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12311 g_luma,
12312 search.base_q_idx,
12313 search.deadzone,
12314 TxbSet::Luma32Inter,
12315 fctx,
12316 );
12317 let u = mc_trial_compound(
12318 &chroma[0],
12319 x / 2,
12320 y / 2,
12321 BLOCK / 2,
12322 mvs,
12323 false,
12324 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12325 g_u,
12326 search.base_q_idx,
12327 search.deadzone,
12328 chroma_set,
12329 fctx,
12330 );
12331 let v = mc_trial_compound(
12332 &chroma[1],
12333 x / 2,
12334 y / 2,
12335 BLOCK / 2,
12336 mvs,
12337 false,
12338 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12339 g_v,
12340 search.base_q_idx,
12341 search.deadzone,
12342 chroma_set,
12343 fctx,
12344 );
12345 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12346 && u.levels.iter().all(|&l| l == 0)
12347 && v.levels.iter().all(|&l| l == 0);
12348 let cost = luma_trial.sse
12349 + u.sse
12350 + v.sse
12351 + search.lambda
12352 * (skip_bits(skip)
12353 + intra_inter_bits(true)
12354 + bits
12355 + if skip {
12356 0.0
12357 } else {
12358 luma_trial.bits + u.bits + v.bits
12359 });
12360 consider(Candidate {
12361 cost,
12362 luma: luma_trial,
12363 u,
12364 v,
12365 mode: DC_PRED,
12366 skip,
12367 mode_bits: bits,
12368 inter: Some(info),
12369 });
12370 }
12371 }
12372
12373 // One trial set per distinct (reference, vector) pair: sort, cheapest
12374 // syntax first, and drop the rest of each pair's run.
12375 cands.sort_by(|a, b| {
12376 (a.2.ref_frame, a.0)
12377 .cmp(&(b.2.ref_frame, b.0))
12378 .then(a.1.total_cmp(&b.1))
12379 });
12380 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
12381 census_add(7, cands.len());
12382 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
12383 // this block reaches WITHOUT it, taken inside the one loop that prices
12384 // them all (a second pricing pass would be a second oracle).
12385 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
12386 {
12387 for (mv, mode_bits_inter, info) in cands {
12388 let (ref_luma, ref_u, ref_v) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame)
12389 {
12390 Some(&(_, g, _)) => (
12391 (&g.y, g.width, luma.true_width, luma.true_height),
12392 (
12393 &g.u,
12394 g.width / 2,
12395 chroma[0].true_width,
12396 chroma[0].true_height,
12397 ),
12398 (
12399 &g.v,
12400 g.width / 2,
12401 chroma[1].true_width,
12402 chroma[1].true_height,
12403 ),
12404 ),
12405 None => (ref_luma, ref_u, ref_v),
12406 };
12407 let luma_trial = mc_trial(
12408 luma,
12409 x,
12410 y,
12411 BLOCK,
12412 mv,
12413 true,
12414 ref_luma.0,
12415 ref_luma.1,
12416 ref_luma.2,
12417 ref_luma.3,
12418 false,
12419 search.base_q_idx,
12420 search.deadzone,
12421 TxbSet::Luma32Inter,
12422 fctx,
12423 );
12424 let u = mc_trial(
12425 &chroma[0],
12426 x / 2,
12427 y / 2,
12428 BLOCK / 2,
12429 mv,
12430 false,
12431 ref_u.0,
12432 ref_u.1,
12433 ref_u.2,
12434 ref_u.3,
12435 false,
12436 search.base_q_idx,
12437 search.deadzone,
12438 chroma_set,
12439 fctx,
12440 );
12441 let v = mc_trial(
12442 &chroma[1],
12443 x / 2,
12444 y / 2,
12445 BLOCK / 2,
12446 mv,
12447 false,
12448 ref_v.0,
12449 ref_v.1,
12450 ref_v.2,
12451 ref_v.3,
12452 false,
12453 search.base_q_idx,
12454 search.deadzone,
12455 chroma_set,
12456 fctx,
12457 );
12458 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12459 && u.levels.iter().all(|&l| l == 0)
12460 && v.levels.iter().all(|&l| l == 0);
12461 let cost = luma_trial.sse
12462 + u.sse
12463 + v.sse
12464 + search.lambda
12465 * (skip_bits(skip)
12466 + intra_inter_bits(true)
12467 + mode_bits_inter
12468 + if skip {
12469 0.0
12470 } else {
12471 luma_trial.bits + u.bits + v.bits
12472 });
12473 consider(Candidate {
12474 cost,
12475 luma: luma_trial,
12476 u,
12477 v,
12478 mode: DC_PRED,
12479 skip,
12480 mode_bits: mode_bits_inter,
12481 inter: Some(info),
12482 });
12483 if newmv_census_on() {
12484 if info.mode == InterMode::NewMv
12485 && info.ref1.is_none()
12486 && info.ref_frame == crate::mvstack::LAST_FRAME
12487 {
12488 new_cost = cost;
12489 } else {
12490 other_cost = other_cost.min(cost);
12491 }
12492 }
12493 }
12494 }
12495 if let Some((new_mv, bits)) = newmv_syntax {
12496 newmv_census_block(
12497 BLOCK,
12498 true,
12499 new_cost,
12500 other_cost,
12501 new_mv,
12502 stack.nearest_mv,
12503 bits,
12504 );
12505 } else {
12506 newmv_census_block(
12507 BLOCK,
12508 false,
12509 f64::INFINITY,
12510 other_cost,
12511 mv,
12512 stack.nearest_mv,
12513 0.0,
12514 );
12515 }
12516
12517 let best = best.expect("the search offers at least the intra modes");
12518 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
12519 // offered to the SINGLE-REFERENCE winner only -- libaom's
12520 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
12521 // compound block, so the writer codes no symbol for one. The prediction
12522 // is built by the DECODER's own plan and blend
12523 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
12524 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
12525 // this search's `grid` already carries, so what is priced here is what a
12526 // decoder reconstructs -- never a second implementation of the blend.
12527 //
12528 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
12529 // on). Native crop BD, the standing recipe, with it on against the same
12530 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
12531 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
12532 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
12533 // one UP -- the keep rule wants two down and one flat, so it stays off.
12534 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
12535 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
12536 // things bound it and are the upgrade path: only the 32x32 winner is
12537 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
12538 // that is where libaom cashes most of its OBMC gain), and the symbol/
12539 // residual price here is the static-CDF estimate.
12540 let mut best = best;
12541 let mut motion_won = 0u8;
12542 if let Some(info) = best
12543 .inter
12544 .filter(|i| i.ref1.is_none() && (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on()))
12545 {
12546 let mut refs: [Option<&Picture>; 8] = [None; 8];
12547 refs[LAST_FRAME as usize] = Some(reference);
12548 for &(r, p, _) in extra {
12549 refs[r as usize] = Some(p);
12550 }
12551 // This block's OWN reference planes: the single-reference winner may
12552 // be one of the extra references, not LAST.
12553 let planes: [(&[u16], usize, usize, usize); 3] =
12554 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12555 Some(&(_, g, _)) => [
12556 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12557 (
12558 g.u.as_slice(),
12559 g.width / 2,
12560 chroma[0].true_width,
12561 chroma[0].true_height,
12562 ),
12563 (
12564 g.v.as_slice(),
12565 g.width / 2,
12566 chroma[1].true_width,
12567 chroma[1].true_height,
12568 ),
12569 ],
12570 None => [
12571 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12572 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12573 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12574 ],
12575 };
12576 // The alphabet `tile::write_motion_mode` will code this block's
12577 // symbol against, mirrored term for term (libaom
12578 // `motion_mode_allowed`).
12579 let warp_alphabet = warp_on()
12580 && crate::decode::num_proj_ref(
12581 grid,
12582 mi_row,
12583 mi_col,
12584 8,
12585 8,
12586 mi_cols,
12587 mi_rows,
12588 info.ref_frame,
12589 fctx,
12590 ) >= 1;
12591 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
12592 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
12593 if crate::envflags::env_flag!("EC_AV1_OBMC") {
12594 if let Some(pred) = obmc_prediction(
12595 grid,
12596 (mi_row, mi_col),
12597 (mi_rows, mi_cols),
12598 (x, y),
12599 BLOCK,
12600 info.mv,
12601 &refs,
12602 planes,
12603 reference.width,
12604 fctx,
12605 ) {
12606 candidates.push((1, pred));
12607 }
12608 }
12609 if warp_alphabet {
12610 if let Some(pred) = warp_prediction(
12611 grid,
12612 (mi_row, mi_col),
12613 (mi_rows, mi_cols),
12614 (x, y),
12615 BLOCK,
12616 info.mv,
12617 info.ref_frame,
12618 planes,
12619 fctx,
12620 ) {
12621 candidates.push((2, pred));
12622 }
12623 }
12624 for (motion, pred) in candidates {
12625 let luma_trial = luma.code_from_prediction(
12626 x,
12627 y,
12628 BLOCK,
12629 &pred[0],
12630 false,
12631 search.base_q_idx,
12632 search.deadzone,
12633 TxbSet::Luma32Inter,
12634 );
12635 let u = chroma[0].code_from_prediction(
12636 x / 2,
12637 y / 2,
12638 BLOCK / 2,
12639 &pred[1],
12640 false,
12641 search.base_q_idx,
12642 search.deadzone,
12643 chroma_set,
12644 );
12645 let v = chroma[1].code_from_prediction(
12646 x / 2,
12647 y / 2,
12648 BLOCK / 2,
12649 &pred[2],
12650 false,
12651 search.base_q_idx,
12652 search.deadzone,
12653 chroma_set,
12654 );
12655 let skip = luma_trial.levels.iter().all(|&l| l == 0)
12656 && u.levels.iter().all(|&l| l == 0)
12657 && v.levels.iter().all(|&l| l == 0);
12658 let cost = luma_trial.sse
12659 + u.sse
12660 + v.sse
12661 + search.lambda
12662 * (skip_bits(skip)
12663 + intra_inter_bits(true)
12664 + best.mode_bits
12665 + mm(motion)
12666 + if skip {
12667 0.0
12668 } else {
12669 luma_trial.bits + u.bits + v.bits
12670 });
12671 if cost < best.cost + search.lambda * mm(motion_won) {
12672 motion_won = motion;
12673 best = Candidate {
12674 cost,
12675 luma: luma_trial,
12676 u,
12677 v,
12678 mode: DC_PRED,
12679 skip,
12680 mode_bits: best.mode_bits,
12681 inter: best.inter,
12682 };
12683 }
12684 }
12685 }
12686 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
12687 // default OFF): the four 16x16 units of `commit_inter_luma` against the
12688 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
12689 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
12690 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
12691 // it, and it is worse again on the deciding native table: film 1080p
12692 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
12693 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
12694 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
12695 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
12696 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
12697 // +28.4/+47.4/-4.0 -- the native table decides.)
12698 //
12699 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
12700 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
12701 // either, and the census names the row: the split units' own set
12702 // `Luma16Inter` is priced within 1.4% of what it is written at in every
12703 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
12704 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
12705 // so a perfect pricer would split even more, and more splitting is what
12706 // measured worse. The four extra txb_skip/eob symbols simply cost more
12707 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
12708 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
12709 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
12710 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
12711 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
12712 // plain translation, which is not the prediction it was priced from.
12713 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
12714 Some(info) => {
12715 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12716 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12717 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
12718 };
12719 let second = info.ref1.and_then(|r| {
12720 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
12721 (
12722 info.mv1,
12723 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
12724 )
12725 })
12726 });
12727 match info.ref1.is_some() && second.is_none() {
12728 true => {
12729 luma.commit(x, y, BLOCK, &best.luma);
12730 (best.luma.levels.clone(), 0, 0.0, Vec::new())
12731 }
12732 false => commit_inter_luma(
12733 luma,
12734 (x, y),
12735 BLOCK,
12736 info.mv,
12737 own,
12738 search,
12739 &best.luma,
12740 best.skip,
12741 second,
12742 fctx,
12743 ),
12744 }
12745 }
12746 None => {
12747 luma.commit(x, y, BLOCK, &best.luma);
12748 (best.luma.levels.clone(), 0, 0.0, Vec::new())
12749 }
12750 };
12751 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
12752 let [bu, bv] = match (
12753 best.inter.filter(|_| motion_won == 0),
12754 luma_tx_types.first().copied(),
12755 ) {
12756 (Some(info), Some(t)) => {
12757 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
12758 Some(&(_, g, _)) => (
12759 (
12760 g.u.as_slice(),
12761 g.width / 2,
12762 chroma[0].true_width,
12763 chroma[0].true_height,
12764 ),
12765 (
12766 g.v.as_slice(),
12767 g.width / 2,
12768 chroma[1].true_width,
12769 chroma[1].true_height,
12770 ),
12771 ),
12772 None => (
12773 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
12774 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
12775 ),
12776 };
12777 let sec = info.ref1.and_then(|r| {
12778 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
12779 (
12780 info.mv1,
12781 [
12782 (
12783 g.u.as_slice(),
12784 g.width / 2,
12785 chroma[0].true_width,
12786 chroma[0].true_height,
12787 ),
12788 (
12789 g.v.as_slice(),
12790 g.width / 2,
12791 chroma[1].true_width,
12792 chroma[1].true_height,
12793 ),
12794 ],
12795 )
12796 })
12797 });
12798 recode_inter_chroma(
12799 chroma,
12800 (x, y),
12801 BLOCK,
12802 info.mv,
12803 [ou, ov],
12804 sec,
12805 search,
12806 chroma_set,
12807 t,
12808 fctx,
12809 )
12810 .unwrap_or([best.u, best.v])
12811 }
12812 _ => [best.u, best.v],
12813 };
12814 let best = Candidate {
12815 u: bu,
12816 v: bv,
12817 ..best
12818 };
12819 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
12820 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
12821 (
12822 BlockCoeffs {
12823 luma_tx_types,
12824 angle_delta_y: 0,
12825 cfl_alphas: None,
12826 filter_intra: None,
12827 luma: coeffs(&levels, BLOCK),
12828 u: coeffs(&best.u.levels, BLOCK / 2),
12829 v: coeffs(&best.v.levels, BLOCK / 2),
12830 mode: best.mode,
12831 uv_mode: DC_PRED,
12832 skip: best.skip,
12833 inter: best.inter,
12834 motion_mode: motion_won,
12835 eight: None,
12836 dv: None,
12837 palette: None,
12838 palette_uv: None,
12839 tx_depth,
12840 },
12841 best.cost + dcost,
12842 )
12843}
12844
12845/// lane-av1tpl: the strength `k` of the temporal lambda weighting
12846/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
12847/// is what every measurement before this lane was taken on. Swept by
12848/// `EC_AV1_TPL=<k>`.
12849///
12850/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
12851/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
12852/// baseline exactly, which is the control the rest of the table is read
12853/// against:
12854///
12855/// | k | film 1080p | film 2160p | screen |
12856/// |---|---|---|---|
12857/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
12858/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
12859/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
12860/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
12861/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
12862///
12863/// 0.5 is the only arm that is at least flat on every row and down on five of
12864/// the six columns, so it ships as the default. The lookahead pass that feeds
12865/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
12866const TPL_STRENGTH: f64 = 0.5;
12867
12868/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
12869/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
12870/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
12871/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
12872///
12873/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
12874/// nothing to vary the quantizer BY and codes no delta syntax at all.
12875fn deltaq_res_log2() -> Option<u8> {
12876 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
12877 u8::MAX => {}
12878 4 => return None,
12879 r => return Some(r),
12880 }
12881 match crate::envflags::var("EC_AV1_DELTAQ")
12882 .ok()
12883 .as_deref()
12884 .map(str::trim)
12885 {
12886 Some("0") => None,
12887 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
12888 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
12889 }
12890}
12891
12892/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
12893/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
12894/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
12895/// speed presets take, because the streams every other test pins move under
12896/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
12897static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
12898
12899/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
12900#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
12901pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
12902 DELTAQ_OVERRIDE.store(
12903 res_log2.unwrap_or(u8::MAX),
12904 std::sync::atomic::Ordering::Relaxed,
12905 );
12906}
12907
12908/// How much of the derived qindex step is actually taken
12909/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
12910fn deltaq_k() -> f64 {
12911 crate::envflags::var("EC_AV1_DELTAQ_K")
12912 .ok()
12913 .and_then(|v| v.trim().parse::<f64>().ok())
12914 .filter(|k| k.is_finite() && *k >= 0.0)
12915 .unwrap_or(1.0)
12916}
12917
12918/// The largest qindex the map may move a superblock by, either way
12919/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
12920/// deltaq around a quarter of the base qindex).
12921fn deltaq_clamp() -> i32 {
12922 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
12923 .ok()
12924 .and_then(|v| v.trim().parse::<i32>().ok())
12925 .filter(|c| (0..=63).contains(c))
12926 .unwrap_or(16)
12927}
12928
12929/// The qindex a lambda factor `f` asks for, derived rather than fitted.
12930///
12931/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
12932/// square of the quantizer step (`encode_inter_frame`'s own
12933/// `lambda = .. * step * step`), so the step this superblock wants is
12934/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
12935/// step ratio is inverted through the table itself -- the index whose `ac_q`
12936/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
12937/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
12938/// bounds it, and the answer is snapped onto the `res` grid so that every
12939/// superblock's qindex is congruent to `base` and the coded delta is a whole
12940/// number of steps.
12941fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
12942 let base_ac = f64::from(ac_q(8, i32::from(base)));
12943 let target = base_ac * f.max(1e-6).sqrt();
12944 let exact = (1..=255)
12945 .min_by(|&a, &b| {
12946 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
12947 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
12948 })
12949 .expect("the qindex range is not empty")
12950 - i32::from(base);
12951 let want = (exact as f64 * k).round() as i32;
12952 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
12953 // and need not be a whole number of steps, and clamping afterwards would
12954 // hand back a qindex that is not congruent to `base`.
12955 let max_steps = clamp / res;
12956 let steps = (want as f64 / f64::from(res)).round() as i32;
12957 let delta = steps.clamp(-max_steps, max_steps) * res;
12958 (i32::from(base) + delta).clamp(1, 255) as u8
12959}
12960
12961/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
12962/// objective would, from the SAME tpl dependence ratio our own map already
12963/// carries (`EC_AV1_DQ_TPL=1`).
12964///
12965/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
12966/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
12967/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
12968/// same expression at frame scope) by it, and asks
12969/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
12970/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
12971/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
12972/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
12973/// libaom reads `r0`. The offset is clamped to libaom's own
12974/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
12975/// twice the +-16 qindex [`deltaq_for_factor`] allows.
12976///
12977/// Two things differ from [`deltaq_for_factor`] and both are the point of the
12978/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
12979/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
12980/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
12981/// much stronger for the same map. `strength` scales the offset.
12982fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
12983 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
12984 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
12985 let exact = (1..=255)
12986 .min_by(|&a, &b| {
12987 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
12988 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
12989 })
12990 .expect("the qindex range is not empty")
12991 - i32::from(base);
12992 let want = exact as f64 * strength;
12993 // Snapped onto the `res` grid first, so the coded delta is a whole number
12994 // of steps, then bounded by libaom's own `res * 9 - 1`.
12995 let max_steps = (res * 9 - 1) / res;
12996 let steps = (want / f64::from(res)).round() as i32;
12997 let delta = steps.clamp(-max_steps, max_steps) * res;
12998 (i32::from(base) + delta).clamp(1, 255) as u8
12999}
13000
13001/// The frame-level `r0` libaom's objective divides by: the log-mean of
13002/// `1 + r` over the frame's cells, minus 1.
13003fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
13004 if ratio.is_empty() {
13005 return 0.0;
13006 }
13007 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
13008 m.exp() - 1.0
13009}
13010
13011/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
13012/// [`deltaq_for_factor`] derivation.
13013///
13014/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
13015/// the strength (default 1.0 = libaom's own offset when the flag armed it);
13016/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
13017fn dq_tpl_strength(level: DqLevel) -> Option<f64> {
13018 let m = dq_level_k()[level as usize];
13019 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
13020 .ok()
13021 .and_then(|v| v.trim().parse::<f64>().ok())
13022 .filter(|k| k.is_finite() && *k >= 0.0);
13023 let base = match crate::envflags::var("EC_AV1_DQ_TPL")
13024 .ok()
13025 .as_deref()
13026 .map(str::trim)
13027 {
13028 Some("0") => return None,
13029 Some(_) => Some(env_k.unwrap_or(1.0)),
13030 None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))),
13031 };
13032 base.map(|k| k * m).filter(|k| *k > 0.0)
13033}
13034
13035/// lane-arfq: which pyramid level the frame asking for a
13036/// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it
13037/// codes no `delta_q` syntax at all (the whole lever lives in
13038/// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the
13039/// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job.
13040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13041pub(crate) enum DqLevel {
13042 /// The mini-GOP's own hidden `ALTREF`, which every other frame of the
13043 /// group predicts from (directly or through the mid level).
13044 TopArf = 0,
13045 /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it.
13046 MidArf = 1,
13047 /// A shown leaf -- and every frame of the flat, non-pyramid path.
13048 Leaf = 2,
13049}
13050
13051/// The per-level multiplier on the [`dq_tpl_strength`] the preset carries:
13052/// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else
13053/// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes
13054/// no `delta_q` (see [`DqLevel`]).
13055fn dq_level_k() -> [f64; 3] {
13056 dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref())
13057}
13058
13059/// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an
13060/// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry.
13061fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] {
13062 let mut k = crate::speed::DQ_LEVEL_K;
13063 if let Some(spec) = spec {
13064 for (slot, field) in k.iter_mut().zip(spec.split(':')) {
13065 if let Some(v) = field
13066 .trim()
13067 .parse::<f64>()
13068 .ok()
13069 .filter(|v: &f64| v.is_finite() && *v >= 0.0)
13070 {
13071 *slot = v;
13072 }
13073 }
13074 }
13075 k
13076}
13077
13078/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
13079/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
13080/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
13081/// the same tpl map -- and which of the two the frame actually coded.
13082fn dq_census() -> bool {
13083 crate::envflags::var("EC_AV1_DQ_CENSUS")
13084 .ok()
13085 .as_deref()
13086 .map(str::trim)
13087 == Some("1")
13088}
13089
13090/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
13091fn dq_summary(offsets: &[i32]) -> String {
13092 let n = offsets.len().max(1);
13093 let (lo, hi) = offsets
13094 .iter()
13095 .fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
13096 let nz = offsets.iter().filter(|&&o| o != 0).count();
13097 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
13098 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
13099 let mut levels: Vec<i32> = offsets.to_vec();
13100 levels.sort_unstable();
13101 levels.dedup();
13102 format!(
13103 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
13104 offsets.len(),
13105 levels.len()
13106 )
13107}
13108
13109/// How many DISTINCT per-superblock quantizer levels the last inter frame's
13110/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
13111/// (class `gate-blind-to-feature`: every exactness assert below passes on a
13112/// grid that is one flat value, i.e. on no delta_q at all). Process-global
13113/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
13114/// keeps the LARGEST count seen since the last read.
13115static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
13116
13117/// [`DELTAQ_LEVELS`], reset to 0.
13118#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
13119pub(crate) fn take_deltaq_levels() -> usize {
13120 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
13121}
13122
13123/// This superblock's search state: the quantizer it is coded at, and the
13124/// lambda that quantizer implies. RD lambda goes as the square of the step,
13125/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
13126/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
13127/// before lane-deltaq).
13128fn sb_q_search<'m>(
13129 sb_q: &[u8],
13130 sb_cols: usize,
13131 base_q_idx: u8,
13132 (sb_r, sb_c): (usize, usize),
13133 base: Search<'m>,
13134) -> Search<'m> {
13135 let q = sb_q[sb_r * sb_cols + sb_c];
13136 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
13137 Search {
13138 base_q_idx: q,
13139 lambda: base.lambda * ratio * ratio,
13140 ..base
13141 }
13142}
13143
13144fn tpl_strength() -> f64 {
13145 std::env::var("EC_AV1_TPL")
13146 .ok()
13147 .and_then(|v| v.parse::<f64>().ok())
13148 .filter(|k| k.is_finite() && *k >= 0.0)
13149 .unwrap_or(TPL_STRENGTH)
13150}
13151
13152/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
13153/// the frame being coded. 1 turns the weighting off; 2 is the shipped
13154/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
13155/// [`tpl_propagating`], which is the map that can actually use them and is
13156/// the default since lane-av1tpl3, so the default window is 8. Swept by
13157/// `EC_AV1_TPL_D=<d>`.
13158///
13159/// The streaming facade holds `depth - 1` pictures back so it feeds
13160/// `encode_inter_frame` the same window `encode_sequence` does; both read
13161/// THIS function, so the two paths cannot disagree about the window.
13162pub(crate) const TPL_DEPTH: usize = 8;
13163
13164/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
13165/// 0.5 is libaom's own square-root compression of its dependence ratio.
13166const TPL_POWER: f64 = 0.5;
13167
13168/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
13169/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
13170///
13171/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
13172/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
13173/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
13174///
13175/// | k | D | p | film 1080p | film 2160p | screen |
13176/// |---|---|---|---|---|---|
13177/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
13178/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
13179/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
13180/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
13181/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
13182/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
13183/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
13184/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
13185/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
13186/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
13187/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
13188/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
13189///
13190/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
13191/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
13192/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
13193/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
13194/// 0.1..0.4 UP on film 2160p, so it shipped off.
13195///
13196/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
13197/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
13198/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
13199/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
13200/// wherever the window leans on a flat bar, which is exactly where coding is
13201/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
13202/// (libaom's own granularity) puts a busy cell's denominator next to the flat
13203/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
13204/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
13205/// the same native gate (baseline = the shipped one-frame map):
13206///
13207/// | arm | film 1080p | film 2160p | screen |
13208/// |---|---|---|---|
13209/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
13210/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
13211/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
13212/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
13213/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
13214/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
13215/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
13216/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
13217/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
13218/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
13219///
13220/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
13221/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
13222/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
13223/// floor is a real effect on the ratio and never a win once the aggregation
13224/// is in -- the aggregation is the same fix, done where libaom does it.
13225fn tpl_propagating() -> bool {
13226 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
13227}
13228
13229pub(crate) fn tpl_depth() -> usize {
13230 std::env::var("EC_AV1_TPL_D")
13231 .ok()
13232 .and_then(|v| v.parse::<usize>().ok())
13233 .filter(|d| *d >= 1)
13234 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
13235 .max(1)
13236}
13237
13238/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
13239/// process, so the gate can price it against the encode it rides on.
13240static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
13241
13242/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
13243/// the winning displacement and its SAD.
13244///
13245/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
13246/// the left/above winners, first-best tie-break. Built once on the frame's
13247/// own thread and read-only afterwards, so it cannot make a tile's bytes
13248/// depend on the thread count.
13249fn tpl_coarse_pass(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<((i32, i32), u32)> {
13250 let (cells_x, cells_y) = (width / 16, height / 16);
13251 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
13252 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
13253 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
13254 return u32::MAX;
13255 }
13256 let (sx, sy) = (sx as usize, sy as usize);
13257 let mut sum = 0u32;
13258 for r in 0..16 {
13259 let a = &next[(by + r) * width + bx..][..16];
13260 let b = &cur[(sy + r) * width + sx..][..16];
13261 sum += a
13262 .iter()
13263 .zip(b)
13264 .map(|(&p, &q)| u32::from(p.abs_diff(q)))
13265 .sum::<u32>();
13266 }
13267 sum
13268 };
13269 let mut out = Vec::with_capacity(cells_x * cells_y);
13270 let mut above = vec![(0i32, 0i32); cells_x];
13271 for cy in 0..cells_y {
13272 let mut left = (0i32, 0i32);
13273 for cx in 0..cells_x {
13274 let (bx, by) = (cx * 16, cy * 16);
13275 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
13276 for cand in [left, above[cx]] {
13277 if cand != (0, 0) {
13278 let s = sad(bx, by, cand);
13279 if s < best.0 {
13280 best = (s, cand);
13281 }
13282 }
13283 }
13284 for step in [8i32, 4, 2, 1] {
13285 let centre = best.1;
13286 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
13287 let mv = (centre.0 + dx, centre.1 + dy);
13288 if mv.0.abs() > 32 || mv.1.abs() > 32 {
13289 continue;
13290 }
13291 let s = sad(bx, by, mv);
13292 if s < best.0 {
13293 best = (s, mv);
13294 }
13295 }
13296 }
13297 left = best.1;
13298 above[cx] = best.1;
13299 out.push((best.1, best.0));
13300 }
13301 }
13302 out
13303}
13304
13305/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
13306/// transform: here, the mean absolute deviation of the cell from its own DC.
13307/// It is the denominator every propagated cost is read against, so only its
13308/// SHAPE across the frame matters, not its scale.
13309fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
13310 let (cells_x, cells_y) = (width / 16, height / 16);
13311 let mut out = Vec::with_capacity(cells_x * cells_y);
13312 for cy in 0..cells_y {
13313 for cx in 0..cells_x {
13314 let (bx, by) = (cx * 16, cy * 16);
13315 let mut sum = 0u32;
13316 for r in 0..16 {
13317 sum += frame[(by + r) * width + bx..][..16]
13318 .iter()
13319 .map(|&p| u32::from(p))
13320 .sum::<u32>();
13321 }
13322 let dc = ((sum + 128) / 256) as u8;
13323 let mut cost = 0u32;
13324 for r in 0..16 {
13325 cost += frame[(by + r) * width + bx..][..16]
13326 .iter()
13327 .map(|&p| u32::from(p.abs_diff(dc)))
13328 .sum::<u32>();
13329 }
13330 out.push(cost);
13331 }
13332 }
13333 out
13334}
13335
13336/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
13337/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
13338/// splats its own area, at its winning displacement, onto the (at most four)
13339/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
13340fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
13341 let start = std::time::Instant::now();
13342 let (cells_x, cells_y) = (width / 16, height / 16);
13343 let pass = tpl_coarse_pass(cur, next, width, height);
13344 let mut area = vec![0.0f64; cells_x * cells_y];
13345 for cy in 0..cells_y {
13346 for cx in 0..cells_x {
13347 let (mv, _) = pass[cy * cells_x + cx];
13348 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
13349 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
13350 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
13351 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
13352 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
13353 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
13354 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
13355 }
13356 }
13357 }
13358 }
13359 TPL_NANOS.fetch_add(
13360 start.elapsed().as_nanos() as u64,
13361 std::sync::atomic::Ordering::Relaxed,
13362 );
13363 area
13364}
13365
13366/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
13367/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
13368/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
13369/// Decreasing in referenced-ness (a block the next frame leans on is coded
13370/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
13371/// total lambda scale is only redistributed, never moved -- a global move is
13372/// the thing lane-av1lambda already measured inert.
13373fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
13374 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
13375 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
13376 let mut out = Vec::with_capacity(sb_cols * sb_rows);
13377 for sr in 0..sb_rows {
13378 for sc in 0..sb_cols {
13379 let mut sum = 0.0;
13380 for r in 0..4 {
13381 for c in 0..4 {
13382 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
13383 }
13384 }
13385 let w_rel = sum / 16.0 / mean;
13386 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
13387 }
13388 }
13389 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
13390 let mut hist = [0usize; 8];
13391 for w in map {
13392 hist[((w / mean * 2.0) as usize).min(7)] += 1;
13393 }
13394 let (lo, hi) = out
13395 .iter()
13396 .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
13397 eprintln!(
13398 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
13399 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
13400 map.len(),
13401 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
13402 );
13403 }
13404 out
13405}
13406
13407/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
13408/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
13409/// much of the WHOLE lookahead window leans on that cell.
13410///
13411/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
13412/// coarse pass gives a displacement and an inter cost; a cell's own
13413/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
13414/// cell well saves the frames that predict from it -- and it is splatted,
13415/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
13416/// displacement lands on. Walking `f` from the far end of the window back to
13417/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
13418/// area map could not do at all.
13419///
13420/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
13421/// factor over the frame is exactly 1: a cell the window leans on is coded
13422/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
13423/// scale only moves around, never up or down -- a global move is what
13424/// lane-av1lambda already measured inert.
13425/// Returns the per-cell lambda factors AND the per-cell dependence ratio
13426/// `mc_dep / intra` they were derived from -- the second half is what
13427/// [`deltaq_libaom`] needs, since the factor alone has been through a
13428/// mean normalisation the raw ratio cannot be recovered across.
13429fn tpl_lambda_factors(
13430 frames: &[&[u8]],
13431 width: usize,
13432 height: usize,
13433 k: f64,
13434) -> (Vec<f64>, Vec<f64>) {
13435 let start = std::time::Instant::now();
13436 let (cells_x, cells_y) = (width / 16, height / 16);
13437 let cells = cells_x * cells_y;
13438 let levels = frames.len();
13439 let intra: Vec<Vec<u32>> = frames
13440 .iter()
13441 .map(|f| tpl_intra_costs(f, width, height))
13442 .collect();
13443 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
13444 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
13445 .collect();
13446 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
13447 for f in (1..levels).rev() {
13448 for cy in 0..cells_y {
13449 for cx in 0..cells_x {
13450 let ci = cy * cells_x + cx;
13451 let (mv, inter) = passes[f - 1][ci];
13452 let saved = f64::from(intra[f][ci].saturating_sub(inter));
13453 let propagate = saved + mc_dep[f][ci];
13454 if propagate <= 0.0 {
13455 continue;
13456 }
13457 // The 16x16 window of the PREVIOUS frame this cell predicted
13458 // from, spread over the cells it overlaps.
13459 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
13460 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
13461 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
13462 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
13463 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
13464 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
13465 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
13466 }
13467 }
13468 }
13469 }
13470 }
13471 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
13472 // tail (a nearly flat cell the window leans on has a tiny denominator),
13473 // and at p = 1 that tail slams into the clamp. libaom reads its own
13474 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
13475 // sweeps the exponent, 1 being the raw ratio.
13476 let power = std::env::var("EC_AV1_TPL_P")
13477 .ok()
13478 .and_then(|v| v.parse::<f64>().ok())
13479 .filter(|p| p.is_finite() && *p > 0.0)
13480 .unwrap_or(TPL_POWER);
13481 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
13482 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
13483 // `0` to take either back out); `FLOOR` defaults to off.
13484 //
13485 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
13486 // frame's own mean intra cost. A cell of flat content has a near-zero
13487 // MAD, so its ratio explodes exactly where coding is cheap.
13488 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
13489 // and mc_dep are summed over the 64x64 superblock first -- libaom's
13490 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
13491 // per-16x16 numbers), which is also what makes the ratio survive one
13492 // flat cell next to a busy one.
13493 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
13494 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
13495 // harder than the `p` exponent alone can.
13496 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
13497 .ok()
13498 .and_then(|v| v.parse::<f64>().ok())
13499 .filter(|f| f.is_finite() && *f >= 0.0)
13500 .unwrap_or(0.0);
13501 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
13502 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
13503 let intra_mean = intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
13504 let floor = floor_frac * intra_mean;
13505 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
13506 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
13507 // every cell under it. The edge groups are partial and summed as they are.
13508 let ratio: Vec<f64> = if sb_agg {
13509 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
13510 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
13511 for cy in 0..cells_y {
13512 for cx in 0..cells_x {
13513 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
13514 e.0 += mc_dep[0][cy * cells_x + cx];
13515 e.1 += denom(cy * cells_x + cx);
13516 }
13517 }
13518 (0..cells)
13519 .map(|c| {
13520 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
13521 dep / den.max(1.0)
13522 })
13523 .collect()
13524 } else {
13525 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
13526 };
13527 let mut out: Vec<f64> = ratio
13528 .iter()
13529 .map(|&r| {
13530 let r = if log_beta { (1.0 + r).log2() } else { r };
13531 (1.0 + k * r).powf(-power)
13532 })
13533 .collect();
13534 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
13535 for f in &mut out {
13536 *f = (*f / mean).clamp(0.25, 4.0);
13537 }
13538 TPL_NANOS.fetch_add(
13539 start.elapsed().as_nanos() as u64,
13540 std::sync::atomic::Ordering::Relaxed,
13541 );
13542 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
13543 let mut hist = [0usize; 8];
13544 for &f in &out {
13545 hist[((f * 4.0) as usize).min(7)] += 1;
13546 }
13547 let (lo, hi) = out
13548 .iter()
13549 .fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
13550 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
13551 eprintln!(
13552 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
13553 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
13554 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
13555 );
13556 }
13557 (out, ratio)
13558}
13559
13560/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
13561/// references name, which slot it refreshes, whether it is shown when it is
13562/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
13563/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
13564/// 0/2 alternation, every frame shown, every reference in the past).
13565///
13566/// The sign bias is carried rather than derived here because only the caller
13567/// knows what order hint each slot holds; it is armed onto the tile writer
13568/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
13569/// the writer scans the same stacks the decoder will.
13570#[derive(Debug, Clone, Copy)]
13571pub(crate) struct PyramidFrame {
13572 /// The slot `LAST_FRAME` (and every reference this encoder does not name
13573 /// apart) reads.
13574 pub last_slot: u8,
13575 /// The single slot `refresh_frame_flags` sets.
13576 pub self_slot: u8,
13577 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
13578 /// pyramid, which is what makes `sign_bias`'s last entry true.
13579 pub altref_slot: u8,
13580 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
13581 /// picture (the leaf chain alternates its refresh between two slots, so
13582 /// the frame before `LAST` is still intact). `None` leaves
13583 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
13584 /// wrote before, and the caller then passes no `last2` picture either.
13585 pub last2_slot: Option<u8>,
13586 /// `show_frame`: false for a hidden frame, output later by a
13587 /// `show_existing_frame` header.
13588 pub show_frame: bool,
13589 /// lane-arfq: which level's `delta_q` strength this frame reads
13590 /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid
13591 /// one share `Level::Arf` and differ only by their q offset.
13592 pub dq_level: DqLevel,
13593 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
13594 pub sign_bias: crate::mvstack::SignBiasTable,
13595}
13596
13597/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
13598/// `temporal_filter` in the small: every 16x16 luma block of `src` is
13599/// motion-compensated from each picture of `window` (the group's own display
13600/// neighbours, nearest first) and averaged in with weight
13601/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
13602/// nothing and one that matches well cancels the grain the block's residual
13603/// would otherwise have to code.
13604///
13605/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
13606/// rides the luma block's own vector (halved), which is what libaom does at
13607/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
13608/// grid tiles it exactly.
13609///
13610/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
13611/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
13612/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
13613/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
13614/// quality the ARF is coded at, so the substitution itself costs little.
13615// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and
13616// `ARF_TF_WIN_FUT` future ones); this takes every picture in it.
13617pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
13618 const SIDE: usize = 16;
13619 let neighbours: Vec<&Picture> = window
13620 .iter()
13621 .filter(|p| p.width == src.width && p.height == src.height)
13622 .collect();
13623 if neighbours.is_empty() || strength <= 0.0 {
13624 return src.clone();
13625 }
13626 let mut out = src.clone();
13627 // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
13628 // `None` when the displaced block leaves the picture.
13629 let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
13630 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
13631 if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
13632 return None;
13633 }
13634 let (sy, sx) = (sy as usize, sx as usize);
13635 let mut acc = 0u64;
13636 for row in 0..SIDE {
13637 let c = &src.y[(by + row) * src.width + bx..][..SIDE];
13638 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
13639 acc += c
13640 .iter()
13641 .zip(p)
13642 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
13643 .sum::<u64>();
13644 }
13645 Some((acc, (sy, sx)))
13646 };
13647 // The log-step diamond `arf_pred_census` priced this with.
13648 let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
13649 let mut best = sad(r, bx, by, (0, 0))?;
13650 let mut centre = (0isize, 0isize);
13651 let mut step = 16isize;
13652 while step >= 1 {
13653 let from = centre;
13654 for (dy, dx) in [
13655 (-1, -1),
13656 (-1, 0),
13657 (-1, 1),
13658 (0, -1),
13659 (0, 1),
13660 (1, -1),
13661 (1, 0),
13662 (1, 1),
13663 ] {
13664 let mv = (from.0 + dy * step, from.1 + dx * step);
13665 if let Some(s) = sad(r, bx, by, mv) {
13666 if s.0 < best.0 {
13667 best = s;
13668 centre = mv;
13669 }
13670 }
13671 }
13672 step /= 2;
13673 }
13674 Some(best.1)
13675 };
13676 let (cw, ch) = (src.width / 2, src.height / 2);
13677 for by in (0..src.height).step_by(SIDE) {
13678 for bx in (0..src.width).step_by(SIDE) {
13679 if by + SIDE > src.height || bx + SIDE > src.width {
13680 continue;
13681 }
13682 let mut y_acc = vec![0f64; SIDE * SIDE];
13683 let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
13684 let mut wsum = 1.0f64;
13685 // Chroma keeps its OWN weight sum: an edge block whose halved
13686 // vector leaves the chroma plane contributes to luma only, and
13687 // dividing chroma by the luma sum would darken it (class
13688 // `metric blind to a plane`, on the encoder side).
13689 let mut cwsum = 1.0f64;
13690 for row in 0..SIDE {
13691 for col in 0..SIDE {
13692 y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
13693 }
13694 }
13695 for row in 0..SIDE / 2 {
13696 for col in 0..SIDE / 2 {
13697 let i = (by / 2 + row) * cw + bx / 2 + col;
13698 c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
13699 c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
13700 }
13701 }
13702 for r in &neighbours {
13703 let Some((sy, sx)) = search(r, bx, by) else {
13704 continue;
13705 };
13706 let mut sse = 0f64;
13707 for row in 0..SIDE {
13708 for col in 0..SIDE {
13709 let d = f64::from(src.y[(by + row) * src.width + bx + col])
13710 - f64::from(r.y[(sy + row) * r.width + sx + col]);
13711 sse += d * d;
13712 }
13713 }
13714 let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
13715 for row in 0..SIDE {
13716 for col in 0..SIDE {
13717 y_acc[row * SIDE + col] +=
13718 w * f64::from(r.y[(sy + row) * r.width + sx + col]);
13719 }
13720 }
13721 // Chroma reads the luma vector halved; a block on the picture
13722 // edge whose halved vector would leave the chroma plane is
13723 // left to luma alone rather than clamped to a different
13724 // displacement than the luma it must stay registered with.
13725 let (cy, cx) = (sy / 2, sx / 2);
13726 if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
13727 for row in 0..SIDE / 2 {
13728 for col in 0..SIDE / 2 {
13729 let i = (cy + row) * cw + cx + col;
13730 c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
13731 c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
13732 }
13733 }
13734 cwsum += w;
13735 }
13736 wsum += w;
13737 }
13738 for row in 0..SIDE {
13739 for col in 0..SIDE {
13740 out.y[(by + row) * src.width + bx + col] =
13741 (y_acc[row * SIDE + col] / wsum).round() as u16;
13742 }
13743 }
13744 for row in 0..SIDE / 2 {
13745 for col in 0..SIDE / 2 {
13746 let i = (by / 2 + row) * cw + bx / 2 + col;
13747 out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
13748 out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
13749 }
13750 }
13751 }
13752 }
13753 out
13754}
13755
13756/// Encodes one picture as an inter frame predicting from `reference`'s
13757/// reconstruction, which the caller decoded (or, for the frame right after
13758/// the key frame, is the key frame's own reconstruction).
13759pub(crate) fn encode_inter_frame(
13760 picture: &Picture,
13761 reference: &Picture,
13762 base_q_idx: u8,
13763 deadzone: f64,
13764 order_hint: u32,
13765 // The order hint each of the seven `ref_frame_idx` entries names, which a
13766 // decoder reads out of its own reference state -- only spec 5.9.22's
13767 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
13768 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
13769 // callers that follow this crate's own flat slot plan.
13770 order_hints: [u32; 7],
13771 render: (usize, usize),
13772 // The tables this frame's writer starts from: what the previous frame
13773 // stored into the slot this one's `primary_ref_frame` names. `None`
13774 // starts from the defaults, which is right only for the frame straight
13775 // after a key frame.
13776 start_cdfs: Option<&crate::cdf_state::Cdfs>,
13777 // The key frame's own (padded) reconstruction, which every frame of the
13778 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
13779 // with `LAST_FRAME` alone, exactly as before.
13780 golden: Option<&Picture>,
13781 // The frame two back, held in the slot this frame is about to refresh
13782 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
13783 // inter frames of a GOP, where the frame two back IS the key frame.
13784 altref: Option<&Picture>,
13785 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
13786 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
13787 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
13788 // take. `None` (every caller but the pyramid leaves) codes the frame
13789 // with the reference set unchanged.
13790 last2: Option<&Picture>,
13791 fctx: &crate::decode::FrameCtx,
13792 // Where this frame sits in the coding-order pyramid; `None` is the flat
13793 // one-shown-frame-per-picture stream this encoder wrote before.
13794 pyramid: Option<PyramidFrame>,
13795 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
13796 // them), padded like this one -- the lookahead window the per-block
13797 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
13798 // EMPTY slice codes the frame at one lambda, as before.
13799 lookahead: &[Picture],
13800) -> Result<Encoded> {
13801 picture.check()?;
13802 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
13803 return Err(Error::unsupported(
13804 "AV1 encode",
13805 "an inter frame is coded only for a picture that is a whole number \
13806 of 64x64 superblocks -- the inter tile writer never splits a \
13807 superblock's partition below that",
13808 ));
13809 }
13810 if reference.width != picture.width || reference.height != picture.height {
13811 return Err(Error::unsupported(
13812 "AV1 encode",
13813 "the reference picture must be the same size as the one being coded",
13814 ));
13815 }
13816
13817 // The single slot this crate's inter frames ever predict from or
13818 // refresh (`inter_frame_headers`'s contract): every frame both reads and
13819 // overwrites slot 0, so the frame just coded is always what the next one
13820 // predicts against.
13821 const LAST_SLOT: u8 = 0;
13822 // Slot 0 and slot 2 alternate so the frame two back survives one more
13823 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
13824 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
13825 // in the very slot it will overwrite.
13826 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
13827 let last_slot = pyramid.map_or(
13828 if order_hint <= 1 {
13829 LAST_SLOT
13830 } else if (order_hint - 1) % 2 == 1 {
13831 0
13832 } else {
13833 2
13834 },
13835 |p| p.last_slot,
13836 );
13837 // `render`, not `picture.width`/`picture.height`: `picture` here is
13838 // already padded to a whole number of superblocks (`encode_sequence`'s
13839 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
13840 // every true-edge clamp downstream) must come from the frame's real,
13841 // unpadded size, same as `key_frame_headers_colour` takes `render` and
13842 // not the padded picture in `encode_key_frame_inner`.
13843 let (seq, mut header) = inter_frame_headers_slots(
13844 render.0,
13845 render.1,
13846 base_q_idx,
13847 order_hint,
13848 last_slot,
13849 self_slot,
13850 match pyramid {
13851 Some(p) => p.altref_slot,
13852 None if altref.is_some() => self_slot,
13853 None => GOLDEN_SLOT,
13854 },
13855 )?;
13856 header.render_width = render.0 as u32;
13857 header.render_height = render.1 as u32;
13858 // lane-refs: this frame's motion-compensation kernel, written into the
13859 // header AND armed on the context every prediction reads, in one place so
13860 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
13861 // tile decodes to different pixels than the encoder scored).
13862 header.interpolation_filter = frame_interp_filter();
13863 fctx.interp_filter.set(mc::InterpFilterKind::from_header(
13864 header.interpolation_filter,
13865 ));
13866 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
13867 // The order hint behind each `ref_frame_idx` entry. The flat path's own
13868 // slot plan (`inter_frame_headers_slots`) is: every reference but
13869 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
13870 // `ALTREF_FRAME`, which reads the frame two back when there is one;
13871 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
13872 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
13873 header.order_hints = order_hints;
13874 // lane-last2: `inter_frame_headers_slots` points every un-named
13875 // reference at `last_slot`; the pyramid's leaf chain retains a second,
13876 // older picture and names it here. The caller's `sign_bias` /
13877 // `order_hints` entry 1 is derived from this same slot, so the stack
13878 // scans and `skipModeAllowed` read what the decoder will.
13879 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
13880 header.ref_frame_idx[1] = slot;
13881 }
13882 header.reference_select = reference_select();
13883 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
13884 // per-reference order-hint distance is read by the block SEARCH, which
13885 // runs long before the writer arms these (the distance-scaled search step
13886 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
13887 // never reached the tool).
13888 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
13889 // lane-hpmv: armed here for the same reason the order hints are -- the
13890 // block SEARCH reads it (its eighth-pel stage) long before the writer.
13891 let hp_mv = header.allow_high_precision_mv;
13892 crate::tile::arm_high_precision_mv(hp_mv);
13893 if let Some(p) = pyramid {
13894 header.show_frame = p.show_frame;
13895 header.showable_frame = !p.show_frame;
13896 header.ref_frame_sign_bias = p.sign_bias;
13897 }
13898 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
13899 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
13900 // block inside this frame codes and searches its own `tx_depth`, the same
13901 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
13902 let tx_select = tx_select() && tx_select_inter();
13903 if tx_select {
13904 header.tx_mode = TxMode::Select;
13905 }
13906
13907 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
13908 // lane-palw: the encoder's own in-process reconstruct reads its palette
13909 // colour-index maps back through `decode::palette_onscreen`, which takes
13910 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
13911 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
13912 // them here so the reconstruct clamps a block cut by the frame edge
13913 // exactly as the writer now does.
13914 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
13915 fctx.seg_mi_dims.set(frame_mi_dims);
13916 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
13917 // here (see `encode_key_frame_inner`).
13918 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
13919 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
13920 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
13921 // This frame's own `allow_screen_content_tools`. It can only be set when
13922 // the SEQUENCE offers the bit at all, which is the key frame's decision
13923 // ([`SEQ_SCREEN`]): a frame header that contradicts
13924 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
13925 // encode.
13926 let screen =
13927 seq_screen() && screen_content(&picture_y8, picture.width, true_width, true_height);
13928 header.allow_screen_content_tools = screen;
13929 // lane-txi, as on the key frame: the header bit the writer's own
13930 // `Cdfs` then reads for every luma `tx_type` symbol.
13931 header.reduced_tx_set = !wide_tx_set(screen);
13932 // lane-intertx, desync (a): the frame context this value is read back
13933 // through ([`decode::reduce_inherited_chroma_tx_type`] inside
13934 // `recode_inter_chroma`, and every inter decode helper the search's own
13935 // trial decode shares) must carry THIS frame's bit, not whatever the
13936 // previous frame's trial decode last left in the shared cell -- a stale
13937 // `true` here narrows the chroma allowance the search reconstructs
13938 // against under the one the header's bit actually allows.
13939 fctx.reduced_tx_set_inter.set(header.reduced_tx_set);
13940 // The search prices coefficients against the tables this frame's writer
13941 // starts from, not against the defaults (lane-av1txbits) -- but only on a
13942 // frame the screen detector said no to (lane-av1price2): armed HERE, after
13943 // `screen` exists, and again on every search/tile worker below.
13944 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
13945 let mut luma = Plane {
13946 source: &picture_y8,
13947 reconstruction: vec![128; picture_y8.len()],
13948 width: picture.width,
13949 height: picture.height,
13950 true_width,
13951 true_height,
13952 tile_x0: 0,
13953 tile_y0: 0,
13954 tile_x1: picture.width,
13955 tile_y1: picture.height,
13956 ctx: CoefCtxMap::default(),
13957 };
13958 let mut chroma = [
13959 Plane {
13960 source: &picture_u8,
13961 reconstruction: vec![128; picture_u8.len()],
13962 width: picture.width / 2,
13963 height: picture.height / 2,
13964 true_width: true_width / 2,
13965 true_height: true_height / 2,
13966 tile_x0: 0,
13967 tile_y0: 0,
13968 tile_x1: picture.width / 2,
13969 tile_y1: picture.height / 2,
13970 ctx: CoefCtxMap::default(),
13971 },
13972 Plane {
13973 source: &picture_v8,
13974 reconstruction: vec![128; picture_v8.len()],
13975 width: picture.width / 2,
13976 height: picture.height / 2,
13977 true_width: true_width / 2,
13978 true_height: true_height / 2,
13979 tile_x0: 0,
13980 tile_y0: 0,
13981 tile_x1: picture.width / 2,
13982 tile_y1: picture.height / 2,
13983 ctx: CoefCtxMap::default(),
13984 },
13985 ];
13986
13987 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
13988 let top_arf = matches!(
13989 pyramid,
13990 Some(p) if p.dq_level == DqLevel::TopArf
13991 );
13992 let arfmode_v = arfmode();
13993 let search = Search {
13994 base_q_idx,
13995 deadzone,
13996 lambda: lambda_scale()
13997 * match pyramid {
13998 Some(p) if !p.show_frame => hidden_lambda_factor(),
13999 _ => 1.0,
14000 }
14001 * step
14002 * step,
14003 modes: &KEY_FRAME_MODES,
14004 top_k: prune_top_k_inter(),
14005 screen,
14006 // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose
14007 // offset is the pyramid's own `arf_q_offset`) reads its leaf offer
14008 // set from [`crate::speed::ARFMODE`]; every other frame -- the mid
14009 // and quarter hidden frames, the leaves, the flat path -- keeps the
14010 // full set.
14011 arf_leaf_intra: !top_arf || arfmode_v & 1 == 0,
14012 arf_leaf8: !top_arf || arfmode_v & 2 == 0,
14013 arf_leaf_compound: !top_arf || arfmode_v & 4 == 0,
14014 };
14015 let mode_bits_table = inter_mode_bits();
14016 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
14017 // this frame the NEXT one predicts from. Off (`None`) without a
14018 // lookahead picture or at strength 0.
14019 let tpl_k = tpl_strength();
14020 let window: Vec<&Picture> = lookahead
14021 .iter()
14022 .take_while(|n| n.width == picture.width && n.height == picture.height)
14023 .collect();
14024 let tpl_sources: Vec<Vec<u8>> = window
14025 .iter()
14026 .map(|n| n.y.iter().map(|&v| v as u8).collect())
14027 .collect();
14028 let tpl_cells_x = picture.width / 16;
14029 // `.1` is the propagating map's raw per-cell dependence ratio, which only
14030 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
14031 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> = (tpl_k > 0.0 && !tpl_sources.is_empty())
14032 .then(|| {
14033 if tpl_propagating() {
14034 let mut frames: Vec<&[u8]> = vec![&picture_y8];
14035 frames.extend(tpl_sources.iter().map(Vec::as_slice));
14036 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
14037 (f, Some(r))
14038 } else {
14039 // The shipped map is one factor per 64x64; it is spread over that
14040 // superblock's own 16 cells so the application site below (which
14041 // averages the four cells of a 32x32 block) reads exactly the
14042 // superblock factor, whichever map fed it.
14043 let map = tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
14044 let cells_y = picture.height / 16;
14045 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
14046 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
14047 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
14048 .collect();
14049 (f, None)
14050 }
14051 });
14052 let (tpl_factors, tpl_ratio) = match tpl_both {
14053 Some((f, r)) => (Some(f), r),
14054 None => (None, None),
14055 };
14056
14057 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
14058 // coding surface's: `blocks` carries one entry per 32x32 block the tile
14059 // writer will actually visit, same count it checks `blocks.len()`
14060 // against, which is fewer than the padded surface's own block count
14061 // whenever the true size is not a 64x64 multiple.
14062 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
14063 let (cols, rows) = (cols as usize, rows as usize);
14064 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
14065 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
14066 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
14067 // only when the map is, and `delta_q_res` follows straight into the frame
14068 // header (`write_delta_q_params`) and into the tile writer's own plan.
14069 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
14070 // measured the per-superblock quantizer as a win on both films and a
14071 // 0.5 loss vs libaom on the desktop capture, so a frame that set
14072 // `allow_screen_content_tools` codes no delta syntax at all and stays
14073 // byte-identical to the pre-lane encoder.
14074 // lane-arfq: the level whose `delta_q` strength this frame reads; the
14075 // flat path (no pyramid) is a leaf.
14076 let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level);
14077 let deltaq_res: Option<i32> = tpl_factors
14078 .as_ref()
14079 .filter(|_| !screen)
14080 .and(deltaq_res_log2().map(|r| 1i32 << r));
14081 // The same 16-cell mean the superblock's own lambda takes, clamped to the
14082 // map the frame actually has -- read over the factors or over the raw
14083 // dependence ratios, whichever mapping is asking.
14084 let sb_mean = |m: &[f64], sb: usize| {
14085 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
14086 (0..16)
14087 .map(|i| {
14088 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
14089 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
14090 })
14091 .sum::<f64>()
14092 / 16.0
14093 };
14094 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
14095 // raw dependence ratio; without it (and always without a ratio map, i.e.
14096 // on the one-frame area map) the shipped derivation stands.
14097 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
14098 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
14099 match (libaom, tpl_ratio.as_deref(), r_frame) {
14100 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
14101 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
14102 }
14103 };
14104 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
14105 (Some(f), Some(res)) => {
14106 let libaom = dq_tpl_strength(dq_level);
14107 let mut g: Vec<u8> = (0..sb_cols * _sb_rows)
14108 .map(|sb| sb_qindex(f, res, sb, libaom))
14109 .collect();
14110 // lane-b128m: under 128 superblocks the delta_q syntax is coded
14111 // ONCE per 128 root (the reader's own unit), so all four 64x64
14112 // cells of a root have to be searched -- and quantized -- at the
14113 // one qindex the root's top-left cell codes.
14114 if sb128_on() {
14115 for sb_r in 0.._sb_rows {
14116 for sb_c in 0..sb_cols {
14117 let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
14118 g[sb_r * sb_cols + sb_c] = q;
14119 }
14120 }
14121 }
14122 Some(g)
14123 }
14124 _ => None,
14125 };
14126 // lane-dq census: both mappings on the SAME superblocks, whether or not
14127 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
14128 // off, and the census then prices the default `res = 4` grid).
14129 if dq_census() {
14130 if let Some(f) = &tpl_factors {
14131 let res = deltaq_res.unwrap_or(4);
14132 let off = |libaom: Option<f64>| -> Vec<i32> {
14133 (0..sb_cols * _sb_rows)
14134 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
14135 .collect()
14136 };
14137 let strength = dq_tpl_strength(dq_level);
14138 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
14139 let coded = match (deltaq_res.is_some(), strength) {
14140 (false, _) => "none".to_string(),
14141 (true, None) => "ours".to_string(),
14142 (true, Some(k)) => format!("libaom k={k}"),
14143 };
14144 eprintln!(
14145 "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
14146 sb_cols * _sb_rows,
14147 r_frame.unwrap_or(f64::NAN),
14148 dq_summary(&ours),
14149 dq_summary(&aom),
14150 );
14151 }
14152 }
14153 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
14154 header.delta.q_present = true;
14155 header.delta.q_res = res.trailing_zeros() as u8;
14156 }
14157 // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
14158 // below, so the root search prices the group the writer really codes.
14159 let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
14160 if let Some(g) = &sb_q {
14161 let mut levels: Vec<u8> = g.clone();
14162 levels.sort_unstable();
14163 levels.dedup();
14164 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
14165 }
14166 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
14167 // This frame's tile grid, as in `encode_key_frame_inner`.
14168 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
14169 let layout = crate::tile::TileLayout::new(
14170 header.mi_cols,
14171 header.mi_rows,
14172 tile_cols_log2,
14173 tile_rows_log2,
14174 );
14175 header.tile_info = tile_info_of(&layout, 1);
14176 let header_tile_info = header.tile_info.clone();
14177 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
14178 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
14179 // once per frame (lane-av1rd2), not once per block, which is a whole
14180 // plane's map per 32x32 block and now per leaf too.
14181 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
14182 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
14183 // availability -- intra edges and the MV stack's scans alike -- already
14184 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
14185 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
14186 // giving each job its own planes and its own `MiGrid` therefore leaves
14187 // every decision, and so every coded bit, exactly where the whole-frame
14188 // loop left it, at any tile count and any thread count.
14189 let (frame_width, frame_height) = (picture.width, picture.height);
14190 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
14191 let [cb, cr] = &mut chroma;
14192 let chroma_out = [
14193 crate::par::Shared::new(&mut cb.reconstruction),
14194 crate::par::Shared::new(&mut cr.reconstruction),
14195 ];
14196 let search_tile = |index: usize,
14197 fctx: &crate::decode::FrameCtx|
14198 -> Result<Vec<(usize, Quadrant)>> {
14199 // Thread-local, and this job may be running on a `search_tiles`
14200 // worker: `ref_distance`'s order-hint distance (the scaled motion
14201 // search step) is read by the SEARCH, so every worker arms it or the
14202 // tile's bits depend on the thread count.
14203 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
14204 crate::tile::arm_high_precision_mv(hp_mv);
14205 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
14206 let rect = layout.rect(index);
14207 let mut luma = fresh_plane(
14208 &picture_y8,
14209 frame_width,
14210 frame_height,
14211 true_width,
14212 true_height,
14213 );
14214 let mut chroma = [
14215 fresh_plane(
14216 &picture_u8,
14217 frame_width / 2,
14218 frame_height / 2,
14219 true_width / 2,
14220 true_height / 2,
14221 ),
14222 fresh_plane(
14223 &picture_v8,
14224 frame_width / 2,
14225 frame_height / 2,
14226 true_width / 2,
14227 true_height / 2,
14228 ),
14229 ];
14230 clip_planes_to_tile(&mut luma, &mut chroma, rect);
14231 let mut grid = MiGrid::new(mi_cols, mi_rows);
14232 grid.set_sign_bias(sign_bias);
14233 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
14234 // built once per tile job (`obmc_prediction`).
14235 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
14236 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
14237 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
14238 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
14239 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
14240 grid.set_tile_bounds(
14241 rect.mi_row0 as usize,
14242 rect.mi_col0 as usize,
14243 rect.mi_row1 as usize,
14244 rect.mi_col1 as usize,
14245 );
14246 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
14247 // lane-b128: under a 128x128 superblock the search walks the roots the
14248 // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
14249 // not plain raster -- a search that visits BL before TR builds every mv
14250 // stack and neighbour context off blocks the writer has not coded yet,
14251 // which is what made the write-time drl clamp fire at all (lane-sb128b).
14252 // At a 64 superblock the two orders are identical and this is the same
14253 // raster loop as before.
14254 let sb128_search = sb128_on();
14255 let root_step = if sb128_search { 2 } else { 1 };
14256 let mut roots: Vec<(usize, usize)> = Vec::new();
14257 {
14258 let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
14259 let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
14260 let mut r = r0;
14261 while r < r1 {
14262 let mut c = c0;
14263 while c < c1 {
14264 roots.push((r, c));
14265 c += root_step;
14266 }
14267 r += root_step;
14268 }
14269 }
14270 for (root_r, root_c) in roots {
14271 // The 64x64 cells of this root, in the writer's own order.
14272 let cells: Vec<(usize, usize)> = if sb128_search {
14273 [(0, 0), (0, 1), (1, 0), (1, 1)]
14274 .into_iter()
14275 .map(|(dr, dc)| (root_r + dr, root_c + dc))
14276 .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
14277 .collect()
14278 } else {
14279 vec![(root_r, root_c)]
14280 };
14281 // What the four cells below really cost, against which the whole
14282 // 128x128 candidate is weighed.
14283 let mark128 = blocks.len();
14284 let mut root_cost = 0.0f64;
14285 // The 128 root's own compound pairs, at its 32x32-mi window (the 64
14286 // root builds the same list one size down, per superblock).
14287 let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14288 if header.reference_select && b128_compound() && !screen && sb128_search {
14289 [
14290 (crate::mvstack::GOLDEN_FRAME, golden),
14291 (crate::mvstack::ALTREF_FRAME, altref),
14292 ]
14293 .into_iter()
14294 .filter_map(|(r, pic)| {
14295 pic.map(|p| {
14296 (
14297 r,
14298 p,
14299 crate::mvstack::find_mv_stack_compound(
14300 &grid,
14301 root_r * 16,
14302 root_c * 16,
14303 32,
14304 32,
14305 (crate::mvstack::LAST_FRAME, r),
14306 mi_cols,
14307 mi_rows,
14308 grid.sign_bias_table(),
14309 &[(0, 0); 7],
14310 None,
14311 ),
14312 )
14313 })
14314 })
14315 .collect()
14316 } else {
14317 Vec::new()
14318 };
14319 let root128 = (sb128_search && b128_root() && cells.len() == 4)
14320 .then(|| {
14321 search_root_128(
14322 &mut luma,
14323 &mut chroma,
14324 &grid,
14325 (root_r, root_c),
14326 (rows, cols),
14327 (header.mi_cols, header.mi_rows),
14328 search,
14329 &tpl_factors,
14330 sb_q.as_ref(),
14331 sb_cols,
14332 tpl_cells_x,
14333 base_q_idx,
14334 dq_res,
14335 reference,
14336 &root_compound,
14337 fctx,
14338 )
14339 })
14340 .flatten();
14341 // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
14342 // are priced; the cheaper one competes with the NONE block and with
14343 // the four superblocks below.
14344 let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
14345 let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
14346 .then(|| {
14347 let mut best: Option<(bool, _)> = None;
14348 for horz in [true, false] {
14349 if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
14350 continue;
14351 }
14352 let Some(found) = search_root_128_rect(
14353 &mut luma,
14354 &mut chroma,
14355 &mut grid,
14356 (root_r, root_c),
14357 (rows, cols),
14358 (header.mi_cols, header.mi_rows),
14359 search,
14360 &tpl_factors,
14361 sb_q.as_ref(),
14362 sb_cols,
14363 tpl_cells_x,
14364 base_q_idx,
14365 dq_res,
14366 reference,
14367 &root_compound,
14368 horz,
14369 fctx,
14370 ) else {
14371 continue;
14372 };
14373 if best
14374 .as_ref()
14375 .is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0)
14376 {
14377 best = Some((horz, found));
14378 }
14379 }
14380 best
14381 })
14382 .flatten();
14383 // lane-ab128: and the same root as one of the four AB shapes -- two
14384 // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
14385 // the cheapest joins the candidate list below.
14386 let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
14387 let root_ab = (sb128_search
14388 && (b128_ab() || forced_ab != 0)
14389 && cells.len() == 4
14390 && forced_rect == 0)
14391 .then(|| {
14392 let mut best: Option<(usize, _)> = None;
14393 for symbol in 4..=7usize {
14394 if forced_ab != 0 && usize::from(forced_ab) != symbol {
14395 continue;
14396 }
14397 let Some(found) = search_root_128_ab(
14398 &mut luma,
14399 &mut chroma,
14400 &mut grid,
14401 (root_r, root_c),
14402 (rows, cols),
14403 (header.mi_cols, header.mi_rows),
14404 search,
14405 &tpl_factors,
14406 sb_q.as_ref(),
14407 sb_cols,
14408 tpl_cells_x,
14409 base_q_idx,
14410 reference,
14411 &root_compound,
14412 symbol,
14413 fctx,
14414 ) else {
14415 continue;
14416 };
14417 if best
14418 .as_ref()
14419 .is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0)
14420 {
14421 best = Some((symbol, found));
14422 }
14423 }
14424 best
14425 })
14426 .flatten();
14427 for (sb_r, sb_c) in cells {
14428 // lane-b64: the whole superblock as ONE 64x64 block, tried before
14429 // its quadrants are (`search_skip_64`) and compared against the
14430 // four of them below. Only a superblock wholly inside the true
14431 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
14432 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
14433 // only that the block's half is inside, and the trial is ranked
14434 // over the inside part alone ([`Plane::block_sse`]).
14435 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
14436 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
14437 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
14438 && x64 + SUPERBLOCK <= luma.true_width
14439 && y64 + SUPERBLOCK <= luma.true_height;
14440 let edge_inside = b64_edge()
14441 && crate::tile::has_half(
14442 sb_c as u32 * crate::tile::SB_MI,
14443 crate::tile::SB_MI,
14444 header.mi_cols,
14445 )
14446 && crate::tile::has_half(
14447 sb_r as u32 * crate::tile::SB_MI,
14448 crate::tile::SB_MI,
14449 header.mi_rows,
14450 );
14451 let sb64_legal = b64_root()
14452 && sb_r * 2 + 1 < rows
14453 && sb_c * 2 + 1 < cols
14454 && (whole_inside || edge_inside);
14455 // One lambda for the whole superblock, the same mean the 32x32
14456 // level takes over its own four tpl cells: the 64-vs-four-32
14457 // comparison below weighs one cost against four, so both sides
14458 // have to be priced at the same lambda.
14459 let sb_search = match &tpl_factors {
14460 // lane-deltaq: with a per-superblock quantizer the lambda
14461 // comes from that quantizer, not from the raw map factor --
14462 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
14463 Some(_) if sb_q.is_some() => sb_q_search(
14464 sb_q.as_ref().expect("armed"),
14465 sb_cols,
14466 base_q_idx,
14467 (sb_r, sb_c),
14468 search,
14469 ),
14470 Some(f) if sb64_legal => {
14471 let mean = (0..16)
14472 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
14473 .sum::<f64>()
14474 / 16.0;
14475 Search {
14476 lambda: search.lambda * mean,
14477 ..search
14478 }
14479 }
14480 _ => search,
14481 };
14482 let mark = blocks.len();
14483 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
14484 let mut sb_cost = 0.0f64;
14485 if sb64_legal {
14486 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
14487 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
14488 let stack =
14489 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
14490 // lane-b64b: the `LAST` + extra-reference pairs at this
14491 // superblock's own 16x16-mi window, the same stacks the tile
14492 // writer's `Whole64` arm rebuilds. Empty unless the frame
14493 // codes `reference_select`, which is what gates the syntax.
14494 // `!screen` for the same reason the residual arm is gated
14495 // there ([`b64_residual`]): a desktop capture's superblocks
14496 // are flat runs the skip arm already codes for nothing, and
14497 // MEASURED, compound at the root cost it +33.4/-23.8 ->
14498 // +33.7/-23.6 while both film rows gained (step 1's table).
14499 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14500 if header.reference_select && b64_compound() && !screen {
14501 [
14502 (crate::mvstack::GOLDEN_FRAME, golden),
14503 (crate::mvstack::ALTREF_FRAME, altref),
14504 ]
14505 .into_iter()
14506 .filter_map(|(r, pic)| {
14507 pic.map(|p| {
14508 (
14509 r,
14510 p,
14511 crate::mvstack::find_mv_stack_compound(
14512 &grid,
14513 mi_row,
14514 mi_col,
14515 16,
14516 16,
14517 (crate::mvstack::LAST_FRAME, r),
14518 mi_cols,
14519 mi_rows,
14520 grid.sign_bias_table(),
14521 &[(0, 0); 7],
14522 None,
14523 ),
14524 )
14525 })
14526 })
14527 .collect()
14528 } else {
14529 Vec::new()
14530 };
14531 if let Some((cost, block)) = search_skip_64(
14532 &mut luma,
14533 &mut chroma,
14534 (x64, y64),
14535 (SUPERBLOCK, SUPERBLOCK),
14536 &sb_search,
14537 b64_residual() && !screen,
14538 reference,
14539 &stack,
14540 &sb_compound,
14541 fctx,
14542 ) {
14543 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
14544 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
14545 let cost = cost
14546 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
14547 sb64 = Some((cost, block, after));
14548 }
14549 }
14550 // A superblock whose 64x64 trial already codes almost nothing per
14551 // pixel is taken outright and its quadrants are never searched --
14552 // the same `split_rd_breakout` shape the 32x32 level uses one
14553 // size up, and where this lever BUYS wall instead of spending it.
14554 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
14555 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, sb_search.lambda)
14556 });
14557 for quadrant in 0..if early64 { 0 } else { 4 } {
14558 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
14559 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
14560 // decision under it (partition, mode, tx, motion) reads
14561 // `search.lambda`, so scaling the one field here scales all
14562 // of them. 32x32 and not the 16x16 the map is built at
14563 // because the whole-vs-split comparison right below weighs
14564 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
14565 // would make those two numbers incomparable.
14566 let search = match &tpl_factors {
14567 // lane-deltaq: the quantizer is a SUPERBLOCK-level
14568 // symbol, so all four quadrants take their superblock's
14569 // own qindex and the lambda it implies. No granularity is
14570 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
14571 // factor per superblock, shared by its sixteen cells.
14572 Some(_) if sb_q.is_some() => sb_q_search(
14573 sb_q.as_ref().expect("armed"),
14574 sb_cols,
14575 base_q_idx,
14576 (sb_r, sb_c),
14577 search,
14578 ),
14579 Some(f) => {
14580 let mean = (0..4)
14581 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
14582 .sum::<f64>()
14583 / 4.0;
14584 Search {
14585 lambda: search.lambda * mean,
14586 ..search
14587 }
14588 }
14589 None => search,
14590 };
14591 // Same filter as the tile writer's: a quadrant whose own mi
14592 // origin is not inside the true frame is never coded.
14593 if r32 >= rows || c32 >= cols {
14594 continue;
14595 }
14596 // spec `decode_partition`'s hasRows/hasCols recomputed at this
14597 // 32x32 block's own half (`crate::tile::has_half`), same as
14598 // the key frame search: the true frame edge can fall inside a
14599 // quadrant a superblock-level check already let through, and
14600 // such a quadrant cannot be left whole -- it must split into
14601 // the 16x16 leaves that are actually inside the true frame
14602 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
14603 // arm).
14604 let (has_cols32, has_rows32) = (
14605 crate::tile::has_half(
14606 c32 as u32 * crate::tile::BLOCK_MI,
14607 crate::tile::BLOCK_MI,
14608 header.mi_cols,
14609 ),
14610 crate::tile::has_half(
14611 r32 as u32 * crate::tile::BLOCK_MI,
14612 crate::tile::BLOCK_MI,
14613 header.mi_rows,
14614 ),
14615 );
14616 if has_cols32 && has_rows32 {
14617 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
14618 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
14619 let stack = find_mv_stack(
14620 &grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows,
14621 );
14622 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
14623 (crate::mvstack::LAST2_FRAME, last2),
14624 (crate::mvstack::GOLDEN_FRAME, golden),
14625 (crate::mvstack::ALTREF_FRAME, altref),
14626 ]
14627 .into_iter()
14628 .filter_map(|(r, pic)| {
14629 pic.map(|p| {
14630 (
14631 r,
14632 p,
14633 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
14634 )
14635 })
14636 })
14637 .collect();
14638 let extra: Vec<(i8, &Picture, &MvStack)> =
14639 extra_stacks.iter().map(|(r, p, st)| (*r, *p, st)).collect();
14640 // The COMPOUND stack of each `LAST` + extra pair, off the
14641 // same grid (and the same armed sign bias) the tile writer
14642 // rebuilds it from. Empty unless this frame codes
14643 // `reference_select`, which is what gates the syntax.
14644 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
14645 if header.reference_select {
14646 extra_stacks
14647 .iter()
14648 .map(|&(r, p, _)| {
14649 (
14650 r,
14651 p,
14652 crate::mvstack::find_mv_stack_compound(
14653 &grid,
14654 mi_row,
14655 mi_col,
14656 8,
14657 8,
14658 (crate::mvstack::LAST_FRAME, r),
14659 mi_cols,
14660 mi_rows,
14661 grid.sign_bias_table(),
14662 &[(0, 0); 7],
14663 None,
14664 ),
14665 )
14666 })
14667 .collect()
14668 } else {
14669 Vec::new()
14670 };
14671
14672 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
14673 let (block, mut cost_whole) = search_inter_block(
14674 &mut luma,
14675 &mut chroma,
14676 (x, y),
14677 &search,
14678 &mode_bits_table,
14679 reference,
14680 &stack,
14681 &extra,
14682 &compound,
14683 &grid,
14684 (mi_row, mi_col),
14685 (mi_rows, mi_cols),
14686 fctx,
14687 );
14688 cost_whole += search.lambda * partition_bits(BLOCK, false);
14689 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
14690
14691 // What four 16x16 leaves cost instead (spec
14692 // PARTITION_SPLIT at BLOCK_32X32, which
14693 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
14694 // already writes for a straddling quadrant). Each leaf is
14695 // searched against the reconstruction -- and the `mi`
14696 // grid -- the ones before it left, exactly as the writer
14697 // and the decoder will read them.
14698 //
14699 // A block the whole-32 search left skipped (no residual
14700 // at all) is not offered the split: libaom prunes the
14701 // same way at cpu-used 6, and it is where the wall would
14702 // otherwise go on static content.
14703 let leaf_positions: Vec<(usize, usize)> =
14704 (0..4).map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)).collect();
14705 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
14706 crate::tile::has_half(
14707 sc as u32 * crate::tile::SUB_MI,
14708 crate::tile::SUB_MI,
14709 header.mi_cols,
14710 ) && crate::tile::has_half(
14711 sr as u32 * crate::tile::SUB_MI,
14712 crate::tile::SUB_MI,
14713 header.mi_rows,
14714 )
14715 });
14716 // The breakout above: a 32x32 block that codes almost
14717 // nothing is not offered the split at all.
14718 let breakout = split_breakout_coeffs();
14719 let split = (!block.skip
14720 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
14721 && (breakout == 0 || block.luma.len() > 4 * breakout)
14722 && leaves_legal
14723 && split_inter_blocks())
14724 .then(|| {
14725 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
14726 let mut cost = search.lambda * partition_bits(BLOCK, true);
14727 let mut leaves = Vec::with_capacity(4);
14728 for &(sr, sc) in &leaf_positions {
14729 let (mi_row, mi_col) = (sr * 4, sc * 4);
14730 let (lx, ly) = (sc * SUB, sr * SUB);
14731 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
14732 let stack = find_mv_stack(
14733 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
14734 );
14735 let cstacks = leaf_compound_stacks(
14736 &grid,
14737 mi_row,
14738 mi_col,
14739 4,
14740 4,
14741 mi_cols,
14742 mi_rows,
14743 header.reference_select,
14744 golden,
14745 altref,
14746 );
14747 let (leaf, leaf_cost) = code_square_inter(
14748 &mut luma,
14749 &mut chroma,
14750 (lx, ly),
14751 SUB,
14752 &search,
14753 &mode_bits_table,
14754 reference,
14755 &stack,
14756 &cstacks,
14757 &grid,
14758 (mi_row, mi_col),
14759 (mi_rows, mi_cols),
14760 &obmc_refs,
14761 fctx,
14762 );
14763 let leaf_cost =
14764 leaf_cost + search.lambda * partition_bits(SUB, false);
14765 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
14766
14767 // And what four 8x8 leaves cost instead --
14768 // the same tree one step further down, which
14769 // the writer codes as a real PARTITION_SPLIT
14770 // at BLOCK_16X16 (lane-av1rd2). Same
14771 // skipped-block prune as the level above.
14772 let eight = (!leaf.skip
14773 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
14774 && (breakout == 0 || leaf.luma.len() > breakout)
14775 && split_inter_8()
14776 // lane-arfmode: arm 2 makes 16x16 the top
14777 // ARF's leaf floor -- the RD-optional 8x8
14778 // comparison is not offered. Counted only
14779 // when every other prune let it through,
14780 // so the counter means "refused", not
14781 // "never considered". The spec-forced 8x8s
14782 // at a straddling 16x16 (the
14783 // `sub_positions` path below) are a
14784 // different site and stay.
14785 && (search.arf_leaf8 || arfmode_hit_and_no()))
14786 .then(|| {
14787 restore(&mut luma, &mut chroma, (lx, ly), SUB, &leaf_base);
14788 let mut cost8 = search.lambda
14789 * (partition_bits(SUB, true)
14790 + 4.0 * partition_bits(8, false));
14791 let mut eight = Vec::with_capacity(4);
14792 for i in 0..4 {
14793 let (mr, mc) = (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
14794 let stack8 = find_mv_stack(
14795 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
14796 );
14797 let cstacks8: Vec<(
14798 i8,
14799 &Picture,
14800 crate::mvstack::CompoundMvStack,
14801 )> = if header.reference_select && leaf_compound() {
14802 [
14803 (crate::mvstack::GOLDEN_FRAME, golden),
14804 (crate::mvstack::ALTREF_FRAME, altref),
14805 ]
14806 .into_iter()
14807 .filter_map(|(r, pic)| {
14808 pic.map(|p| {
14809 (
14810 r,
14811 p,
14812 crate::mvstack::find_mv_stack_compound(
14813 &grid,
14814 mr,
14815 mc,
14816 2,
14817 2,
14818 (crate::mvstack::LAST_FRAME, r),
14819 mi_cols,
14820 mi_rows,
14821 grid.sign_bias_table(),
14822 &[(0, 0); 7],
14823 None,
14824 ),
14825 )
14826 })
14827 })
14828 .collect()
14829 } else {
14830 Vec::new()
14831 };
14832 let (leaf8, cost) = code_square_inter(
14833 &mut luma,
14834 &mut chroma,
14835 (lx + (i % 2) * 8, ly + (i / 2) * 8),
14836 8,
14837 &search,
14838 &mode_bits_table,
14839 reference,
14840 &stack8,
14841 &cstacks8,
14842 &grid,
14843 (mr, mc),
14844 (mi_rows, mi_cols),
14845 &obmc_refs,
14846 fctx,
14847 );
14848 cost8 += cost;
14849 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
14850 eight.push(leaf8);
14851 }
14852 (eight, cost8)
14853 });
14854 match eight {
14855 Some((eight, cost8)) if cost8 < leaf_cost => {
14856 partition_hit(3);
14857 cost += cost8;
14858 leaves.push(BlockCoeffs {
14859 eight: Some(eight),
14860 ..BlockCoeffs::default()
14861 });
14862 continue;
14863 }
14864 Some(_) => {
14865 restore(&mut luma, &mut chroma, (lx, ly), SUB, &after_leaf)
14866 }
14867 None => {}
14868 }
14869 partition_hit(2);
14870 cost += leaf_cost;
14871 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
14872 leaves.push(leaf);
14873 }
14874 (leaves, cost)
14875 });
14876 if let Some((leaves, cost)) = split {
14877 if cost < cost_whole {
14878 // The leaves' own `mi` cells are already in the
14879 // grid, and their reconstruction is what the
14880 // planes hold.
14881 partition_hit(1);
14882 sb_cost += cost;
14883 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
14884 continue;
14885 }
14886 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
14887 }
14888 partition_hit(0);
14889 sb_cost += cost_whole;
14890 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
14891 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
14892 } else {
14893 // The sub-positions actually inside the true frame, same
14894 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
14895 let sub_positions: Vec<(usize, usize)> = (0..4)
14896 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
14897 .filter(|&(sr, sc)| {
14898 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
14899 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
14900 })
14901 .collect();
14902 // Each leaf searches intra against its own `NEARESTMV`
14903 // candidate (`code_square_inter`), same real-inter choice
14904 // `search_inter_block` makes for a whole 32x32 block, at
14905 // this leaf's own 4x4-mi mv-stack window -- unless the
14906 // leaf's own half itself straddles the true edge, which
14907 // it codes as two (or one, at a true corner) 8x8 leaves
14908 // (`crate::tile::write_leaf8`'s inter counterpart),
14909 // mirroring the key frame search's straddling-16x16
14910 // handling above (lane-av1inter8).
14911 let mut leaves = Vec::with_capacity(sub_positions.len());
14912 for (sr, sc) in sub_positions {
14913 let (has_cols16, has_rows16) = (
14914 crate::tile::has_half(
14915 sc as u32 * crate::tile::SUB_MI,
14916 crate::tile::SUB_MI,
14917 header.mi_cols,
14918 ),
14919 crate::tile::has_half(
14920 sr as u32 * crate::tile::SUB_MI,
14921 crate::tile::SUB_MI,
14922 header.mi_rows,
14923 ),
14924 );
14925 if has_cols16 && has_rows16 {
14926 let (x, y) = (sc * SUB, sr * SUB);
14927 let (mi_row, mi_col) = (sr * 4, sc * 4);
14928 let stack = find_mv_stack(
14929 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
14930 );
14931 let cstacks = leaf_compound_stacks(
14932 &grid,
14933 mi_row,
14934 mi_col,
14935 4,
14936 4,
14937 mi_cols,
14938 mi_rows,
14939 header.reference_select,
14940 golden,
14941 altref,
14942 );
14943 let (block, _) = code_square_inter(
14944 &mut luma,
14945 &mut chroma,
14946 (x, y),
14947 SUB,
14948 &search,
14949 &mode_bits_table,
14950 reference,
14951 &stack,
14952 &cstacks,
14953 &grid,
14954 (mi_row, mi_col),
14955 (mi_rows, mi_cols),
14956 &obmc_refs,
14957 fctx,
14958 );
14959 // One publication point for every coded leaf
14960 // (`record_mi`): this site used to spell the vote
14961 // out with `ref_frame` pinned to LAST and `mv1`
14962 // to (0,0), which is the encoder-grid-drift class
14963 // -- correct only for as long as a leaf can never
14964 // be compound.
14965 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
14966 leaves.push(block);
14967 } else {
14968 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
14969 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
14970 let mut eight = Vec::with_capacity(2);
14971 for i in 0..4 {
14972 let leaf_x = x_sub + (i % 2) * 8;
14973 let leaf_y = y_sub + (i / 2) * 8;
14974 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
14975 continue;
14976 }
14977 let (mi_row, mi_col) =
14978 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
14979 let stack = find_mv_stack(
14980 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
14981 );
14982 let cstacks = leaf_compound_stacks(
14983 &grid,
14984 mi_row,
14985 mi_col,
14986 2,
14987 2,
14988 mi_cols,
14989 mi_rows,
14990 header.reference_select,
14991 golden,
14992 altref,
14993 );
14994 let (leaf, _) = code_square_inter(
14995 &mut luma,
14996 &mut chroma,
14997 (leaf_x, leaf_y),
14998 8,
14999 &search,
15000 &mode_bits_table,
15001 reference,
15002 &stack,
15003 &cstacks,
15004 &grid,
15005 (mi_row, mi_col),
15006 (mi_rows, mi_cols),
15007 &obmc_refs,
15008 fctx,
15009 );
15010 // Same publication point as the 16x16
15011 // straddling leaf above (`record_mi`).
15012 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
15013 eight.push(leaf);
15014 }
15015 leaves.push(BlockCoeffs {
15016 eight: Some(eight),
15017 ..BlockCoeffs::default()
15018 });
15019 }
15020 }
15021 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
15022 }
15023 }
15024 // The 64x64 root against what its four quadrants really cost.
15025 if let Some((cost64, block, after)) = sb64
15026 && (early64
15027 || cost64
15028 < sb_cost
15029 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
15030 {
15031 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15032 if block.inter.is_some_and(|i| i.ref1.is_some()) {
15033 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15034 }
15035 if !whole_inside {
15036 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15037 }
15038 blocks.truncate(mark);
15039 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
15040 // Overwrites every 16x16 mi cell the quadrant searches
15041 // published under this superblock, so the next block's stack
15042 // is built off the block that was really coded.
15043 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
15044 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
15045 for q in 1..4 {
15046 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
15047 blocks.push((r32 * cols + c32, Quadrant::Covered));
15048 }
15049 root_cost += cost64;
15050 } else {
15051 root_cost += sb_cost;
15052 }
15053 }
15054 // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
15055 // `partition_w128` symbol) against what its four superblocks really
15056 // cost, the same weighing the 64 root does one size down. Both sides
15057 // carry their own partition symbol, so the comparison is complete.
15058 // The root candidates, each tagged with the PARTITION symbol its
15059 // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
15060 // shapes (lane-ab128).
15061 let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
15062 if let Some((c, l, b, a)) = root128 {
15063 cands.push((c, l, 0, vec![b], a));
15064 }
15065 if let Some((horz, (c, l, halves, a))) = root_rect {
15066 cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
15067 }
15068 if let Some((symbol, (c, l, pieces, a))) = root_ab {
15069 cands.push((c, l, symbol, pieces.to_vec(), a));
15070 }
15071 // The witness knobs drop every other arm outright: on synthetic
15072 // content the whole block always wins its own comparison.
15073 if forced_rect != 0 {
15074 cands.retain(|c| c.2 == 1 || c.2 == 2);
15075 }
15076 if forced_ab != 0 {
15077 cands.retain(|c| c.2 == usize::from(forced_ab));
15078 }
15079 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
15080 // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
15081 // superblock arm codes the delta_q group too -- the Whole64 writer
15082 // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
15083 // with `!sb128_armed()`) and every smaller shape below it pass
15084 // `is_whole_sb = false` under a 128 grid, so the arm's first
15085 // (root-origin) superblock codes the group even when skipped. Only the skipped 128
15086 // NONE root escapes it, so the split side is charged here at the same
15087 // root lambda the candidates are priced with.
15088 let split_dq =
15089 delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
15090 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
15091 && (cost128
15092 < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
15093 // The witness knobs take the root whatever it costs, so the
15094 // forced block really reaches the writer.
15095 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
15096 || forced_rect != 0
15097 || forced_ab != 0)
15098 {
15099 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
15100 blocks.truncate(mark128);
15101 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
15102 let at = (root_r * 2) * cols + root_c * 2;
15103 match shape {
15104 0 => {
15105 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15106 let block = halves.into_iter().next().expect("the NONE arm's block");
15107 record_mi(
15108 &mut grid,
15109 root_r * 16,
15110 root_c * 16,
15111 32,
15112 block.inter,
15113 block.skip,
15114 );
15115 blocks.push((at, Quadrant::Whole128(block)));
15116 }
15117 // lane-ab128: three pieces, published at their own footprints
15118 // in the writer's own order ([`ab128_pieces`]).
15119 symbol @ 4..=7 => {
15120 B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15121 for (((mr, mc), (w, h)), piece) in
15122 ab128_pieces(symbol, (root_r * 16, root_c * 16))
15123 .iter()
15124 .zip(&halves)
15125 {
15126 record_mi_rect(
15127 &mut grid,
15128 *mr,
15129 *mc,
15130 (w / 4, h / 4),
15131 piece.inter,
15132 piece.skip,
15133 );
15134 }
15135 blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
15136 }
15137 symbol => {
15138 let horz = symbol == 1;
15139 if horz {
15140 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15141 } else {
15142 B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15143 }
15144 let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
15145 for (i, half) in halves.iter().enumerate() {
15146 let (mr, mc) = if horz {
15147 (root_r * 16 + i * 16, root_c * 16)
15148 } else {
15149 (root_r * 16, root_c * 16 + i * 16)
15150 };
15151 record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
15152 }
15153 blocks.push((at, Quadrant::Rect128(horz, halves)));
15154 }
15155 }
15156 for q in 1..16 {
15157 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
15158 blocks.push((r32 * cols + c32, Quadrant::Covered));
15159 }
15160 }
15161 }
15162 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
15163 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
15164 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
15165 for (&out, tile) in chroma_out.iter().zip(&chroma) {
15166 copy_rect(
15167 out,
15168 &tile.reconstruction,
15169 frame_width / 2,
15170 x0 / 2,
15171 y0 / 2,
15172 x1.div_ceil(2),
15173 y1.div_ceil(2),
15174 );
15175 }
15176 Ok(blocks)
15177 };
15178 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
15179 .into_iter()
15180 .flatten()
15181 {
15182 blocks[at] = quadrant;
15183 }
15184
15185 // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
15186 // superblock roots the search left whole, so a flat BD result is
15187 // attributable (class `gate-blind-to-feature`). A key frame codes none:
15188 // only the inter writer has a 128x128 block.
15189 if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
15190 let whole = blocks
15191 .iter()
15192 .filter(|q| matches!(q, Quadrant::Whole128(_)))
15193 .count();
15194 let roots = blocks
15195 .iter()
15196 .filter(|q| !matches!(q, Quadrant::Covered))
15197 .count();
15198 // lane-b128r: of those roots, how many code a REAL residual rather
15199 // than the skip-only block lane-b128 shipped -- the fire count this
15200 // arm's own gate row is read against.
15201 let residual = blocks
15202 .iter()
15203 .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
15204 .count();
15205 // lane-b128r: and how many named a second reference (the compound
15206 // arm at the 128 root).
15207 let compound = blocks
15208 .iter()
15209 .filter(
15210 |q| matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some())),
15211 )
15212 .count();
15213 // lane-b128hv: and how many roots took a rect cut instead, per shape
15214 // -- the HORZ/VERT fire count the gate rows are read against.
15215 let horz = blocks
15216 .iter()
15217 .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
15218 .count();
15219 let vert = blocks
15220 .iter()
15221 .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
15222 .count();
15223 let rect_compound = blocks
15224 .iter()
15225 .filter(|q| {
15226 matches!(q, Quadrant::Rect128(_, hs)
15227 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
15228 })
15229 .count();
15230 // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
15231 // .. _VERT_B order -- the per-shape fire count its gate rows are read
15232 // against.
15233 let ab: [usize; 4] = std::array::from_fn(|i| {
15234 blocks
15235 .iter()
15236 .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
15237 .count()
15238 });
15239 eprintln!(
15240 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
15241 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
15242 compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
15243 {roots} coded blocks ({:.1}% of the frame's area at 128)",
15244 ab[0],
15245 ab[1],
15246 ab[2],
15247 ab[3],
15248 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
15249 / blocks.len().max(1) as f64,
15250 );
15251 }
15252 let modes = blocks
15253 .iter()
15254 .flat_map(Quadrant::blocks)
15255 .map(|b| b.mode)
15256 .collect::<Vec<_>>();
15257 let inter_block_share = blocks
15258 .iter()
15259 .flat_map(Quadrant::blocks)
15260 .filter(|b| b.inter.is_some())
15261 .count() as f64
15262 / modes.len() as f64;
15263 for block in blocks.iter().flat_map(Quadrant::blocks) {
15264 if let Some(info) = block.inter {
15265 let r = (info.ref_frame as usize).min(7);
15266 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15267 }
15268 }
15269 #[cfg(test)]
15270 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
15271 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
15272 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
15273 // next frame's writer starts from them -- exactly what
15274 // `crate::stream::stored_cdfs_for` hands the decoder.
15275 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
15276 let mut cdfs = start_cdfs
15277 .cloned()
15278 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
15279 // lane-txi: set per frame, never inherited from the snapshot the
15280 // previous frame stored -- the content gate can flip the bit between
15281 // frames (class `per-tile-state-not-reset`).
15282 cdfs.reduced_tx_set = header.reduced_tx_set;
15283 let start_cdfs = CdfSnapshot(cdfs);
15284 let reference_select_bit = header.reference_select;
15285 let switchable_motion_mode = header.is_motion_mode_switchable;
15286 let warped_motion = header.allow_warped_motion;
15287 let order_hint_bits = seq.order_hint_bits;
15288 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
15289 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
15290 // What this frame stores is the LARGEST tile's end-of-tile tables --
15291 // its own header's `context_update_tile_id` (spec 7.20), which
15292 // `tile_info_of` set to exactly that tile.
15293 let store_tile = layout.largest_tile();
15294 let end_cdfs = std::cell::RefCell::new(None);
15295 // As in `encode_key_frame_inner`: every tile starts from this frame's
15296 // own tables, so no tile depends on any other.
15297 let code_tiles = |bits: u8,
15298 sb_cols: usize,
15299 cdef_grid: &[u8],
15300 units: &[Option<crate::restoration::WienerInfo>]|
15301 -> Result<Vec<Vec<u8>>> {
15302 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
15303 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
15304 crate::tile::arm_delta_q(
15305 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
15306 sb_cols,
15307 sb_q.clone().unwrap_or_default(),
15308 base_q_idx,
15309 );
15310 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
15311 crate::tile::arm_sb128(sb128_on());
15312 crate::tile::arm_sign_bias(sign_bias);
15313 // Thread-locals: every tile job arms its own worker.
15314 crate::tile::arm_reference_select(reference_select_bit);
15315 crate::tile::arm_motion_mode(switchable_motion_mode);
15316 crate::tile::arm_warped_motion(warped_motion);
15317 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
15318 crate::tile::arm_high_precision_mv(hp_mv);
15319 crate::tile::arm_screen(screen);
15320 crate::tile::arm_frame_mi_dims(frame_mi_dims);
15321 crate::tile::arm_filter_intra(filter_intra_on());
15322 let mut cdfs = start_cdfs.0.clone();
15323 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
15324 // Each tile's own MV grid: a candidate scan never reaches past
15325 // the tile's bounds, so a grid holding only this tile's own
15326 // blocks reads exactly as the decoder's frame-wide one does
15327 // under `MiGrid::set_tile_bounds`.
15328 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
15329 mv_grid.set_sign_bias(sign_bias);
15330 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
15331 mi_cols,
15332 mi_rows,
15333 base_q_idx,
15334 &blocks,
15335 tx_select,
15336 &mut cdfs,
15337 layout.rect(index),
15338 &mut mv_grid,
15339 )?;
15340 Ok((bytes, Some(cdfs)))
15341 })?;
15342 if let Some(cdfs) = stored {
15343 *end_cdfs.borrow_mut() = Some(cdfs);
15344 }
15345 Ok(out)
15346 };
15347 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
15348 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
15349 // this tile against the same single-slot reference this encoder predicted
15350 // from, under each candidate level.
15351 // The reference a DECODER holds is this frame's cropped size, not the
15352 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
15353 // reference whose height is not the header's own `frame_height` (spec
15354 // 7.9's compatible-size rule), and the chained-decode round trips prove
15355 // the two predict identically.
15356 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
15357 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
15358 reference.clone()
15359 } else {
15360 Picture {
15361 width: fw,
15362 height: fh,
15363 y: crop_plane(&reference.y, reference.width, fw, fh),
15364 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
15365 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
15366 }
15367 };
15368 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
15369 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
15370 // blocks may name GOLDEN needs that plane too, cropped the same way.
15371 let trial_golden = golden.map(|g| {
15372 if (g.width, g.height) == (fw, fh) {
15373 g.clone()
15374 } else {
15375 Picture {
15376 width: fw,
15377 height: fh,
15378 y: crop_plane(&g.y, g.width, fw, fh),
15379 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
15380 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
15381 }
15382 }
15383 });
15384 let trial_altref = altref.map(|a| {
15385 if (a.width, a.height) == (fw, fh) {
15386 a.clone()
15387 } else {
15388 Picture {
15389 width: fw,
15390 height: fh,
15391 y: crop_plane(&a.y, a.width, fw, fh),
15392 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
15393 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
15394 }
15395 }
15396 });
15397 let trial_last2 = last2.map(|l| {
15398 if (l.width, l.height) == (fw, fh) {
15399 l.clone()
15400 } else {
15401 Picture {
15402 width: fw,
15403 height: fh,
15404 y: crop_plane(&l.y, l.width, fw, fh),
15405 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
15406 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
15407 }
15408 }
15409 });
15410 let mut refs: [Option<&Picture>; 8] = [None; 8];
15411 refs[1] = Some(&trial_ref);
15412 refs[2] = trial_last2.as_ref();
15413 refs[4] = trial_golden.as_ref();
15414 refs[7] = trial_altref.as_ref();
15415 let refpix = crate::decode::RefPix::ready(refs);
15416 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
15417 // sum the block search believed it was minimising. Against the
15418 // post-filter per-frame PSNR the gate prints, this separates a trial
15419 // whose reconstruction is a lie from a filter stage that undoes the win.
15420 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
15421 let sse: u64 = luma
15422 .reconstruction
15423 .chunks(luma.width)
15424 .take(luma.true_height)
15425 .zip(picture_y8.chunks(luma.width))
15426 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
15427 .map(|(&r, &s)| {
15428 let d = i64::from(r) - i64::from(s);
15429 (d * d) as u64
15430 })
15431 .sum();
15432 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
15433 }
15434 let post = |luma: &Plane<'_>, tag: &str| {
15435 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
15436 return;
15437 }
15438 let sse: u64 = luma
15439 .reconstruction
15440 .chunks(luma.width)
15441 .take(luma.true_height)
15442 .zip(picture_y8.chunks(luma.width))
15443 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
15444 .map(|(&r, &s)| {
15445 let d = i64::from(r) - i64::from(s);
15446 (d * d) as u64
15447 })
15448 .sum();
15449 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
15450 };
15451 pick_and_apply_filters(
15452 &mut header,
15453 &mut luma,
15454 &mut chroma,
15455 [&picture_y8, &picture_u8, &picture_v8],
15456 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
15457 // this frame's own `tx_select`, so the search runs under inter
15458 // `TxMode::Select` too (it used to skip and leave every inter frame
15459 // unfiltered once Select became the default).
15460 true,
15461 &mut tiles,
15462 search.lambda,
15463 fctx,
15464 &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows),
15465 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
15466 // are what the NEXT frame writes from, so the winning re-code
15467 // publishes its own into `end_cdfs` -- the first write's are stale
15468 // the moment a second tile is coded.
15469 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
15470 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
15471 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
15472 crate::decode::decode_inter_frame_tiles_lr(
15473 &payloads,
15474 &header_tile_info,
15475 h.mi_cols,
15476 h.mi_rows,
15477 base_q_idx,
15478 h.frame_width,
15479 h.frame_height,
15480 &refpix,
15481 cdef,
15482 lf,
15483 h.allow_high_precision_mv,
15484 h.force_integer_mv,
15485 Some(fctx.interp_filter.get()),
15486 seq.enable_dual_filter,
15487 h.reference_select,
15488 // lane-txi: this frame's own bit, not the hardcoded `true`
15489 // the wrapper used to pass.
15490 h.reduced_tx_set,
15491 tx_select,
15492 lr,
15493 // The trial decode re-reads the tile the writer just wrote,
15494 // so it starts from the same tables the writer did (this
15495 // frame's `start_cdfs`), not from the defaults.
15496 Some(start_cdfs.0.clone()),
15497 sign_bias,
15498 h.allow_screen_content_tools,
15499 switchable_motion_mode,
15500 h.allow_warped_motion,
15501 seq.enable_filter_intra,
15502 // lane-deltaq: this frame's own delta_q/delta_lf params, so
15503 // the trial decode reads the per-superblock `delta_qindex`
15504 // syntax the writer just wrote.
15505 h.delta.clone(),
15506 fctx,
15507 )
15508 },
15509 )?;
15510 post(&luma, "EC_POSTFILTER");
15511 let mut cdfs = end_cdfs
15512 .into_inner()
15513 .unwrap_or_else(|| start_cdfs.0.clone());
15514 cdfs.reset_counts();
15515 let next_cdfs = CdfSnapshot(cdfs);
15516 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
15517 header.tile_info.tile_size_bytes = tile_size_bytes;
15518 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
15519 let mut stream = temporal_delimiter();
15520 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
15521
15522 let [u, v] = chroma;
15523 Ok(Encoded {
15524 stream,
15525 modes,
15526 inter_block_share,
15527 reconstruction: Picture {
15528 width: luma.width,
15529 height: luma.height,
15530 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15531 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15532 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
15533 },
15534 tile,
15535 mi_cols: header.mi_cols,
15536 mi_rows: header.mi_rows,
15537 base_q_idx,
15538 tx_select,
15539 switchable_motion_mode,
15540 screen,
15541 reduced_tx_set: header.reduced_tx_set,
15542 start_cdfs,
15543 next_cdfs,
15544 loop_filter: header.loop_filter,
15545 cdef: header.cdef,
15546 loop_restoration: header.loop_restoration,
15547 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
15548 // intra frames only).
15549 allow_intrabc: false,
15550 delta: header.delta.clone(),
15551 })
15552}
15553
15554/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
15555/// frame's temporal unit followed by one inter frame's temporal unit per
15556/// remaining picture, all sharing the key frame's sequence header -- and
15557/// each frame's own [`Encoded`], in coding order.
15558#[derive(Clone, Debug)]
15559pub struct EncodedSequence {
15560 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
15561 /// sequence header and the key frame) followed by each later frame's
15562 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
15563 /// the sequence header the key frame carried).
15564 pub stream: Vec<u8>,
15565 /// One entry per picture, in DISPLAY order — the order a decoder outputs
15566 /// them and the order `pictures` came in. Without a pyramid that is also
15567 /// the coding order; with one the two differ, and `coding_order` is the
15568 /// map between them.
15569 pub frames: Vec<Encoded>,
15570 /// The index into `frames` of each coded frame, in CODING order — what a
15571 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
15572 /// `0..frames.len()` on the flat path.
15573 pub coding_order: Vec<usize>,
15574}
15575
15576/// Encodes a sequence of pictures as a key frame followed by one inter frame
15577/// per remaining picture, each predicting from the previous frame's own
15578/// decoded reconstruction — never from the source, which is what a decoder
15579/// cannot see. Every picture must be the same even size (any even width and
15580/// height — each is padded to a whole number of 64x64 superblocks
15581/// internally, which is what lets an inter frame's reference always match
15582/// the frame being coded against it), and `pictures` must be non-empty.
15583///
15584/// # Errors
15585/// Returns an error when `pictures` is empty, when any picture besides the
15586/// first is not the same size as the first, or under the same conditions
15587/// [`encode_key_frame`] and the inter frame path do.
15588pub(crate) fn encode_sequence_with_ctx(
15589 pictures: &[Picture],
15590 base_q_idx: u8,
15591 deadzone: f64,
15592 fctx: &crate::decode::FrameCtx,
15593) -> Result<EncodedSequence> {
15594 let Some((first, rest)) = pictures.split_first() else {
15595 return Err(Error::unsupported(
15596 "AV1 encode",
15597 "a sequence needs at least one picture",
15598 ));
15599 };
15600 first.check_even()?;
15601 let render = (first.width, first.height);
15602 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
15603 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
15604 // the leaves that predict backward off it, and a `show_existing_frame`
15605 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
15606 // an A/B. Screen content stays flat (the content gate in
15607 // `Av1Encoder::encode_frames`, whose detector this asks first so the
15608 // whole sequence path is decided in one place), and so does a run that
15609 // asks for a quantizer rounding offset the facade does not carry: the
15610 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
15611 // the ablations' -- must keep the flat path rather than be silently
15612 // ignored.
15613 //
15614 // The reordering itself is NOT reimplemented here: it is the facade's
15615 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
15616 // called with this sequence's shape, so the two paths cannot drift.
15617 let pyramid = crate::encoder::Pyramid::from_env()
15618 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
15619 .filter(|_| !picture_is_screen(first));
15620 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
15621 if let Some(pyramid) = pyramid {
15622 for picture in rest {
15623 picture.check_even()?;
15624 if (picture.width, picture.height) != render {
15625 return Err(Error::unsupported(
15626 "AV1 encode",
15627 "every picture in a sequence must be the same size as the first",
15628 ));
15629 }
15630 }
15631 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
15632 pictures,
15633 base_q_idx,
15634 pyramid,
15635 armed_tiles(),
15636 );
15637 }
15638 // The key frame and every inter frame after it are coded at the same
15639 // padded size, so the reference each inter frame predicts from -- the
15640 // previous frame's own uncropped reconstruction, at the size a decoder's
15641 // reference buffer actually holds -- always matches the frame being
15642 // coded against it.
15643 let key = encode_key_frame_inner(
15644 &first.padded_to(SUPERBLOCK),
15645 base_q_idx,
15646 deadzone,
15647 &KEY_FRAME_MODES,
15648 split_blocks(),
15649 render,
15650 unspecified_color_config(),
15651 fctx,
15652 )?;
15653 let mut stream = key.stream.clone();
15654 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
15655 // key frame refreshes every slot, each inter frame only slot 0), which is
15656 // what `GOLDEN_FRAME` names.
15657 let golden = key.reconstruction.clone();
15658 // The frame two back, once there is one that is not the key frame
15659 // itself (which `GOLDEN_FRAME` already names).
15660 let mut prev2: Option<Picture> = None;
15661 let mut carried = key.next_cdfs.clone();
15662 let mut reference = key.reconstruction.clone();
15663 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
15664 for (i, picture) in rest.iter().enumerate() {
15665 picture.check_even()?;
15666 // lane-av1tpl2: the lookahead window the per-block lambda weighting
15667 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
15668 // sources at this frame's coded (padded) size. The tail of the
15669 // sequence gets a shorter window, and the last frame none at all.
15670 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
15671 .iter()
15672 .take(tpl_depth() - 1)
15673 .map(|n| n.padded_to(SUPERBLOCK))
15674 .collect();
15675 if (picture.width, picture.height) != render {
15676 return Err(Error::unsupported(
15677 "AV1 encode",
15678 "every picture in a sequence must be the same size as the first",
15679 ));
15680 }
15681 let order_hint = (i + 1) as u32;
15682 let inter = encode_inter_frame(
15683 &picture.padded_to(SUPERBLOCK),
15684 &reference,
15685 base_q_idx,
15686 deadzone,
15687 order_hint,
15688 flat_order_hints(order_hint, 0, prev2.is_some()),
15689 render,
15690 Some(&carried.0),
15691 Some(&golden),
15692 prev2.as_ref(),
15693 None,
15694 fctx,
15695 None,
15696 &lookahead,
15697 )?;
15698 stream.extend_from_slice(&inter.stream);
15699 carried = inter.next_cdfs.clone();
15700 prev2 = Some(std::mem::replace(
15701 &mut reference,
15702 inter.reconstruction.clone(),
15703 ));
15704 frames.push(crop_encoded(&inter, render.0, render.1));
15705 }
15706 Ok(EncodedSequence {
15707 stream,
15708 coding_order: (0..frames.len()).collect(),
15709 frames,
15710 })
15711}
15712
15713#[cfg(test)]
15714mod tests {
15715
15716 /// Every (site, frame type, block side) the census can be called with
15717 /// lands in its own ten-counter bucket, inside the array (class
15718 /// `enumerate-table-domain`: an off-by-one here would silently add two
15719 /// sites' trials together).
15720 #[test]
15721 fn the_split_census_buckets_are_distinct_and_in_bounds() {
15722 let mut seen = std::collections::BTreeSet::new();
15723 for site in 0..2 {
15724 for key in [true, false] {
15725 for side in [8usize, 16, 32, 64] {
15726 let base = super::split_census_base(site, key, side);
15727 assert!(
15728 base + 10 <= super::SPLIT_CENSUS.len(),
15729 "{site} {key} {side}"
15730 );
15731 assert!(seen.insert(base), "{site} {key} {side} collides");
15732 }
15733 }
15734 }
15735 assert_eq!(seen.len(), 16);
15736 }
15737
15738 /// An [`crate::mvstack::MvStack`] with every context at zero and no
15739 /// neighbours, for the pricer tests below to fill the one band each of
15740 /// them is about.
15741 /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
15742 /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
15743 /// against the same stack -- an offer the writer clamps prices the
15744 /// residual against a predictor the decoder never derives, which is the
15745 /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
15746 /// side, so the stream stays legal; here the pricer's own offer set is
15747 /// enumerated, class `enumerate-table-domain`).
15748 ///
15749 /// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt
15750 /// r2, 2026-09-29). It replaces the clip gate
15751 /// `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`,
15752 /// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a
15753 /// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable
15754 /// while the invariant above holds, so no recipe could ever satisfy it.
15755 /// Deletion loses no coverage on either half:
15756 /// * the clamp half -- this test IS the coverage, and it is strictly
15757 /// stronger than any clip gate: it enumerates the pricer's whole offer
15758 /// set against the writer's rule for every stack size 0..=4, and larger
15759 /// stacks add entries the pricers never offer (`best_new_mv_syntax`
15760 /// breaks at `entries.len() <= idx` for `idx > 0`, so indices 3/4 are
15761 /// unreachable at ANY stack size), which is why 0..=4 bounds the
15762 /// domain rather than sampling it;
15763 /// * the pixel half -- the deleted gate's own decode-vs-encoder-
15764 /// reconstruction compare on a 1280x768 sb128 sequence is already made
15765 /// four times over, by `a_128_superblock_clip_whose_root_search_codes_
15766 /// 128x128_blocks_decodes_exact`,
15767 /// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`,
15768 /// `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact`
15769 /// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
15770 /// (same geometry, same `force_sb128(true)`, same own-reconstruction AND
15771 /// ffmpeg compare).
15772 /// MEASURED before deleting (153 clip x size x frame-count x q combinations,
15773 /// `enc_probe`): `tile::drl_clamp_hits()` = 0 on every one. MUTATION PROOF
15774 /// the clip was never the variable: widening `best_new_mv_syntax`'s offer
15775 /// set to `0..5` fires the counter immediately (9/2/2/1 on
15776 /// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8,
15777 /// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp`
15778 /// and `DRL_CLAMP_HITS` are KEPT as the tripwire for the owning fix
15779 /// (`deferred(unblock: the DRL owner widens the pricer past the writer's
15780 /// `start + 2` ceiling, or retires the counter)`) -- this test will go red
15781 /// the moment either happens, which is the signal to re-open the cell.
15782 ///
15783 /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
15784 #[test]
15785 fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
15786 for n in 0..=4usize {
15787 let mut stack = bare_stack();
15788 for i in 0..n {
15789 stack.entries.push(crate::mvstack::StackEntry {
15790 mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
15791 weight: 1,
15792 });
15793 stack.drl_ctx.push(0);
15794 }
15795 stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
15796 stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
15797 stack.pred_mv = stack.nearest_mv;
15798 // Aim the vector at each entry in turn, so every index the offer
15799 // set holds is the one that wins at least once.
15800 for target in 0..n.max(1) {
15801 let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
15802 let (_, idx) =
15803 best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable");
15804 let idx = usize::from(idx);
15805 assert_eq!(
15806 crate::tile::signalled_drl_idx(n, 0, idx),
15807 idx,
15808 "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
15809 );
15810 }
15811 // The NEARMV arm's own offer set (`search_inter_block`,
15812 // `search_skip_64`): indices 1 and 2, offered only when the stack
15813 // really holds that entry.
15814 for idx in 1..=2usize {
15815 if stack.entries.get(idx).is_some() {
15816 assert_eq!(
15817 crate::tile::signalled_drl_idx(n, 1, idx),
15818 idx,
15819 "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
15820 );
15821 }
15822 }
15823 }
15824 }
15825
15826 fn bare_stack() -> crate::mvstack::MvStack {
15827 crate::mvstack::MvStack {
15828 entries: Default::default(),
15829 nearest_mv: (0, 0),
15830 near_mv: (0, 0),
15831 pred_mv: (0, 0),
15832 new_mv_ctx: 0,
15833 ref_mv_ctx: 0,
15834 zero_mv_ctx: 0,
15835 drl_ctx: Default::default(),
15836 above_refs: (None, None),
15837 left_refs: (None, None),
15838 above_nbr: None,
15839 left_nbr: None,
15840 above_skip: false,
15841 left_skip: false,
15842 }
15843 }
15844
15845 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
15846 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
15847 /// own neighbour-derived context. Red before lane-ctx, where the pricer
15848 /// spent four constants at CDF row 0 that assumed the pair was
15849 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
15850 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
15851 #[test]
15852 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
15853 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
15854 use crate::encode::symbol_bits as b;
15855 use crate::mvstack::{
15856 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
15857 LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
15858 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
15859 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
15860 };
15861 // (pair, unidirectional?, the tree's symbols as (table, p index,
15862 // context selector, value)) -- transcribed from the writer.
15863 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
15864 type Sym = (char, usize, usize, usize);
15865 let cases: [((i8, i8), bool, &[Sym]); 7] = [
15866 (
15867 (LAST_FRAME, LAST2_FRAME),
15868 true,
15869 &[('u', 0, 1, 0), ('u', 1, 7, 0)],
15870 ),
15871 (
15872 (LAST_FRAME, LAST3_FRAME),
15873 true,
15874 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
15875 ),
15876 (
15877 (LAST_FRAME, GOLDEN_FRAME),
15878 true,
15879 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
15880 ),
15881 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
15882 (
15883 (LAST_FRAME, ALTREF_FRAME),
15884 false,
15885 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
15886 ),
15887 (
15888 (LAST_FRAME, BWDREF_FRAME),
15889 false,
15890 &[
15891 ('c', 0, 3, 0),
15892 ('c', 1, 4, 0),
15893 ('b', 0, 2, 0),
15894 ('b', 1, 6, 0),
15895 ],
15896 ),
15897 (
15898 (LAST_FRAME, ALTREF2_FRAME),
15899 false,
15900 &[
15901 ('c', 0, 3, 0),
15902 ('c', 1, 4, 0),
15903 ('b', 0, 2, 0),
15904 ('b', 1, 6, 1),
15905 ],
15906 ),
15907 ];
15908 let nbr = |ref0, ref1: Option<i8>| {
15909 Some(NeighbourRef {
15910 is_inter: true,
15911 ref0,
15912 ref1,
15913 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
15914 })
15915 };
15916 // No neighbours (every context zero), then a mixed pair that puts the
15917 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
15918 for (above_nbr, left_nbr, above_refs, left_refs) in [
15919 (None, None, (None, None), (None, None)),
15920 (
15921 nbr(LAST_FRAME, None),
15922 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
15923 (Some(LAST_FRAME), None),
15924 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
15925 ),
15926 ] {
15927 let stack = crate::mvstack::MvStack {
15928 above_nbr,
15929 left_nbr,
15930 above_refs,
15931 left_refs,
15932 ..bare_stack()
15933 };
15934 let (a, a1) = above_refs;
15935 let (l, l1) = left_refs;
15936 let ctx_of = |sel: usize| match sel {
15937 1 => single_ref_p1_ctx(a, a1, l, l1),
15938 2 => single_ref_p2_ctx(a, a1, l, l1),
15939 3 => single_ref_p3_ctx(a, a1, l, l1),
15940 4 => single_ref_p4_ctx(a, a1, l, l1),
15941 5 => single_ref_p5_ctx(a, a1, l, l1),
15942 6 => single_ref_p6_ctx(a, a1, l, l1),
15943 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
15944 };
15945 for (pair, unidir, symbols) in cases {
15946 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
15947 + b(
15948 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
15949 usize::from(!unidir),
15950 );
15951 for &(table, p, sel, v) in symbols {
15952 let row = ctx_of(sel);
15953 want += match table {
15954 'u' => b(&UNI_COMP_REF[row][p], v),
15955 'c' => b(&COMP_REF[row][p], v),
15956 _ => b(&COMP_BWDREF[row][p], v),
15957 };
15958 }
15959 let got = super::compound_ref_bits(pair, &stack);
15960 assert!(
15961 (got - want).abs() < 1e-9,
15962 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
15963 priced {got} bits, writer codes {want}"
15964 );
15965 }
15966 }
15967 }
15968
15969 /// The `skip` and `is_inter` symbols are priced at the SAME context
15970 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
15971 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
15972 /// on every neighbour configuration whose context is not zero (class
15973 /// pricer-context-zero).
15974 #[test]
15975 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
15976 use crate::cdf::{INTRA_INTER, SKIP};
15977 use crate::encode::symbol_bits as b;
15978 use crate::mvstack::NeighbourRef;
15979 let nbr = |is_inter| NeighbourRef {
15980 is_inter,
15981 ref0: if is_inter {
15982 crate::mvstack::LAST_FRAME
15983 } else {
15984 0
15985 },
15986 ref1: None,
15987 uni: false,
15988 };
15989 for (above, left, above_skip, left_skip) in [
15990 (None, None, false, false),
15991 (Some(nbr(true)), Some(nbr(true)), true, false),
15992 (Some(nbr(false)), Some(nbr(false)), true, true),
15993 (Some(nbr(false)), None, false, true),
15994 (None, Some(nbr(true)), true, true),
15995 ] {
15996 let stack = crate::mvstack::MvStack {
15997 above_nbr: above,
15998 left_nbr: left,
15999 above_skip,
16000 left_skip,
16001 ..bare_stack()
16002 };
16003 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
16004 let ii_ctx = crate::tile::intra_inter_ctx(
16005 above.is_some(),
16006 left.is_some(),
16007 above.is_some_and(|n| n.is_inter),
16008 left.is_some_and(|n| n.is_inter),
16009 );
16010 for v in [false, true] {
16011 let (got, want) = (
16012 super::skip_bits_at(&stack, v),
16013 b(&SKIP[skip_ctx], usize::from(v)),
16014 );
16015 assert!(
16016 (got - want).abs() < 1e-9,
16017 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
16018 );
16019 let (got, want) = (
16020 super::intra_inter_bits_at(&stack, v),
16021 b(&INTRA_INTER[ii_ctx], usize::from(v)),
16022 );
16023 assert!(
16024 (got - want).abs() < 1e-9,
16025 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
16026 );
16027 }
16028 }
16029 }
16030
16031 /// [`super::single_ref_bits`] pays exactly what tile.rs'
16032 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
16033 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
16034 /// the context that symbol's own `single_ref_p*_ctx` derives from the
16035 /// block's above/left neighbours. Red before lane-pricer, where every
16036 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
16037 #[test]
16038 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
16039 use crate::cdf::SINGLE_REF as SR;
16040 use crate::encode::symbol_bits as b;
16041 use crate::mvstack::{
16042 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
16043 LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
16044 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
16045 };
16046 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
16047 above_refs,
16048 left_refs,
16049 above_nbr,
16050 left_nbr,
16051 ..bare_stack()
16052 };
16053 let nbr = |ref0, ref1| {
16054 Some(crate::mvstack::NeighbourRef {
16055 is_inter: true,
16056 ref0,
16057 ref1,
16058 uni: false,
16059 })
16060 };
16061 // (reference, the symbols `write_single_ref` emits as (p index, value))
16062 let cases: [(i8, &[(usize, usize)]); 7] = [
16063 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
16064 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
16065 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
16066 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
16067 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
16068 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
16069 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
16070 ];
16071 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
16072 // that puts every p* context on a different row -- the second with a
16073 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
16074 // off row 0.
16075 for (above_refs, left_refs, above_nbr, left_nbr) in [
16076 ((None, None), (None, None), None, None),
16077 (
16078 (Some(LAST_FRAME), None),
16079 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
16080 nbr(LAST_FRAME, None),
16081 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
16082 ),
16083 ] {
16084 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
16085 let (a, a1) = above_refs;
16086 let (l, l1) = left_refs;
16087 let ctx_of = |p: usize| match p {
16088 0 => single_ref_p1_ctx(a, a1, l, l1),
16089 1 => single_ref_p2_ctx(a, a1, l, l1),
16090 2 => single_ref_p3_ctx(a, a1, l, l1),
16091 3 => single_ref_p4_ctx(a, a1, l, l1),
16092 4 => single_ref_p5_ctx(a, a1, l, l1),
16093 _ => single_ref_p6_ctx(a, a1, l, l1),
16094 };
16095 for (ref_frame, symbols) in cases {
16096 // Plus the `comp_mode = 0` symbol the writer codes ahead of
16097 // the reference syntax on a `reference_select` frame.
16098 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
16099 if super::reference_select() {
16100 want += b(
16101 &crate::cdf::COMP_MODE
16102 [crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)],
16103 0,
16104 );
16105 }
16106 let got = super::single_ref_bits(ref_frame, &stack);
16107 assert!(
16108 (got - want).abs() < 1e-9,
16109 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
16110 priced {got} bits, writer codes {want}"
16111 );
16112 }
16113 }
16114 }
16115
16116 /// lane-av1tpl2's propagated map, on the two properties every decision
16117 /// under it rests on: a frame the whole lookahead window repeats exactly
16118 /// (uniform texture) leans on every cell alike, so every factor is 1 and
16119 /// the weighting is a no-op; and where the window really does save bits
16120 /// by predicting -- the textured half of a frame whose other half is
16121 /// flat -- the factor FALLS below 1, i.e. that half is coded more
16122 /// distortion-averse than the half nothing gains from.
16123 /// The distortion metric itself (lane-sse): a block the true frame edge
16124 /// cuts through is scored over its INSIDE part only, so a difference that
16125 /// lives entirely in the padding costs nothing and a block wholly past
16126 /// the edge scores zero. Before this, the search ranked modes,
16127 /// transforms and partition trees on samples the display crop throws
16128 /// away -- which lane-b64b had fixed for the 64x64 root alone.
16129 #[test]
16130 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
16131 // A 40x40 true frame on a 64x64 padded coding surface.
16132 let source = vec![10u8; 64 * 64];
16133 let plane = fresh_plane(&source, 64, 64, 40, 40);
16134 let mut reconstruction = vec![10u8; 64 * 64];
16135 // Off by 190 at (50, 50) -- past the true edge in both axes.
16136 reconstruction[50 * 64 + 50] = 200;
16137 assert_eq!(
16138 plane.block_sse(0, 0, 64, &reconstruction),
16139 0.0,
16140 "padding was scored"
16141 );
16142 // Off by 10 at (39, 39) -- the last sample the decoder shows.
16143 reconstruction[39 * 64 + 39] = 20;
16144 assert_eq!(
16145 plane.block_sse(0, 0, 64, &reconstruction),
16146 100.0,
16147 "inside was not scored"
16148 );
16149 // A 16x16 block whose every sample is padding.
16150 let block = vec![200u8; 16 * 16];
16151 assert_eq!(
16152 plane.block_sse(48, 0, 16, &block),
16153 0.0,
16154 "a block past the edge scored"
16155 );
16156 // A 16x16 block the edge cuts: 8 of its columns are inside.
16157 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
16158 }
16159
16160 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
16161 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
16162 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
16163 #[test]
16164 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
16165 let (base, res) = (162u8, 4i32);
16166 let rf = 2.0;
16167 // A superblock the window leans on more than the frame average is
16168 // coded FINER (lower qindex); a slack one coarser; the average one
16169 // exactly at the base.
16170 assert!(
16171 super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base,
16172 "leaned-on SB must go finer"
16173 );
16174 assert!(
16175 super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base,
16176 "idle SB must go coarser"
16177 );
16178 assert_eq!(
16179 super::deltaq_libaom(base, rf, rf, 1.0, res),
16180 base,
16181 "the average SB moves 0"
16182 );
16183 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
16184 let max = ((res * 9 - 1) / res) * res;
16185 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
16186 for k in [0.5f64, 1.0, 1.5] {
16187 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
16188 let d = q - i32::from(base);
16189 assert_eq!(
16190 d % res,
16191 0,
16192 "r={r} k={k}: offset {d} is not a whole {res}-step"
16193 );
16194 assert!(
16195 d.abs() <= max,
16196 "r={r} k={k}: offset {d} past libaom's +-{max}"
16197 );
16198 }
16199 }
16200 // The clamp is REACHED from both ends, so the bound is a real bound
16201 // and not a formula that never gets there.
16202 assert_eq!(
16203 i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base),
16204 -max
16205 );
16206 assert_eq!(
16207 i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base),
16208 max
16209 );
16210 // A stronger `k` never moves less than a weaker one.
16211 let d = |k: f64| {
16212 (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs()
16213 };
16214 assert!(
16215 d(0.5) <= d(1.0) && d(1.0) <= d(1.5),
16216 "strength must be monotone: {} {} {}",
16217 d(0.5),
16218 d(1.0),
16219 d(1.5)
16220 );
16221 // The frame reference is libaom's log-mean: flat in, the same value out.
16222 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
16223 }
16224
16225 /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
16226 /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
16227 /// shipped default, and the multiplier reaches the strength.
16228 #[test]
16229 fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
16230 let d = crate::speed::DQ_LEVEL_K;
16231 assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
16232 assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
16233 // Short and broken fields fall back per SLOT, not per spec.
16234 assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
16235 assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
16236 assert_eq!(super::DqLevel::TopArf as usize, 0);
16237 assert_eq!(super::DqLevel::MidArf as usize, 1);
16238 assert_eq!(super::DqLevel::Leaf as usize, 2);
16239 }
16240
16241 #[test]
16242 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
16243 // Four 64x64 superblocks across: the shipped map forms its ratio per
16244 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
16245 // only ever produce one ratio -- and one ratio, mean-normalised, is
16246 // the flat map, whatever the content underneath it.
16247 let (w, h) = (256usize, 64usize);
16248 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
16249 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
16250 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
16251 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
16252 for (i, &v) in f.iter().enumerate() {
16253 assert!(
16254 (v - 1.0).abs() < 1e-6,
16255 "cell {i} factor {v}, a flat map must move no lambda"
16256 );
16257 }
16258
16259 // Left half textured, right half constant: the window saves bits
16260 // predicting the left half and nothing at all on the right.
16261 let split: Vec<u8> = (0..w * h)
16262 .map(|i| {
16263 if i % w < w / 2 {
16264 ((i * 37) % 251) as u8
16265 } else {
16266 128
16267 }
16268 })
16269 .collect();
16270 let frames: Vec<&[u8]> = vec![&split, &split, &split];
16271 let cells_x = w / 16;
16272 for k in [0.25f64, 0.5, 1.0, 2.0] {
16273 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
16274 for r in 0..h / 16 {
16275 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
16276 assert!(
16277 lean < 1.0,
16278 "k={k} row {r}: leaned-on cell factor {lean} must be < 1"
16279 );
16280 assert!(
16281 idle > 1.0,
16282 "k={k} row {r}: idle cell factor {idle} must be > 1"
16283 );
16284 }
16285 }
16286 }
16287
16288 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
16289 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
16290 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
16291 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
16292 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
16293 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
16294 /// only a quarter of the 16x8 table and read the wrong byte for every
16295 /// block row but the first (silently wrong above-right/below-left
16296 /// availability -- wrong pixels, no error).
16297 #[test]
16298 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
16299 for (bw, bh) in [
16300 (16usize, 8usize),
16301 (8, 16),
16302 (32, 16),
16303 (16, 32),
16304 (64, 32),
16305 (32, 64),
16306 ] {
16307 let (bw_log2, bh_log2) = (
16308 (bw / 4).trailing_zeros() as usize,
16309 (bh / 4).trailing_zeros() as usize,
16310 );
16311 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
16312 for (name, table) in [
16313 ("has_tr", rect_reach_tables(bw, bh).0),
16314 ("has_bl", rect_reach_tables(bw, bh).1),
16315 ] {
16316 assert_eq!(
16317 table.len() * 8,
16318 rows * cols,
16319 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
16320 );
16321 let mut seen = vec![0u32; table.len() * 8];
16322 for blk_row in 0..rows {
16323 for blk_col in 0..cols {
16324 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
16325 assert!(
16326 idx < seen.len(),
16327 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
16328 );
16329 seen[idx] += 1;
16330 }
16331 }
16332 assert!(
16333 seen.iter().all(|&n| n == 1),
16334 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
16335 (row stride is not {cols})"
16336 );
16337 }
16338 }
16339 }
16340 use super::*;
16341 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
16342 use crate::probe::run_with_stdin;
16343 use std::process::{Command, Stdio};
16344
16345 /// Every rectangular shape this decoder codes, at every position a block
16346 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
16347 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
16348 /// (`reconintra.c`) answer, whose bodies are ported below.
16349 ///
16350 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
16351 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
16352 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
16353 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
16354 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
16355 /// oracle's own arrays, so a re-routed or truncated table fails here even
16356 /// where the two rows happen to agree.
16357 ///
16358 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
16359 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
16360 /// callers handle by predicting each transform unit as its own block.
16361 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
16362 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
16363 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
16364 /// (the horizontal shapes, which those partitions never produce).
16365 #[test]
16366 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
16367 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
16368 // it pins the 64 reach explicitly instead of following the process's
16369 // own superblock knob (`for_encoder`), which made it red under
16370 // `EC_AV1_SB128=1` for no defect of the code under test.
16371 let fctx = &crate::decode::FrameCtx::new();
16372 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
16373 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
16374 (4, 8, 64, 9280, 64, 550),
16375 (8, 4, 64, 3712, 64, 9630),
16376 (8, 16, 16, 2352, 16, 134),
16377 (16, 8, 16, 960, 16, 2400),
16378 (16, 32, 4, 620, 4, 32),
16379 (32, 16, 4, 32, 4, 184),
16380 (32, 64, 1, 127, 1, 0),
16381 (64, 32, 1, 19, 1, 34),
16382 (4, 16, 32, 5472, 32, 14),
16383 (16, 4, 32, 960, 32, 6464),
16384 (8, 32, 8, 1400, 8, 2),
16385 (32, 8, 8, 32, 8, 1136),
16386 (16, 64, 2, 382, 2, 0),
16387 (64, 16, 2, 4, 2, 84),
16388 ];
16389 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
16390 /// a block whose transform covers it whole (`row_off == col_off == 0`,
16391 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
16392 /// superblock (`sb_mi_size == 16`).
16393 fn libaom_reach(
16394 bw: usize,
16395 bh: usize,
16396 x: usize,
16397 y: usize,
16398 width: usize,
16399 height: usize,
16400 _fctx: &crate::decode::FrameCtx,
16401 ) -> (bool, bool) {
16402 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
16403 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
16404 let sb_mi_size = 16usize;
16405 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
16406 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
16407 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
16408 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
16409 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
16410 // has_top_right: top_available && right_available, then row_off == 0.
16411 let top_right = if y == 0 || x + bw >= width {
16412 false
16413 } else if blk_row_in_sb == 0 {
16414 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
16415 // `bw_unit < bw_unit`, false for a whole-block transform.)
16416 true
16417 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
16418 false
16419 } else {
16420 bit(tr_table)
16421 };
16422 // has_bottom_left: bottom_available && left_available, col_off == 0.
16423 let bottom_left = if x == 0 || y + bh >= height {
16424 false
16425 } else if blk_col_in_sb == 0 {
16426 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
16427 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
16428 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
16429 false
16430 } else {
16431 bit(bl_table)
16432 };
16433 (top_right, bottom_left)
16434 }
16435 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
16436 let (tr, bl) = rect_reach_tables(bw, bh);
16437 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
16438 assert_eq!(
16439 (tr.len(), sum(tr), bl.len(), sum(bl)),
16440 (tr_len, tr_sum, bl_len, bl_sum),
16441 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
16442 );
16443 // Two superblocks across and down, so the superblock-relative
16444 // position (and not the frame position) is what decides.
16445 for sb_y in [0usize, 64] {
16446 for sb_x in [0usize, 64] {
16447 for y in (sb_y..sb_y + 64).step_by(bh) {
16448 for x in (sb_x..sb_x + 64).step_by(bw) {
16449 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
16450 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
16451 assert_eq!(
16452 (got.above_right, got.below_left),
16453 want,
16454 "{bw}x{bh} at ({x}, {y})"
16455 );
16456 }
16457 }
16458 }
16459 }
16460 }
16461 }
16462
16463 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
16464 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
16465 /// aomenc gate decodes its stream through ffmpeg and is meaningless
16466 /// without it -- turns it into a hard failure. Without this the require
16467 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
16468 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
16469 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
16470 fn have_ffmpeg() -> bool {
16471 let present = Command::new("ffmpeg")
16472 .arg("-version")
16473 .stdout(Stdio::null())
16474 .stderr(Stdio::null())
16475 .status()
16476 .is_ok_and(|s| s.success());
16477 assert!(
16478 present
16479 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
16480 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
16481 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
16482 );
16483 present
16484 }
16485
16486 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
16487 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
16488 fn have_encoder(encoder: &str) -> bool {
16489 Command::new("ffmpeg")
16490 .args(["-hide_banner", "-encoders"])
16491 .stderr(Stdio::null())
16492 .output()
16493 .is_ok_and(|o| {
16494 String::from_utf8_lossy(&o.stdout)
16495 .lines()
16496 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
16497 })
16498 }
16499
16500 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
16501 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
16502 let out = run_with_stdin(
16503 Command::new("ffmpeg").args([
16504 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
16505 ]),
16506 stream,
16507 );
16508 assert!(
16509 out.status.success(),
16510 "ffmpeg refused the stream: {}",
16511 String::from_utf8_lossy(&out.stderr)
16512 );
16513 let (luma, chroma) = (width * height, width * height / 4);
16514 assert_eq!(
16515 out.stdout.len(),
16516 luma + 2 * chroma,
16517 "expected one 4:2:0 frame"
16518 );
16519 Picture {
16520 width,
16521 height,
16522 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
16523 u: out.stdout[luma..luma + chroma]
16524 .iter()
16525 .map(|&v| u16::from(v))
16526 .collect(),
16527 v: out.stdout[luma + chroma..]
16528 .iter()
16529 .map(|&v| u16::from(v))
16530 .collect(),
16531 }
16532 }
16533
16534 /// A picture with something of everything in it: a gradient, an edge, a
16535 /// ripple and a block of flat colour, none of them aligned to the block
16536 /// grid.
16537 /// The in-loop filters actually FIRE and the stream still decodes to
16538 /// exactly what the encoder kept as its reconstruction
16539 /// (gate-blind-to-feature: a filter search that always answered "off"
16540 /// would leave every other test just as green, and the BD gate that
16541 /// would notice is `#[ignore]`d).
16542 ///
16543 /// Run:
16544 /// cargo test -p ec-av1 --release --lib -- \
16545 /// encode::tests::the_filter_search_picks_real_filters
16546 #[test]
16547 fn the_filter_search_picks_real_filters() {
16548 let _knobs = crate::speed::knob_read();
16549 let fctx = &crate::decode::FrameCtx::for_encoder();
16550 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
16551 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
16552 let fired = encoded
16553 .frames
16554 .iter()
16555 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
16556 .count();
16557 assert!(
16558 fired > 0,
16559 "no frame of this sequence chose any in-loop filtering: {:?}",
16560 encoded
16561 .frames
16562 .iter()
16563 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
16564 .collect::<Vec<_>>()
16565 );
16566 // The reconstruction the encoder predicts from is the FILTERED one,
16567 // and it is what a decoder of the stream produces -- byte for byte,
16568 // frame for frame.
16569 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
16570 assert_eq!(decoded.len(), encoded.frames.len());
16571 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
16572 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
16573 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
16574 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
16575 }
16576 }
16577
16578 fn test_card(width: usize, height: usize) -> Picture {
16579 let mut picture = Picture::grey(width, height);
16580 for y in 0..height {
16581 for x in 0..width {
16582 let gradient = x as f64 * 200.0 / width as f64;
16583 let ripple = 30.0
16584 * (x as f64 * std::f64::consts::PI / 23.0).sin()
16585 * (y as f64 * std::f64::consts::PI / 37.0).cos();
16586 let edge = if x > width * 3 / 7 && y > height / 3 {
16587 40.0
16588 } else {
16589 0.0
16590 };
16591 picture.y[y * width + x] =
16592 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
16593 }
16594 }
16595 for y in 0..height / 2 {
16596 for x in 0..width / 2 {
16597 let i = y * width / 2 + x;
16598 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
16599 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
16600 }
16601 }
16602 picture
16603 }
16604
16605 fn psnr(a: &[u16], b: &[u16]) -> f64 {
16606 let squared: f64 = a
16607 .iter()
16608 .zip(b)
16609 .map(|(&x, &y)| {
16610 let d = f64::from(x) - f64::from(y);
16611 d * d
16612 })
16613 .sum();
16614 if squared == 0.0 {
16615 return f64::INFINITY;
16616 }
16617 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
16618 }
16619
16620 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
16621 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
16622 /// frame's new root fires on most superblocks -- and what BOTH decoders
16623 /// produce is the encoder's own reconstruction, sample for sample.
16624 ///
16625 /// The fire count is the `gate-blind-to-feature` guard: without it every
16626 /// assert below passes on a stream that codes no whole superblock at all.
16627 #[test]
16628 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
16629 let _knobs = crate::speed::knob_read();
16630 let fctx = &crate::decode::FrameCtx::for_encoder();
16631 // 4 x 3 superblocks, all of them wholly inside the frame.
16632 let (width, height) = (256usize, 192usize);
16633 let mut picture = Picture::grey(width, height);
16634 for y in 0..height {
16635 for x in 0..width {
16636 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
16637 }
16638 }
16639 for y in 0..height / 2 {
16640 for x in 0..width / 2 {
16641 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
16642 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
16643 }
16644 }
16645 let _ = take_i64_root_hits();
16646 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
16647 let [roots, _offered, _edge] = take_i64_root_hits();
16648 // The counters are process-global, so another test encoding in
16649 // parallel can only ADD to them -- the per-FRAME fact is the mode
16650 // list, which carries one entry per coded block and so exactly 12
16651 // when every superblock was coded as one 64x64 intra block.
16652 assert_eq!(
16653 encoded.modes.len(),
16654 12,
16655 "not every superblock was coded as one 64x64 intra block"
16656 );
16657 assert!(
16658 roots >= 8,
16659 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
16660 );
16661 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
16662
16663 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16664 assert_eq!(ours.len(), 1, "our decoder's frames");
16665 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
16666 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
16667 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
16668
16669 if !have_ffmpeg() {
16670 eprintln!("SKIP the ffmpeg half: no ffmpeg");
16671 return;
16672 }
16673 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16674 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
16675 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
16676 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
16677 }
16678
16679 /// The claim the whole encoder rests on: what a decoder produces is what
16680 /// the encoder said it would, sample for sample, on every plane.
16681 ///
16682 /// Prediction reads the reconstruction, so a single sample of drift
16683 /// anywhere would spread into every block below and to the right of it —
16684 /// which is why this is an equality and not a tolerance.
16685 #[test]
16686 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
16687 let _knobs = crate::speed::knob_read();
16688 let fctx = &crate::decode::FrameCtx::for_encoder();
16689 if !have_ffmpeg() {
16690 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
16691 return;
16692 }
16693 for &(width, height) in &[
16694 (64usize, 64usize),
16695 (96, 64),
16696 (160, 96),
16697 (32, 48),
16698 (248, 152),
16699 ] {
16700 let picture = test_card(width, height);
16701 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16702 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16703 assert_eq!(
16704 decoded.y, encoded.reconstruction.y,
16705 "{width}x{height}: luma"
16706 );
16707 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
16708 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
16709 }
16710 // One q index from each of the four coefficient-CDF contexts
16711 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
16712 let (width, height) = (64usize, 64usize);
16713 let picture = test_card(width, height);
16714 let _ = take_tx_depth_hits();
16715 for &q in &[15u8, 45, 100, 200] {
16716 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16717 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16718 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
16719 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
16720 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
16721 }
16722 // lane-av1tx: the exactness above is only a claim about SPLIT
16723 // transforms if some block actually split one (`gate-blind-to-feature`
16724 // -- with `tx_depth` stuck at 0 every assert here passes on the
16725 // pre-lane stream). The test card's edges split at these four
16726 // quantizers; the counter is per-process (another test encoding in
16727 // parallel can only ADD to it, so this can be masked, never falsely
16728 // failed), so it is read once for the whole q ladder.
16729 let depths = take_tx_depth_hits();
16730 assert!(
16731 depths[1] + depths[2] > 0,
16732 "no block split its transform: depths {depths:?}"
16733 );
16734 }
16735
16736 /// A synthetic screen-content picture -- a few flat colours in a grid of
16737 /// boxes with hard edges and text-like bars, the shape a desktop capture
16738 /// has -- so the palette path is exercised on content it is for.
16739 #[cfg(test)]
16740 fn screen_card(width: usize, height: usize) -> Picture {
16741 const INK: [u16; 4] = [16, 90, 180, 235];
16742 let mut picture = Picture::grey(width, height);
16743 for y in 0..height {
16744 for x in 0..width {
16745 let cell = (x / 24 + y / 24) % 2;
16746 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
16747 picture.y[y * width + x] = INK[cell * 2 + bar];
16748 }
16749 }
16750 // Four chroma colours, not two: a two-colour chroma block only ever
16751 // codes a `PaletteSizeUV` of 2, which leaves
16752 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
16753 // deltas and the neighbour cache flags, exercised only when
16754 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
16755 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
16756 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
16757 for y in 0..height / 2 {
16758 for x in 0..width / 2 {
16759 let cell = (x / 12 + 2 * (y / 12)) % 4;
16760 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
16761 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
16762 }
16763 }
16764 picture
16765 }
16766
16767 /// The lane's own end-to-end check: on screen content the detector fires,
16768 /// blocks really take a palette (fire count, class
16769 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
16770 /// symbol this lane writes -- reconstructs exactly what the encoder did.
16771 /// The film-shaped `test_card` must NOT trip the detector, which is what
16772 /// keeps every non-screen stream byte-identical.
16773 #[test]
16774 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
16775 let _knobs = crate::speed::knob_read();
16776 let fctx = &crate::decode::FrameCtx::for_encoder();
16777 let (width, height) = (192usize, 96usize);
16778 let _ = crate::tile::take_palette_hits();
16779 let picture = screen_card(width, height);
16780 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16781 assert!(
16782 encoded.screen,
16783 "the detector did not fire on screen content -- no palette syntax was coded at all"
16784 );
16785 let hits = crate::tile::take_palette_hits();
16786 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
16787 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
16788 // The chroma half is a claim about the plane-1 syntax only if some
16789 // block really took a chroma palette (`gate-blind-to-feature`): every
16790 // exactness assert below passes on a stream that codes
16791 // `palette_uv_mode == 0` everywhere.
16792 let uv_hits = crate::tile::take_palette_uv_hits();
16793 assert!(
16794 uv_hits[0] > 0,
16795 "no block took a chroma palette: {uv_hits:?}"
16796 );
16797 let uv_cached = crate::tile::take_palette_uv_cache_hits();
16798 eprintln!(
16799 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
16800 uv_hits[0],
16801 &uv_hits[2..]
16802 );
16803 assert!(
16804 uv_cached > 0,
16805 "no chroma base colour came out of the neighbour cache -- \
16806 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
16807 );
16808 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
16809 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
16810 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
16811 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
16812 if !have_ffmpeg() {
16813 eprintln!("SKIP the ffmpeg half: no ffmpeg");
16814 return;
16815 }
16816 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16817 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
16818 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
16819 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
16820 // A whole GOP: the inter frames' own intra blocks carry the palette
16821 // syntax too (the three intra arms of the inter writers), which only
16822 // ffmpeg reading the frames back can prove.
16823 let moved: Vec<Picture> = (0..4)
16824 .map(|f| {
16825 let base = screen_card(width, height);
16826 let mut out = Picture::grey(width, height);
16827 for y in 0..height {
16828 for x in 0..width {
16829 let sx = (x + f * 7) % width;
16830 out.y[y * width + x] = base.y[y * width + sx];
16831 }
16832 }
16833 for y in 0..height / 2 {
16834 for x in 0..width / 2 {
16835 let sx = (x + f * 3) % (width / 2);
16836 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
16837 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
16838 }
16839 }
16840 out
16841 })
16842 .collect();
16843 let _ = crate::tile::take_palette_hits();
16844 let _ = crate::tile::take_palette_uv_hits();
16845 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
16846 let gop_hits = crate::tile::take_palette_hits();
16847 let gop_uv_hits = crate::tile::take_palette_uv_hits();
16848 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
16849 eprintln!(
16850 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
16851 {} chroma palette blocks",
16852 inter_screen, gop_hits[0], gop_uv_hits[0]
16853 );
16854 assert!(
16855 gop_uv_hits[0] > 0,
16856 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
16857 );
16858 assert!(
16859 inter_screen > 0,
16860 "no inter frame set allow_screen_content_tools"
16861 );
16862 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
16863 assert_eq!(
16864 gop_decoded.len(),
16865 gop.frames.len(),
16866 "our decoder: GOP frame count"
16867 );
16868 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
16869 assert_eq!(
16870 ours.y, frame.reconstruction.y,
16871 "our decoder: GOP frame {i} luma"
16872 );
16873 }
16874 if have_ffmpeg() {
16875 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
16876 assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count");
16877 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
16878 assert_eq!(
16879 theirs.y, frame.reconstruction.y,
16880 "ffmpeg: GOP frame {i} luma"
16881 );
16882 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
16883 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
16884 }
16885 }
16886
16887 // The other half of the keep rule: film-shaped content leaves the
16888 // detector (and so the whole sequence header) alone.
16889 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
16890 assert!(
16891 !film.screen,
16892 "the detector fired on the film-shaped test card"
16893 );
16894 }
16895
16896 /// The lane's keep-rule measurement: the gate's own screen capture, one
16897 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
16898 /// Setting the bit forces deblocking, CDEF and loop restoration off for
16899 /// that frame, so the table is exactly the filter loss against the bytes
16900 /// the copied blocks save.
16901 #[test]
16902 #[ignore = "needs the real-library manifest and ffmpeg"]
16903 fn probe_intrabc_key_frame() {
16904 let _knobs = crate::speed::knob_write();
16905 let fctx = &crate::decode::FrameCtx::for_encoder();
16906 // lane-av1clipprobe: the manifest is a real-library file, so it
16907 // resolves through the crate's one fixture root (EC_FIXTURES first)
16908 // and its absence is reported by the one probe instead of an inline
16909 // SKIP that named no path. A file that IS there but unreadable is not
16910 // an absence, so it is a hard error rather than a second silent skip.
16911 let Some(manifest_path) =
16912 crate::library_fixture::require("real-library-manifest.tsv", "probe_intrabc_key_frame")
16913 else {
16914 return;
16915 };
16916 let manifest = std::fs::read_to_string(&manifest_path).unwrap_or_else(|e| {
16917 panic!(
16918 "probe_intrabc_key_frame: {} is present but unreadable ({e})",
16919 manifest_path.display()
16920 )
16921 });
16922 let Some(clip) = manifest
16923 .lines()
16924 .skip(1)
16925 .filter_map(|l| l.split('\t').next())
16926 .find(|p| {
16927 p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
16928 })
16929 else {
16930 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
16931 return;
16932 };
16933 let (width, height) = (1280usize, 768usize);
16934 let picture = clip_frame(clip, "0", width, height);
16935 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
16936 for q in [5u8, 20, 35, 45] {
16937 for on in [false, true] {
16938 force_intrabc(Some(on));
16939 let _ = crate::tile::take_intrabc_hits();
16940 let _ = take_intrabc_search();
16941 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16942 let hits = crate::tile::take_intrabc_hits();
16943 let search = take_intrabc_search();
16944 eprintln!(
16945 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
16946 if encoded.allow_intrabc { "on" } else { "off" },
16947 encoded.stream.len(),
16948 psnr_all(&encoded.reconstruction, &picture),
16949 hits[0],
16950 &hits[1..],
16951 search[0],
16952 search[1],
16953 search[2],
16954 );
16955 }
16956 }
16957 force_intrabc(None);
16958 }
16959
16960 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
16961 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
16962 /// take a block vector (fire count + DV histogram, class
16963 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
16964 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
16965 /// exactly what the encoder did.
16966 #[test]
16967 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
16968 let _knobs = crate::speed::knob_write();
16969 let fctx = &crate::decode::FrameCtx::for_encoder();
16970 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
16971 // superblocks of 64) and tall enough for a source superblock row
16972 // above the blocks that copy from it.
16973 let (width, height) = (512usize, 256usize);
16974 let picture = screen_card(width, height);
16975 let _ = crate::tile::take_intrabc_hits();
16976 // The default is OFF (it measured worse on the real screen capture --
16977 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
16978 // the arm on for its own encode and puts it back straight after.
16979 force_intrabc(Some(true));
16980 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16981 force_intrabc(None);
16982 assert!(
16983 encoded.allow_intrabc,
16984 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
16985 intrabc_source_share() * 100.0
16986 );
16987 let hits = crate::tile::take_intrabc_hits();
16988 eprintln!(
16989 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
16990 hits[0],
16991 &hits[1..],
16992 intrabc_source_share() * 100.0
16993 );
16994 let search = take_intrabc_search();
16995 eprintln!(
16996 "intrabc searches {} found-valid {} won-RD {}",
16997 search[0], search[1], search[2]
16998 );
16999 assert!(
17000 hits[0] > 0,
17001 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
17002 );
17003 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
17004 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
17005 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
17006 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
17007 if !have_ffmpeg() {
17008 eprintln!("SKIP the ffmpeg half: no ffmpeg");
17009 return;
17010 }
17011 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17012 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
17013 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
17014 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
17015 }
17016
17017 /// The minimal repro that isolated the inter-residual desync: a key frame
17018 /// followed by one inter frame whose single superblock carries one
17019 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
17020 /// coefficient, its three sibling blocks all `skip: true`. Before the
17021 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
17022 /// found when processing input") even though every symbol either block
17023 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
17024 /// same coefficient syntax decodes clean on every intra key-frame gate).
17025 #[test]
17026 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
17027 let _knobs = crate::speed::knob_write();
17028 let fctx = &crate::decode::FrameCtx::for_encoder();
17029 if !have_ffmpeg() {
17030 eprintln!(
17031 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
17032 );
17033 return;
17034 }
17035 let (width, height) = (64usize, 64usize);
17036 let picture = Picture::grey(width, height);
17037 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17038
17039 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
17040 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
17041
17042 let residual_block = BlockCoeffs {
17043 luma_tx_types: Vec::new(),
17044 angle_delta_y: 0,
17045 cfl_alphas: None,
17046 filter_intra: None,
17047 luma: vec![Coeff {
17048 row: 0,
17049 col: 0,
17050 level: 4,
17051 }],
17052 u: Vec::new(),
17053 v: Vec::new(),
17054 mode: 0,
17055 uv_mode: 0,
17056 skip: false,
17057 eight: None,
17058 dv: None,
17059 palette: None,
17060 palette_uv: None,
17061 tx_depth: 0,
17062 inter: Some(InterInfo {
17063 ref1: None,
17064 mv1: (0, 0),
17065 ref_frame: crate::mvstack::LAST_FRAME,
17066 mode: InterMode::NearestMv,
17067 mv: (0, 0),
17068 ref_mv_idx: 0,
17069 }),
17070 motion_mode: 0,
17071 };
17072 let skipped_block = BlockCoeffs {
17073 skip: true,
17074 inter: Some(InterInfo {
17075 ref1: None,
17076 mv1: (0, 0),
17077 ref_frame: crate::mvstack::LAST_FRAME,
17078 mode: InterMode::NearestMv,
17079 mv: (0, 0),
17080 ref_mv_idx: 0,
17081 }),
17082 ..BlockCoeffs::default()
17083 };
17084 let blocks = vec![
17085 Quadrant::Whole(residual_block),
17086 Quadrant::Whole(skipped_block.clone()),
17087 Quadrant::Whole(skipped_block.clone()),
17088 Quadrant::Whole(skipped_block),
17089 ];
17090 // lane-av1obmc: the header this tile is decoded under carries
17091 // `is_motion_mode_switchable`, so the writer must be armed with it
17092 // too or the decoder reads a `motion_mode` symbol nobody wrote.
17093 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
17094 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
17095 let tile = crate::tile::sb_coeff_inter_frame_tile(
17096 inter_header.mi_cols,
17097 inter_header.mi_rows,
17098 100,
17099 &blocks,
17100 )
17101 .unwrap();
17102
17103 // `key.stream` is already a temporal delimiter, the sequence header
17104 // and the key frame's own OBU (`encode_key_frame` built it from the
17105 // same `key_frame_headers(width, height, 100)` this test calls), so
17106 // the inter frame's OBU is appended straight onto it rather than
17107 // re-deriving the key frame's tile bytes.
17108 let mut stream = key.stream.clone();
17109 stream.extend_from_slice(&temporal_delimiter());
17110 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
17111
17112 ffmpeg_decode_sequence(&stream, width, height, 2);
17113 }
17114
17115 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
17116 /// frame size an AV1 decoder allocates, not necessarily the render size
17117 /// (see [`a_frame_round_trips_at_its_own_size`]).
17118 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
17119 // Distinct per call, not per process: the test binary runs callers on
17120 // parallel threads, and a shared name lets one test's cleanup delete
17121 // the stream another test's ffprobe is still reading.
17122 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
17123 let path = std::env::temp_dir().join(format!(
17124 "ec-av1-probe-{}-{}.obu",
17125 std::process::id(),
17126 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
17127 ));
17128 let _ = std::fs::remove_file(&path);
17129 std::fs::write(&path, stream).expect("writing the probe stream");
17130 let out = Command::new("ffprobe")
17131 .args([
17132 "-v",
17133 "error",
17134 "-f",
17135 "obu",
17136 "-select_streams",
17137 "v:0",
17138 "-show_entries",
17139 "stream=width,height",
17140 "-of",
17141 "csv=p=0",
17142 ])
17143 .arg(&path)
17144 .output()
17145 .expect("ffprobe failed to run");
17146 let _ = std::fs::remove_file(&path);
17147 assert!(
17148 out.status.success(),
17149 "ffprobe refused the stream: {}",
17150 String::from_utf8_lossy(&out.stderr)
17151 );
17152 let text = String::from_utf8_lossy(&out.stdout);
17153 let mut fields = text.trim().split(',');
17154 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
17155 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
17156 (width, height)
17157 }
17158
17159 /// lane-av1cap: the final filter replay against the capture decode it
17160 /// replaced, at the block-padded and straddling sizes the whole-frame
17161 /// tests cover -- `set_verify_final_replay` makes
17162 /// [`pick_and_apply_filters`] run both on every frame and assert, per
17163 /// frame, that the spliced picture and the two filter stages the
17164 /// restoration search reads are bit-identical over the frame's own crop.
17165 #[test]
17166 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
17167 let _knobs = crate::speed::knob_write();
17168 let fctx = &crate::decode::FrameCtx::for_encoder();
17169 crate::decode::set_verify_final_replay(true);
17170 for &(width, height) in &[
17171 (64usize, 56usize),
17172 (216, 96),
17173 (192, 120),
17174 (640, 352),
17175 (1280, 720),
17176 ] {
17177 eprintln!("--- {width}x{height}");
17178 let picture = test_card(width, height);
17179 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17180 }
17181 crate::decode::set_verify_final_replay(false);
17182 }
17183
17184 /// A key frame at an arbitrary even size round-trips through ffmpeg over
17185 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
17186 /// picture's own size, and what ffmpeg decodes over that same top-left
17187 /// region equals it sample for sample.
17188 ///
17189 /// This does not check that `ffprobe` reports the picture's own size,
17190 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
17191 /// (block-padded) frame size, the same one libaom itself would code for
17192 /// a non-block-aligned picture. `render_width`/`render_height` (which
17193 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
17194 /// decoder is required to crop pixels by, and ffmpeg's does not --
17195 /// checked empirically against ffprobe here and against a real libaom
17196 /// encode separately. So the coded size, not the render size, is what
17197 /// `ffprobe` is asserted to report below.
17198 #[test]
17199 fn a_frame_round_trips_at_its_own_size() {
17200 let _knobs = crate::speed::knob_read();
17201 let fctx = &crate::decode::FrameCtx::for_encoder();
17202 if !have_ffmpeg() {
17203 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
17204 return;
17205 }
17206 // 854x480 is covered separately by
17207 // `an_854x480_picture_round_trips_through_its_padding`, which its own
17208 // doc comment explains was worth keeping as its own test.
17209 for &(width, height) in &[
17210 (1920usize, 1080usize),
17211 (640, 352),
17212 (1280, 720),
17213 (64, 56),
17214 (854, 480),
17215 (216, 96),
17216 (192, 120),
17217 ] {
17218 let picture = test_card(width, height);
17219 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17220 assert_eq!(
17221 (encoded.reconstruction.width, encoded.reconstruction.height),
17222 (width, height),
17223 "{width}x{height}: reconstruction is cropped to the picture's own size"
17224 );
17225 assert_eq!(
17226 ffprobe_size(&encoded.stream),
17227 (width as u32, height as u32),
17228 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
17229 );
17230 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17231 assert_eq!(
17232 decoded.y, encoded.reconstruction.y,
17233 "{width}x{height}: luma"
17234 );
17235 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
17236 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
17237 }
17238 }
17239
17240 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
17241 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
17242 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
17243 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
17244 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
17245 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
17246 /// col`) -- different bits of an 8-byte table, one true, one false. The
17247 /// stride libaom indexes by is fixed at its compile-time maximum
17248 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
17249 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
17250 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
17251 /// row/col position within the (correctly 64-relative) superblock stayed
17252 /// right, only the table's own row stride was wrong. Fixed in
17253 /// `Reach::table_stride`; not an arithmetic-coder desync (an
17254 /// EC_RNG-per-symbol trace against the same debug decoder found the
17255 /// bitstream byte-for-byte identical to libaom's across all 51188
17256 /// symbols of this frame before this bug was found).
17257 ///
17258 /// Since the frame header started writing the true (unpadded) display
17259 /// size into `frame_width`/`frame_height` rather than the padded coded
17260 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
17261 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
17262 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
17263 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
17264 /// the header's own size before output).
17265 #[test]
17266 fn an_854x480_picture_round_trips_through_its_padding() {
17267 let _knobs = crate::speed::knob_read();
17268 let fctx = &crate::decode::FrameCtx::for_encoder();
17269 if !have_ffmpeg() {
17270 return;
17271 }
17272 let (width, height) = (854usize, 480usize);
17273 let picture = test_card(width, height);
17274 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17275 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17276 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
17277 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
17278 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
17279 }
17280
17281 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
17282 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
17283 /// superblock, both partition tables:
17284 ///
17285 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
17286 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
17287 /// wiring the TU sites onto it changes no existing stream;
17288 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
17289 /// NULL in libaom because that lookup never happens, and reading a
17290 /// 4x4 row out of the three-row vert tables is what crashed a real
17291 /// `--enable-tx-size-search=1` stream (r2);
17292 /// 3. and it must be the BLOCK's vert answer where the two tables
17293 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
17294 /// row 1, column 0 reads its above-right samples from the 8x8 to its
17295 /// upper right, which a vertical AB partition codes AFTER it
17296 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
17297 #[test]
17298 fn of_tu_follows_the_block_row_including_under_vert_ab() {
17299 let fctx = &crate::decode::FrameCtx::for_encoder();
17300 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
17301 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
17302 // above-right answer is the BLOCK's, which is the whole reason a unit
17303 // asks the block instead of looking itself up (the
17304 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
17305 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
17306 assert_eq!(
17307 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
17308 plain.above_right,
17309 "ordinary table: the top-right TX4 unit takes the block's row"
17310 );
17311 let guard = Reach::vert_ab_partition();
17312 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
17313 assert_eq!(
17314 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
17315 vert.above_right,
17316 "vert AB: the unit follows the vert row the block just picked"
17317 );
17318 assert_ne!(
17319 plain.above_right, vert.above_right,
17320 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
17321 );
17322 drop(guard);
17323 }
17324
17325 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
17326 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
17327 /// reconintra.c`), for every 16x16 and 32x32 block position across three
17328 /// superblocks square -- interior and every superblock edge (top row,
17329 /// left column, right column, bottom row) both sizes reach. Written to
17330 /// catch the class the `table_stride` bug was: an index stride silently
17331 /// wrong for one block size while looking plausible for the other.
17332 #[test]
17333 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
17334 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
17335 // it pins the 64 reach explicitly instead of following the process's
17336 // own superblock knob (`for_encoder`), which made it red under
17337 // `EC_AV1_SB128=1` for no defect of the code under test.
17338 let fctx = &crate::decode::FrameCtx::new();
17339 // Transcribed from has_top_right/has_bottom_left's row_off==0,
17340 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
17341 // 128px reference grid) pinned as libaom pins it, independent of the
17342 // 64px superblock this crate actually codes.
17343 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
17344 if y == 0 || x + side >= width {
17345 return false;
17346 }
17347 let (row, col, per_side) = (
17348 (y % SUPERBLOCK) / side,
17349 (x % SUPERBLOCK) / side,
17350 SUPERBLOCK / side,
17351 );
17352 if row == 0 {
17353 return true;
17354 }
17355 if col + 1 == per_side {
17356 return false;
17357 }
17358 let stride = 128 / side;
17359 let index = row * stride + col;
17360 let table = if side == BLOCK {
17361 [95u8, 87].to_vec()
17362 } else {
17363 vec![255, 85, 119, 85, 127, 85, 119, 85]
17364 };
17365 (table[index / 8] >> (index % 8)) & 1 != 0
17366 }
17367
17368 fn libaom_bottom_left(
17369 side: usize,
17370 x: usize,
17371 y: usize,
17372 height: usize,
17373 _fctx: &crate::decode::FrameCtx,
17374 ) -> bool {
17375 if x == 0 || y + side >= height {
17376 return false;
17377 }
17378 let (row, col, per_side) = (
17379 (y % SUPERBLOCK) / side,
17380 (x % SUPERBLOCK) / side,
17381 SUPERBLOCK / side,
17382 );
17383 if col == 0 {
17384 return row * side + side < SUPERBLOCK;
17385 }
17386 if row + 1 == per_side {
17387 return false;
17388 }
17389 let stride = 128 / side;
17390 let index = row * stride + col;
17391 let table = if side == BLOCK {
17392 [4u8, 4].to_vec()
17393 } else {
17394 vec![84, 16, 84, 0, 84, 16, 84, 0]
17395 };
17396 (table[index / 8] >> (index % 8)) & 1 != 0
17397 }
17398
17399 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
17400 for side in [16usize, BLOCK] {
17401 for y in (0..height).step_by(side) {
17402 for x in (0..width).step_by(side) {
17403 let reach = Reach::of(side, x, y, width, height, fctx);
17404 assert_eq!(
17405 reach.above_right,
17406 libaom_top_right(side, x, y, width, height),
17407 "side={side} x={x} y={y}: above_right"
17408 );
17409 assert_eq!(
17410 reach.below_left,
17411 libaom_bottom_left(side, x, y, height, fctx),
17412 "side={side} x={x} y={y}: below_left"
17413 );
17414 }
17415 }
17416 }
17417 }
17418
17419 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
17420 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
17421 /// column inside the superblock) may read the below-left samples the
17422 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
17423 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
17424 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
17425 /// stream that partitions that small first hits the still-refused
17426 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
17427 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
17428 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
17429 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
17430 /// pixels -- lane-palette2 r12: the square multi-TU path used the
17431 /// standalone-block tables instead of this rule and granted a 16x16
17432 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
17433 #[test]
17434 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
17435 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
17436 // *_count_unit = tx size / 4.
17437 fn libaom_tr(
17438 bw: usize,
17439 bh: usize,
17440 col_off: usize,
17441 row_off: usize,
17442 tx: usize,
17443 blk: bool,
17444 ) -> bool {
17445 let (plane_bw_unit, count) = (bw / 4, tx / 4);
17446 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
17447 let _ = bh;
17448 if row_off_u > 0 {
17449 col_off_u + count < plane_bw_unit
17450 } else if col_off_u + count < plane_bw_unit {
17451 true
17452 } else {
17453 blk
17454 }
17455 }
17456 fn libaom_bl(
17457 bw: usize,
17458 bh: usize,
17459 col_off: usize,
17460 row_off: usize,
17461 tx: usize,
17462 blk: bool,
17463 ) -> bool {
17464 let (plane_bh_unit, count) = (bh / 4, tx / 4);
17465 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
17466 let _ = bw;
17467 if col_off_u > 0 {
17468 false
17469 } else if row_off_u + count < plane_bh_unit {
17470 true
17471 } else {
17472 blk
17473 }
17474 }
17475 for &(bw, bh) in &[
17476 (8, 8),
17477 (16, 16),
17478 (32, 32),
17479 (64, 64),
17480 (16, 8),
17481 (8, 16),
17482 (32, 16),
17483 (16, 32),
17484 (64, 32),
17485 (32, 64),
17486 ] {
17487 for &tx in &[4usize, 8, 16, 32] {
17488 if tx > bw.min(bh) {
17489 continue;
17490 }
17491 for row_off in (0..bh).step_by(tx) {
17492 for col_off in (0..bw).step_by(tx) {
17493 for &blk in &[
17494 Reach {
17495 above_right: false,
17496 below_left: false,
17497 },
17498 Reach {
17499 above_right: true,
17500 below_left: true,
17501 },
17502 ] {
17503 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
17504 assert_eq!(
17505 got.above_right,
17506 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
17507 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
17508 );
17509 assert_eq!(
17510 got.below_left,
17511 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
17512 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
17513 );
17514 }
17515 }
17516 }
17517 }
17518 }
17519 }
17520
17521 #[test]
17522 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
17523 let fctx = &crate::decode::FrameCtx::for_encoder();
17524 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
17525 // Interior superblock, so neither the frame edge nor the col == 0 /
17526 // last-row early returns answer instead of the table.
17527 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
17528 let mut flipped = 0;
17529 for row in 0..8 {
17530 for col in 1..8 {
17531 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
17532 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
17533 let vert = {
17534 let _guard = Reach::vert_ab_partition();
17535 Reach::of(8, x, y, width, height, fctx).below_left
17536 };
17537 // The TR square of a VERT_A/_B sits at an even row, odd
17538 // column; every other slot must be untouched by the guard.
17539 if row % 2 == 0 && col % 2 == 1 {
17540 assert!(!raster, "raster below_left at row={row} col={col}");
17541 assert!(vert, "vert below_left at row={row} col={col}");
17542 flipped += 1;
17543 } else {
17544 assert_eq!(raster, vert, "guard moved row={row} col={col}");
17545 }
17546 }
17547 }
17548 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
17549 // The guard is scoped: it must not leak past its own block.
17550 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
17551 }
17552
17553 /// An odd width or height is refused by name, not by however the padder
17554 /// or the block coder would happen to fail on it.
17555 #[test]
17556 fn odd_dimensions_are_refused() {
17557 let _knobs = crate::speed::knob_read();
17558 let fctx = &crate::decode::FrameCtx::for_encoder();
17559 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
17560 let picture = Picture::grey(width, height);
17561 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
17562 .expect_err(&format!("{width}x{height} is odd and must be refused"));
17563 assert!(
17564 err.to_string().contains("even"),
17565 "{width}x{height}: error was {err}"
17566 );
17567 }
17568 }
17569
17570 /// A sequence at a size that is not a multiple of the block grid decodes
17571 /// to the right frame count and the right size for every frame,
17572 /// including the inter frames whose reference is the previous frame's
17573 /// own (padded) reconstruction.
17574 #[test]
17575 fn sequence_round_trips_at_a_non_multiple_size() {
17576 let _knobs = crate::speed::knob_read();
17577 let fctx = &crate::decode::FrameCtx::for_encoder();
17578 if !have_ffmpeg() {
17579 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
17580 return;
17581 }
17582 let (width, height) = (160usize, 96usize);
17583 let pictures: Vec<Picture> = (0..3)
17584 .map(|i| panned_test_card(width, height, i * 3))
17585 .collect();
17586 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17587 assert_eq!(encoded.frames.len(), 3);
17588 for (i, frame) in encoded.frames.iter().enumerate() {
17589 assert_eq!(
17590 (frame.reconstruction.width, frame.reconstruction.height),
17591 (width, height),
17592 "frame {i}: reconstruction size"
17593 );
17594 }
17595 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
17596 // true (display) size a sequence's frames share, not the padded one.
17597 assert_eq!(
17598 ffprobe_size(&encoded.stream),
17599 (width as u32, height as u32),
17600 "sequence: ffprobe reports the true (display) size"
17601 );
17602 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
17603 assert_eq!(decoded.len(), 3, "decoded frame count");
17604 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17605 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17606 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17607 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17608 }
17609 }
17610
17611 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
17612 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
17613 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
17614 /// `pos + side_mi / 2 < bound` boundary), which is the case
17615 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
17616 /// refusing. A key frame alone already covered this size; this proves the
17617 /// inter tile writer's parity with it across a real multi-frame export.
17618 #[test]
17619 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
17620 let _knobs = crate::speed::knob_read();
17621 let fctx = &crate::decode::FrameCtx::for_encoder();
17622 if !have_ffmpeg() {
17623 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
17624 return;
17625 }
17626 let (width, height) = (1280usize, 720usize);
17627 let pictures: Vec<Picture> = (0..3)
17628 .map(|i| panned_test_card(width, height, i * 3))
17629 .collect();
17630 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17631 assert_eq!(encoded.frames.len(), 3);
17632 for (i, frame) in encoded.frames.iter().enumerate() {
17633 assert_eq!(
17634 (frame.reconstruction.width, frame.reconstruction.height),
17635 (width, height),
17636 "frame {i}: reconstruction size"
17637 );
17638 }
17639 assert_eq!(
17640 ffprobe_size(&encoded.stream),
17641 (width as u32, height as u32),
17642 "ffprobe reports the true (display) 1280x720 size"
17643 );
17644 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
17645 assert_eq!(decoded.len(), 3, "decoded frame count");
17646 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17647 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17648 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17649 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17650 }
17651 }
17652
17653 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
17654 /// leaf's own half (`has_half` at the SUB level) itself straddles the
17655 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
17656 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
17657 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
17658 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
17659 /// straddling-16x16 branch), so an inter frame no longer refuses this
17660 /// size either. This only proves the encoder does not error out -- see
17661 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
17662 /// decoder-clean proof (a 3-frame sequence, so the inter path is
17663 /// actually exercised).
17664 #[test]
17665 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
17666 let _knobs = crate::speed::knob_read();
17667 let fctx = &crate::decode::FrameCtx::for_encoder();
17668 let (width, height) = (640usize, 360usize);
17669 let picture = Picture::grey(width, height);
17670 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
17671 .expect("key frame now codes the mod-32==8 straddle");
17672
17673 // `encode_sequence`'s second frame is the inter path: same size, now
17674 // wired the same way.
17675 let pictures = vec![picture.clone(), picture];
17676 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
17677 .expect("inter frame now codes the mod-32==8 straddle too");
17678 }
17679
17680 /// The r15 fix at production size: three 640x360 key frames (inter is
17681 /// still refused at this size, per the test above, so this stands in for
17682 /// the charter's "3-frame sequence" using three independent key frames of
17683 /// shifted content), each proven decoder-clean through ffmpeg rather than
17684 /// only encoder-clean.
17685 #[test]
17686 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
17687 let _knobs = crate::speed::knob_read();
17688 let fctx = &crate::decode::FrameCtx::for_encoder();
17689 if !have_ffmpeg() {
17690 eprintln!(
17691 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
17692 no ffmpeg"
17693 );
17694 return;
17695 }
17696 let (width, height) = (640usize, 360usize);
17697 for shift in [0i64, 7, 19] {
17698 let picture = panned_test_card(width, height, shift);
17699 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17700 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17701 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
17702 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
17703 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
17704 }
17705 }
17706
17707 /// The 640x360 straddle class, but through the inter path an actual
17708 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
17709 /// proves the leaf-8 inter stream this round wires up is not just
17710 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
17711 #[test]
17712 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
17713 let _knobs = crate::speed::knob_read();
17714 let fctx = &crate::decode::FrameCtx::for_encoder();
17715 if !have_ffmpeg() {
17716 eprintln!(
17717 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
17718 );
17719 return;
17720 }
17721 let (width, height) = (640usize, 360usize);
17722 let pictures: Vec<Picture> = (0..4)
17723 .map(|i| panned_test_card(width, height, i * 3))
17724 .collect();
17725 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17726 assert_eq!(encoded.frames.len(), 4);
17727 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
17728 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
17729 }
17730 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
17731 assert_eq!(decoded.len(), 4, "decoded frame count");
17732 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
17733 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
17734 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
17735 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
17736 }
17737 }
17738
17739 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
17740 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
17741 let out = Command::new("ffmpeg")
17742 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
17743 .args(["-vf", &format!("scale={width}:{height}")])
17744 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
17745 .output()
17746 .expect("ffmpeg failed to run");
17747 assert!(
17748 out.status.success(),
17749 "ffmpeg: {}",
17750 String::from_utf8_lossy(&out.stderr)
17751 );
17752 let (luma, chroma) = (width * height, width * height / 4);
17753 assert_eq!(
17754 out.stdout.len(),
17755 luma + 2 * chroma,
17756 "expected one 4:2:0 frame"
17757 );
17758 Picture {
17759 width,
17760 height,
17761 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
17762 u: out.stdout[luma..luma + chroma]
17763 .iter()
17764 .map(|&v| u16::from(v))
17765 .collect(),
17766 v: out.stdout[luma + chroma..]
17767 .iter()
17768 .map(|&v| u16::from(v))
17769 .collect(),
17770 }
17771 }
17772
17773 /// Prints what the mode search saves over DC prediction alone, for the
17774 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
17775 /// weight the search puts on rate can be swept.
17776 #[test]
17777 #[ignore = "a sweep, not a gate"]
17778 fn probe_lambda() {
17779 let _knobs = crate::speed::knob_read();
17780 let fctx = &crate::decode::FrameCtx::for_encoder();
17781 let mut pictures = vec![
17782 ("test card".to_string(), test_card(160, 96)),
17783 ("stripes".to_string(), stripes(160, 96, true)),
17784 ];
17785 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
17786 for entry in clips.split(':').filter(|e| !e.is_empty()) {
17787 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
17788 let name = path.rsplit('/').next().unwrap_or(path).to_string();
17789 pictures.push((name, clip_frame(path, skip, 640, 352)));
17790 }
17791 }
17792 for (name, picture) in pictures {
17793 let dc = ladder(&picture, &[DC_PRED], fctx);
17794 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
17795 println!(
17796 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
17797 bd_rate(&dc, &searched) * 100.0,
17798 10f64.powf(searched[1].1),
17799 searched[1].0,
17800 10f64.powf(dc[1].1),
17801 dc[1].0,
17802 );
17803 }
17804 }
17805
17806 /// Prints the whole mode-search ladder, so two builds of the search can be
17807 /// compared against each other rather than each against its own baseline.
17808 #[test]
17809 #[ignore = "a sweep, not a gate"]
17810 fn probe_ladder() {
17811 let _knobs = crate::speed::knob_read();
17812 let fctx = &crate::decode::FrameCtx::for_encoder();
17813 for (name, picture) in sweep_pictures() {
17814 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
17815 let points = all
17816 .iter()
17817 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
17818 .collect::<Vec<_>>()
17819 .join(" ");
17820 println!("ladder {name}: {points}");
17821 }
17822 }
17823
17824 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
17825 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
17826 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
17827 #[test]
17828 // ROBUST-RED on this tree, and the red is in the MEASURE, not the codec:
17829 // the `stripes` picture codes LOSSLESSLY at q110/90/70, so both ladders
17830 // come back as three identical `(inf, 1.8260748027008264)` points and
17831 // `bd_rate` has an empty trapezoid to integrate, which panics with
17832 // "the two ladders have to overlap in PSNR". Row 1 (`test card`) still
17833 // prints its number before the panic. Point `EC_AV1_CLIPS` at a real lossy
17834 // clip, or read only row 1.
17835 #[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"]
17836 fn probe_split() {
17837 let _knobs = crate::speed::knob_read();
17838 let fctx = &crate::decode::FrameCtx::for_encoder();
17839 for (name, picture) in sweep_pictures() {
17840 let ladder = |split: bool| {
17841 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
17842 .iter()
17843 .map(|&q| {
17844 let encoded = encode_key_frame_inner(
17845 &picture,
17846 q,
17847 0.5,
17848 &KEY_FRAME_MODES,
17849 split,
17850 (picture.width, picture.height),
17851 unspecified_color_config(),
17852 fctx,
17853 )
17854 .unwrap();
17855 (
17856 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
17857 (encoded.stream.len() as f64).log10(),
17858 )
17859 })
17860 .collect();
17861 points.sort_by(|a, b| a.0.total_cmp(&b.0));
17862 points
17863 };
17864 let (whole, split) = (ladder(false), ladder(true));
17865 let blocks = encode_key_frame_inner(
17866 &picture,
17867 90,
17868 0.5,
17869 &KEY_FRAME_MODES,
17870 true,
17871 (picture.width, picture.height),
17872 unspecified_color_config(),
17873 fctx,
17874 )
17875 .unwrap()
17876 .modes
17877 .len();
17878 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
17879 println!(
17880 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
17881 bd_rate(&whole, &split) * 100.0
17882 );
17883 }
17884 }
17885
17886 /// A striped picture, running one way or the other. The stripes are what
17887 /// separates a vertical predictor from a horizontal one: a mode search
17888 /// reading a transposed edge would pick the wrong one of the pair, which no
17889 /// symmetric picture would show.
17890 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
17891 let mut picture = Picture::grey(width, height);
17892 for y in 0..height {
17893 for x in 0..width {
17894 let along = if vertical { x } else { y };
17895 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
17896 }
17897 }
17898 picture
17899 }
17900
17901 /// Where two planes first disagree, and by how much: a mismatch reported as
17902 /// a position says which block and which sample of it went wrong, which a
17903 /// pair of thousand-sample arrays does not. A length difference counts as a
17904 /// disagreement: `zip` stops at the shorter plane, so a short one would
17905 /// otherwise compare exact over the prefix the two share.
17906 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
17907 if let Some(i) = ours.iter().zip(theirs).position(|(a, b)| a != b) {
17908 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
17909 return Some(format!(
17910 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
17911 i % width,
17912 i / width,
17913 ours[i],
17914 theirs[i]
17915 ));
17916 }
17917 if ours.len() != theirs.len() {
17918 return Some(format!(
17919 "no sample in the shared prefix differs, but ours is {} samples and theirs is {}",
17920 ours.len(),
17921 theirs.len()
17922 ));
17923 }
17924 None
17925 }
17926
17927 /// Every mode the encoder offers has to predict what the decoder predicts,
17928 /// not just the ones a particular picture happens to choose: each is forced
17929 /// over a whole picture and the reconstruction gated against ffmpeg.
17930 #[test]
17931 fn every_mode_decodes_to_what_the_encoder_predicted() {
17932 let _knobs = crate::speed::knob_write();
17933 let fctx = &crate::decode::FrameCtx::for_encoder();
17934 if !have_ffmpeg() {
17935 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
17936 return;
17937 }
17938 // A mode ablation measures the MODE search: a filter-intra block is
17939 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
17940 // "the encoder coded something else" check for a reason that is not
17941 // about the mode search at all.
17942 force_filter_intra(Some(false));
17943 // 128 wide is a whole number of superblocks and 160 is not: the last
17944 // superblock of a 160-wide row is half a one, whose blocks have no
17945 // above-right samples inside the frame at all.
17946 for (width, height) in [(128, 96), (160, 96)] {
17947 let picture = test_card(width, height);
17948 for mode in KEY_FRAME_MODES {
17949 let encoded =
17950 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx)
17951 .unwrap();
17952 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17953 for (plane, ours, theirs, stride) in [
17954 ("luma", &encoded.reconstruction.y, &decoded.y, width),
17955 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
17956 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
17957 ] {
17958 assert!(
17959 first_difference(ours, theirs, stride).is_none(),
17960 "{width}x{height} mode {mode}, {plane}: {}",
17961 first_difference(ours, theirs, stride).unwrap()
17962 );
17963 }
17964 assert!(
17965 encoded.modes.iter().all(|&m| m == mode),
17966 "mode {mode}: the encoder coded something else"
17967 );
17968 }
17969 }
17970 }
17971
17972 /// The search has to follow the picture: vertical stripes are cheapest
17973 /// predicted from the row above, horizontal ones from the column to the
17974 /// left. Reading the edges the other way round would swap the two answers
17975 /// while leaving every fidelity gate intact.
17976 #[test]
17977 fn the_search_picks_the_direction_the_picture_runs() {
17978 let _knobs = crate::speed::knob_write();
17979 let fctx = &crate::decode::FrameCtx::for_encoder();
17980 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
17981 // a filter-intra block is coded `DC_PRED` whatever mode the arm
17982 // offers, and these stripes are SCREEN content, where the filter arm
17983 // now searches its own transform depth (lane-fitu) and wins outright
17984 // -- which says nothing about the mode search this gate measures.
17985 force_filter_intra(Some(false));
17986 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
17987 let picture = stripes(128, 96, vertical);
17988 // Only the pair, because on stripes a third mode predicts exactly
17989 // what the right one of the pair does -- PAETH reads the corner and
17990 // the left column, which a striped picture makes equal -- and the
17991 // tie then goes to whichever is cheaper to name, which is not what
17992 // this gate is about.
17993 let encoded =
17994 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx)
17995 .unwrap();
17996 // The first block of the picture has neither neighbour, so it
17997 // cannot tell the modes apart; every other one can.
17998 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
17999 assert!(
18000 picked * 2 > encoded.modes.len() - 1,
18001 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
18002 encoded.modes.len() - 1,
18003 encoded.modes
18004 );
18005 }
18006 }
18007
18008 /// What the search is for: the same picture, at the same quantizer, coded
18009 /// smaller and more faithfully than DC alone can manage.
18010 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
18011 /// between the two rate-distortion curves in log-rate against PSNR, as a
18012 /// fraction of the reference's rate. Negative means the second curve costs
18013 /// less for the same picture.
18014 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
18015 let low = reference[0].0.max(other[0].0);
18016 let high = reference[reference.len() - 1]
18017 .0
18018 .min(other[other.len() - 1].0);
18019 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
18020 // the non-directional one on the synthetic diagonals -- every point
18021 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
18022 // to integrate over any more. A curve that dominates that way has
18023 // saved everything the measure can express (the
18024 // `instrument-at-bound` class: the answer is at the instrument's own
18025 // edge, not undefined), so name it rather than panicking; anything
18026 // less clean than strict dominance still is.
18027 if high <= low {
18028 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
18029 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
18030 let dominates =
18031 other[0].0 > reference[reference.len() - 1].0 && other_hi_rate <= ref_lo_rate;
18032 assert!(
18033 dominates,
18034 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
18035 );
18036 return -1.0;
18037 }
18038 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
18039 let i = curve
18040 .windows(2)
18041 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
18042 .unwrap_or(0);
18043 let (x0, y0) = curve[i];
18044 let (x1, y1) = curve[i + 1];
18045 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
18046 };
18047 let steps = 64;
18048 let mut area = 0.0;
18049 for step in 0..steps {
18050 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
18051 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
18052 }
18053 10f64.powf(area / f64::from(steps)) - 1.0
18054 }
18055
18056 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
18057 /// fidelity.
18058 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
18059 // A mode ablation measures the MODE search: the palette would code
18060 // these synthetic two-colour pictures losslessly under every arm and
18061 // leave nothing to compare (see [`force_screen`]).
18062 force_screen(Some(false));
18063 // Same reason, for the filter-intra candidate: it wins blocks under
18064 // BOTH arms of a mode ablation and so cancels the difference the
18065 // ablation measures (class `gate-recipe-confound`).
18066 force_filter_intra(Some(false));
18067 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
18068 .iter()
18069 .map(|&q| {
18070 let encoded =
18071 encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
18072 (
18073 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
18074 (encoded.stream.len() as f64).log10(),
18075 )
18076 })
18077 .collect();
18078 points.sort_by(|a, b| a.0.total_cmp(&b.0));
18079 points
18080 }
18081
18082 /// What the search is for: the same pictures cost less to code at the same
18083 /// fidelity than DC prediction alone can manage. A picture that runs one
18084 /// way saves far more than a busy one, which is the shape a working
18085 /// directional pair has.
18086 #[test]
18087 fn the_search_beats_dc_alone() {
18088 let _knobs = crate::speed::knob_read();
18089 let fctx = &crate::decode::FrameCtx::for_encoder();
18090 for (name, picture, want) in [
18091 ("test card", test_card(160, 96), -0.05),
18092 ("stripes", stripes(160, 96, true), -0.40),
18093 ] {
18094 let saved = bd_rate(
18095 &ladder(&picture, &[DC_PRED], fctx),
18096 &ladder(&picture, &NON_DIRECTIONAL, fctx),
18097 );
18098 assert!(
18099 saved < want,
18100 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
18101 saved * 100.0,
18102 -want * 100.0
18103 );
18104 }
18105 }
18106
18107 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
18108 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
18109 fn sweep_pictures() -> Vec<(String, Picture)> {
18110 let mut pictures = vec![
18111 ("test card".to_string(), test_card(160, 96)),
18112 ("stripes".to_string(), stripes(160, 96, true)),
18113 ("diagonal".to_string(), diagonal(160, 96, true)),
18114 ];
18115 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
18116 for entry in clips.split(':').filter(|e| !e.is_empty()) {
18117 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
18118 let name = path.rsplit('/').next().unwrap_or(path).to_string();
18119 pictures.push((name, clip_frame(path, skip, 640, 352)));
18120 }
18121 }
18122 pictures
18123 }
18124
18125 /// What the six directional modes are worth, per picture, at whatever
18126 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
18127 /// no further, and how often the search picks one.
18128 #[test]
18129 #[ignore = "a sweep, not a gate"]
18130 fn probe_directional() {
18131 let _knobs = crate::speed::knob_write();
18132 let fctx = &crate::decode::FrameCtx::for_encoder();
18133 for (name, picture) in sweep_pictures() {
18134 let dc = ladder(&picture, &[DC_PRED], fctx);
18135 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
18136 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
18137 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
18138 let directional = encoded
18139 .modes
18140 .iter()
18141 .filter(|&&m| (3..=8).contains(&m))
18142 .count();
18143 // A picture whose ladders sit at different fidelities altogether
18144 // has no BD-rate to report -- see the flat-sample-window class.
18145 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
18146 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
18147 };
18148 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
18149 if overlap(a, b) {
18150 format!("{:+.2}%", bd_rate(a, b) * 100.0)
18151 } else {
18152 "no overlap".to_string()
18153 }
18154 };
18155 println!(
18156 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
18157 against(&flat, &all),
18158 against(&dc, &all),
18159 encoded.modes.len(),
18160 );
18161 }
18162 }
18163
18164 /// A picture whose stripes run along a diagonal, one way or the other.
18165 /// This is to the directional modes what [`stripes`] is to the vertical and
18166 /// horizontal pair: a predictor that walked the edge in the wrong direction
18167 /// would answer the two pictures the same way round.
18168 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
18169 let mut picture = Picture::grey(width, height);
18170 for y in 0..height {
18171 for x in 0..width {
18172 let along = if down_right { x + height - y } else { x + y };
18173 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
18174 }
18175 }
18176 picture
18177 }
18178
18179 /// The mode picked by the most blocks of a picture, ignoring the first
18180 /// block, which has no neighbours to tell the modes apart with.
18181 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
18182 // A mode ablation measures the MODE search: the palette would code
18183 // these synthetic two-colour pictures losslessly under every arm and
18184 // leave nothing to compare (see [`force_screen`]).
18185 force_screen(Some(false));
18186 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
18187 let blocks = &encoded.modes[1..];
18188 let mut counts = [0usize; 13];
18189 for &mode in blocks {
18190 counts[usize::from(mode)] += 1;
18191 }
18192 let (mode, count) = counts
18193 .iter()
18194 .enumerate()
18195 .max_by_key(|&(_, count)| *count)
18196 .expect("thirteen modes");
18197 (mode as u8, *count, blocks.len())
18198 }
18199
18200 /// The search has to follow a diagonal the way it runs: stripes down and to
18201 /// the right are cheapest predicted at 135 degrees, stripes down and to the
18202 /// left at 45. A walk that stepped the wrong way along the edge, or read
18203 /// the above row where it should read the left column, would swap these.
18204 #[test]
18205 fn the_search_picks_the_diagonal_the_picture_runs() {
18206 let _knobs = crate::speed::knob_write();
18207 let fctx = &crate::decode::FrameCtx::for_encoder();
18208 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
18209 let picture = diagonal(160, 96, down_right);
18210 let (mode, count, blocks) = favourite_mode(&picture, fctx);
18211 assert_eq!(
18212 mode, want,
18213 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
18214 );
18215 }
18216 }
18217
18218 /// What the directional modes are for: a picture that runs along a diagonal
18219 /// costs far less to code with them than the seven that read only their own
18220 /// edges can manage, and a picture that runs no particular way costs no
18221 /// more. The second half is the one that bites: a mode set the search
18222 /// cannot price is a mode set that loses rate on content that does not want
18223 /// it, which is what costing the mode symbol is for.
18224 #[test]
18225 fn the_diagonals_beat_the_modes_that_read_no_further() {
18226 let _knobs = crate::speed::knob_read();
18227 let fctx = &crate::decode::FrameCtx::for_encoder();
18228 for (name, picture, want) in [
18229 ("down-right", diagonal(160, 96, true), -0.20),
18230 ("down-left", diagonal(160, 96, false), -0.20),
18231 ("test card", test_card(160, 96), 0.01),
18232 ] {
18233 let saved = bd_rate(
18234 &ladder(&picture, &NON_DIRECTIONAL, fctx),
18235 &ladder(&picture, &KEY_FRAME_MODES, fctx),
18236 );
18237 assert!(
18238 saved < want,
18239 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
18240 saved * 100.0,
18241 -want * 100.0
18242 );
18243 }
18244 }
18245
18246 /// A mode the encoder cannot predict must be refused rather than coded as
18247 /// something else, and a search with nothing to choose from likewise.
18248 #[test]
18249 fn a_mode_the_encoder_cannot_predict_is_refused() {
18250 let _knobs = crate::speed::knob_read();
18251 let fctx = &crate::decode::FrameCtx::for_encoder();
18252 let picture = test_card(64, 64);
18253 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
18254 .unwrap_err()
18255 .to_string();
18256 assert!(
18257 message.contains("intra mode 13"),
18258 "the refusal must name the mode, got {message}"
18259 );
18260 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
18261 }
18262
18263 /// The picture that comes back is the picture that went in, to within the
18264 /// quantizer. A prediction that read the wrong neighbours, or a block
18265 /// written into the wrong place, would still decode to what the encoder
18266 /// reconstructed — it is this gate that says the reconstruction is of the
18267 /// right picture.
18268 #[test]
18269 fn the_encoded_picture_is_the_one_that_went_in() {
18270 let _knobs = crate::speed::knob_read();
18271 let fctx = &crate::decode::FrameCtx::for_encoder();
18272 let picture = test_card(160, 96);
18273 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18274 let luma = psnr(&encoded.reconstruction.y, &picture.y);
18275 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
18276 for (plane, (got, want)) in [
18277 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
18278 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
18279 ]
18280 .iter()
18281 .enumerate()
18282 {
18283 let chroma = psnr(got, want);
18284 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
18285 }
18286 }
18287
18288 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
18289 /// does the opposite. Both are monotone, which is what a rate-distortion
18290 /// loop above this will assume.
18291 #[test]
18292 fn fidelity_and_rate_move_with_the_quantizer() {
18293 let _knobs = crate::speed::knob_read();
18294 let fctx = &crate::decode::FrameCtx::for_encoder();
18295 let picture = test_card(128, 128);
18296 let mut previous: Option<(usize, f64)> = None;
18297 for &q in &[70u8, 90, 110] {
18298 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18299 let quality = psnr(&encoded.reconstruction.y, &picture.y);
18300 if let Some((bytes, better)) = previous {
18301 assert!(
18302 encoded.stream.len() < bytes,
18303 "q {q}: {} bytes",
18304 encoded.stream.len()
18305 );
18306 assert!(quality < better, "q {q}: PSNR {quality}");
18307 }
18308 previous = Some((encoded.stream.len(), quality));
18309 }
18310
18311 // The deadzone half of this claim lives in
18312 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
18313 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
18314 // every zeroing, the deadzone no longer moves a coded stream
18315 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
18316 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
18317 // job, not a quantiser defect.
18318
18319 // Bytes must not jump up across a q-context boundary: a wrong CDF
18320 // table for the far side would show up as a rate discontinuity here,
18321 // even though a coarser quantizer always codes no more than a finer
18322 // one on the same picture.
18323 //
18324 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
18325 // chroma searches its own mode, a coarser quantizer can pick a
18326 // *different* uv_mode on a block whose modes now cost nearly the
18327 // same, and the search prices that symbol against the static default
18328 // CDF while the writer codes it against an adapted one -- 311 -> 319
18329 // bytes at q 120->121 on this picture. The table this gate is really
18330 // watching would move the rate by far more than the mode churn does.
18331 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
18332 // same block can also change transform DEPTH between two neighbouring
18333 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
18334 // symbol is priced off the static CDF row 0 for the same reason the
18335 // uv_mode one is.
18336 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
18337 // path is pricing through the adapting CDF state (what
18338 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
18339 // drift of), after which the exact bound comes back.
18340 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
18341 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx)
18342 .unwrap()
18343 .stream
18344 .len();
18345 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx)
18346 .unwrap()
18347 .stream
18348 .len();
18349 assert!(
18350 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
18351 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
18352 );
18353 }
18354 }
18355
18356 /// A flat picture is a flat stream: every block predicts its neighbours'
18357 /// average, which is the picture's own value, and codes nothing.
18358 #[test]
18359 fn a_flat_picture_costs_almost_nothing() {
18360 let _knobs = crate::speed::knob_read();
18361 let fctx = &crate::decode::FrameCtx::for_encoder();
18362 let mut picture = Picture::grey(128, 128);
18363 picture.y.fill(97);
18364 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18365 // The first block has no neighbour and predicts 128, so it carries a
18366 // DC; every block after it predicts 97 and carries nothing.
18367 assert!(
18368 encoded.stream.len() < 100,
18369 "{} bytes for a flat picture",
18370 encoded.stream.len()
18371 );
18372 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
18373 assert_eq!(s, 97, "sample {i} of a flat picture");
18374 }
18375 }
18376
18377 /// The sizes the encoder refuses, refused for a reason rather than by
18378 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
18379 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
18380 /// lands past the halfway point of whichever block it falls in, so
18381 /// `PARTITION_NONE` or a single gathered split flag still says everything
18382 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
18383 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
18384 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
18385 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
18386 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
18387 /// refusal here claimed otherwise and was wrong; see
18388 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
18389 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
18390 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
18391 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
18392 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
18393 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
18394 /// still refused is a malformed picture.
18395 #[test]
18396 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
18397 let _knobs = crate::speed::knob_read();
18398 let fctx = &crate::decode::FrameCtx::for_encoder();
18399 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
18400 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
18401 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
18402 .expect("36 luma columns still round up to an even MiCols");
18403
18404 let mut short = Picture::grey(64, 64);
18405 short.u.truncate(10);
18406 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
18407 }
18408
18409 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
18410 /// column half only (`has_half` false on cols, true on rows) -- exactly
18411 /// the single-axis straddle lane-av1-rect r7 wires through
18412 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
18413 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
18414 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
18415 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
18416 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
18417 /// `partition_context_lookup` entry this writer ever produces (no 4x4
18418 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
18419 /// leaf regardless of neighbour state -- our writer already agreed with
18420 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
18421 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
18422 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
18423 /// it does not regress the gate. r11 tell-for-tell traced two further,
18424 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
18425 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
18426 /// leaves, when the second leaf's true above (or left) neighbour is the
18427 /// first leaf itself -- fixed by threading the first leaf's mode into the
18428 /// second leaf's context, mi-precise, like `record_mi` already does for
18429 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
18430 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
18431 /// `reduced_tx_set` is false), but this crate's key frames set
18432 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
18433 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
18434 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
18435 /// symbol bits to desync everything after it. Fixed with a new
18436 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
18437 /// eset/size slot). Both fixes are provably correct against libaom
18438 /// source and each closed part of the gap (leaf0's `eob` went from a
18439 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
18440 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
18441 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
18442 /// (do not reuse r11's committed logs, which predate its own fixes) and
18443 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
18444 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
18445 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
18446 /// every other `write_block` caller at 16x16 and up already passes
18447 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
18448 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
18449 /// different amount of arithmetic range and derailed everything after
18450 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
18451 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
18452 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
18453 /// never updating those coarse arrays itself -- so a *second* straddling
18454 /// 16x16 quadrant stacked above or left of the first (never covered by
18455 /// r11's same-call `prev_leaf` override, which only threads state
18456 /// between the two leaves of one shared quadrant) read whatever stale
18457 /// mode sat in that slot before either leaf ran. Fixed by writing the
18458 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
18459 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
18460 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
18461 /// offset of a single unit; fixing (3)+(4) together still leaves a
18462 /// residual divergence one leaf further in -- the decoder now reads
18463 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
18464 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
18465 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
18466 /// desyncs the stream by exactly the width of one earlier symbol -- not
18467 /// yet isolated to a single named symbol. r15 found the last bug: the
18468 /// header fix from r14 explained the rng skew fully, and the remaining
18469 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
18470 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
18471 /// loop, once per leaf, so the first leaf's write clobbered the true
18472 /// external neighbour mode the second leaf of the *same* straddling
18473 /// quadrant still needed for its non-adjacency axis (a column-straddle
18474 /// case: two leaves share one `outer_at` column index, so leaf 1's
18475 /// write to `left_mode[r]` overwrote the real western neighbour before
18476 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
18477 /// doing it once, after the whole leaf loop, from the last (bottom/
18478 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
18479 #[test]
18480 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
18481 let _knobs = crate::speed::knob_read();
18482 let fctx = &crate::decode::FrameCtx::for_encoder();
18483 if !have_ffmpeg() {
18484 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
18485 return;
18486 }
18487 let (width, height) = (40usize, 32usize);
18488 let picture = test_card(width, height);
18489 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18490 assert_eq!(
18491 (encoded.reconstruction.width, encoded.reconstruction.height),
18492 (width, height)
18493 );
18494 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
18495 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
18496 }
18497 let decoded = ffmpeg_decode(&encoded.stream, width, height);
18498 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
18499 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
18500 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
18501 }
18502
18503 /// A frame of real video, rather than a picture built to be easy.
18504 ///
18505 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
18506 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
18507 /// encoder's reconstruction has to survive the same equality gate as the
18508 /// synthetic pictures — real video reaches contexts a test card does not.
18509 #[test]
18510 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
18511 let _knobs = crate::speed::knob_read();
18512 let fctx = &crate::decode::FrameCtx::for_encoder();
18513 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
18514 eprintln!(
18515 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
18516 set EC_AV1_CLIP to a clip"
18517 );
18518 return;
18519 };
18520 if !have_ffmpeg() {
18521 eprintln!(
18522 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
18523 );
18524 return;
18525 }
18526 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
18527 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
18528 // test quick while still spanning many superblocks.
18529 let (width, height) = (640usize, 352usize);
18530 let picture = clip_frame(&clip, &skip, width, height);
18531
18532 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18533 let decoded = ffmpeg_decode(&encoded.stream, width, height);
18534 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
18535 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
18536 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
18537 eprintln!(
18538 "{} bytes, luma PSNR {:.2} dB",
18539 encoded.stream.len(),
18540 psnr(&decoded.y, &picture.y)
18541 );
18542 }
18543
18544 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
18545 /// sequence of these is a translation a motion search can actually find
18546 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
18547 /// inter frame's rate against the key frame's is measuring the same
18548 /// picture moving, not two different pictures.
18549 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
18550 let mut picture = Picture::grey(width, height);
18551 for y in 0..height {
18552 for x in 0..width {
18553 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
18554 let gradient = sx * 200.0 / width as f64;
18555 let ripple = 30.0
18556 * (sx * std::f64::consts::PI / 23.0).sin()
18557 * (y as f64 * std::f64::consts::PI / 37.0).cos();
18558 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
18559 40.0
18560 } else {
18561 0.0
18562 };
18563 picture.y[y * width + x] =
18564 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
18565 }
18566 }
18567 for y in 0..height / 2 {
18568 for x in 0..width / 2 {
18569 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
18570 let i = y * width / 2 + x;
18571 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
18572 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
18573 }
18574 }
18575 picture
18576 }
18577
18578 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
18579 fn ffmpeg_decode_sequence(
18580 stream: &[u8],
18581 width: usize,
18582 height: usize,
18583 frames: usize,
18584 ) -> Vec<Picture> {
18585 let out = run_with_stdin(
18586 Command::new("ffmpeg").args([
18587 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
18588 ]),
18589 stream,
18590 );
18591 assert!(
18592 out.status.success(),
18593 "ffmpeg refused the stream: {}",
18594 String::from_utf8_lossy(&out.stderr)
18595 );
18596 let (luma, chroma) = (width * height, width * height / 4);
18597 let frame_bytes = luma + 2 * chroma;
18598 assert_eq!(
18599 out.stdout.len(),
18600 frame_bytes * frames,
18601 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
18602 String::from_utf8_lossy(&out.stderr)
18603 );
18604 (0..frames)
18605 .map(|i| {
18606 let base = i * frame_bytes;
18607 Picture {
18608 width,
18609 height,
18610 y: out.stdout[base..base + luma]
18611 .iter()
18612 .map(|&v| u16::from(v))
18613 .collect(),
18614 u: out.stdout[base + luma..base + luma + chroma]
18615 .iter()
18616 .map(|&v| u16::from(v))
18617 .collect(),
18618 v: out.stdout[base + luma + chroma..base + frame_bytes]
18619 .iter()
18620 .map(|&v| u16::from(v))
18621 .collect(),
18622 }
18623 })
18624 .collect()
18625 }
18626
18627 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
18628 /// makes for a key frame, extended down the reference chain: each inter
18629 /// frame's reconstruction predicts from the previous frame's own decoded
18630 /// reconstruction, so a single sample of drift anywhere would propagate
18631 /// into every frame after it -- which is why every frame is checked, not
18632 /// just the last one, and why this is an equality and not a tolerance.
18633 #[test]
18634 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
18635 let _knobs = crate::speed::knob_read();
18636 let fctx = &crate::decode::FrameCtx::for_encoder();
18637 if !have_ffmpeg() {
18638 eprintln!(
18639 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
18640 );
18641 return;
18642 }
18643 let (width, height) = (128usize, 64usize);
18644 let pictures: Vec<Picture> = (0..5)
18645 .map(|i| panned_test_card(width, height, i * 3))
18646 .collect();
18647 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18648 assert_eq!(encoded.frames.len(), 5);
18649
18650 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
18651 assert_eq!(
18652 encoded.frames.len(),
18653 decoded.len(),
18654 "frame count: ours vs ffmpeg"
18655 );
18656 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18657 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
18658 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
18659 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
18660 }
18661
18662 eprintln!("frame bytes luma PSNR (dB) inter share");
18663 for (i, frame) in encoded.frames.iter().enumerate() {
18664 eprintln!(
18665 "{i:5} {:5} {:14.2} {:11.2}",
18666 frame.stream.len(),
18667 psnr(&frame.reconstruction.y, &pictures[i].y),
18668 frame.inter_block_share
18669 );
18670 }
18671 }
18672
18673 /// The same sequence through OUR OWN decoder, sample-exact against the
18674 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
18675 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
18676 /// divergence point at all, while our decoder can be traced symbol by
18677 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
18678 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
18679 /// names the first differing frame, plane and position.
18680 /// lane-sb128b: the writer used to price a `NEWMV` residual against
18681 /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
18682 /// write-time stack could not carry, while the drl symbols signalled the
18683 /// clamped index -- so the decoder derived a DIFFERENT motion vector with
18684 /// the entropy stream still in sync, and the drift only surfaced frames
18685 /// later as a drl desync (on film B, as the encoder's own trial decode
18686 /// refusing a reference slot).
18687 ///
18688 /// The clamp needs a stack that shrinks between search and write, which
18689 /// is what a 128x128 superblock's visit order does; the counter is the
18690 /// point (class `gate-blind-to-feature`): a green round trip on a clip
18691 /// that never clamps proves nothing.
18692 ///
18693 /// `#[ignore]`: [`force_sb128`] moves a process-global.
18694 ///
18695 /// The drl-clamp cell this gate's counter used to gate is no longer gated
18696 /// here: it is covered by
18697 /// [`every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`],
18698 /// which enumerates the pricer's offer set against the writer's rule (see
18699 /// its doc). The clamp needs a stack that shrinks between search and
18700 /// write, which is what a 128x128 superblock's visit order would do -- but
18701 /// the pricer never offers an index this tree's `write_drl_idx` cannot
18702 /// signal, so no clip can provoke it (lane-av1recipehunt: 153 attempts, 0;
18703 /// widening the pricer to `0..5` fires the counter immediately, reverting
18704 /// silences it). `drl_clamp_hits` is kept as the tripwire for that fix.
18705
18706 /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
18707 /// and one motion vector where the four 64x64 roots below spend four of
18708 /// each (cen3's L1). The counter is the gate on the fixture (class
18709 /// `gate-blind-to-feature`): a green round trip on a clip that never
18710 /// codes a 128x128 block proves nothing. RED before the search existed
18711 /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
18712 /// root by construction).
18713 ///
18714 /// Both readers: our own decoder sample-exact against the encoder's
18715 /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
18716 /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
18717 ///
18718 /// `#[ignore]`: [`force_sb128`] moves a process-global.
18719 ///
18720 /// cargo test -p ec-av1 --release --lib -- --ignored \
18721 /// a_128_superblock_clip_whose_root_search --nocapture
18722 #[test]
18723 #[ignore = "sets the process-global superblock size: run it alone"]
18724 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
18725 let _knobs = crate::speed::knob_write();
18726 if !have_ffmpeg() {
18727 eprintln!("SKIP: no ffmpeg");
18728 return;
18729 }
18730 force_sb128(true);
18731 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
18732 std::fs::create_dir_all(&dir).unwrap();
18733 let clip = dir.join("smpte-1280x768.y4m");
18734 // A slow horizontal pan over a still pattern: whole 128x128 regions
18735 // share one motion vector, which is exactly what a 128 root can code
18736 // as one block and four 64 roots cannot.
18737 let ok = Command::new("ffmpeg")
18738 .args(["-v", "error", "-y", "-f", "lavfi"])
18739 .args(["-i", "smptebars=size=1600x768:rate=24"])
18740 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
18741 .args(["-pix_fmt", "yuv420p"])
18742 .arg(&clip)
18743 .status()
18744 .expect("ffmpeg failed to run")
18745 .success();
18746 assert!(ok, "ffmpeg could not write the synthetic clip");
18747 let (width, height) = (1280usize, 768usize);
18748 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
18749 let _ = take_b128_none_hits();
18750 let _ = crate::tile::take_sb128_none_hits();
18751 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
18752 let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
18753 eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
18754 assert!(
18755 coded > 0,
18756 "no 128x128 block was coded on this clip, so it cannot witness the root search",
18757 );
18758 assert_eq!(
18759 won, coded,
18760 "every 128x128 root the search took must be coded as one"
18761 );
18762 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18763 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18764 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18765 let recon = &frame.reconstruction;
18766 for (plane, got, want) in [
18767 ("luma", &dec.y, &recon.y),
18768 ("U", &dec.u, &recon.u),
18769 ("V", &dec.v, &recon.v),
18770 ] {
18771 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18772 assert_eq!(
18773 differ,
18774 0,
18775 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18776 own reconstruction",
18777 got.len()
18778 );
18779 assert_eq!(
18780 got.len(),
18781 want.len(),
18782 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
18783 got.len(),
18784 want.len()
18785 );
18786 }
18787 }
18788 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18789 assert_eq!(
18790 encoded.frames.len(),
18791 ff.len(),
18792 "frame count: ours vs ffmpeg"
18793 );
18794 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18795 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
18796 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
18797 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
18798 }
18799 }
18800
18801 /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
18802 /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
18803 /// same pan the skip-only witness above uses, with the arm FORCED
18804 /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
18805 /// about once per frame, which witnesses the shape but not every context
18806 /// it reads, and forcing codes all 420 roots of the clip through it. RED
18807 /// before this lane by construction (`write_inter_block_128` refused
18808 /// every non-skip 128 block, so no such block existed to decode), and RED
18809 /// again on the first draft of the writer, whose neighbour band recorded
18810 /// `skip = true` for a block that carries a residual -- the next root's
18811 /// `skip` symbol then took CDF row 1 where the reader takes row 0.
18812 ///
18813 /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces
18814 /// the skip arm's cost unconditionally (that is what makes the writer see
18815 /// the residual), and the cost model moved under it since lane-b128r --
18816 /// lane-rectdq made every non-skipped root pay its delta_q group and the
18817 /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root
18818 /// lost its partition at ALL 420 roots and the writer coded none. q=60
18819 /// puts 52 written blocks back on this clip; the `coded > 0` assert below
18820 /// is the guard that catches the next such drift.
18821 ///
18822 /// cargo test -p ec-av1 --release --lib -- --ignored \
18823 /// a_128_root_block_with_a_real_residual --nocapture
18824 #[test]
18825 #[ignore = "sets the process-global superblock size: run it alone"]
18826 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
18827 let _knobs = crate::speed::knob_write();
18828 if !have_ffmpeg() {
18829 eprintln!("SKIP: no ffmpeg");
18830 return;
18831 }
18832 force_sb128(true);
18833 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
18834 std::fs::create_dir_all(&dir).unwrap();
18835 let clip = dir.join("smpte-pan-1280x768.y4m");
18836 let ok = Command::new("ffmpeg")
18837 .args(["-v", "error", "-y", "-f", "lavfi"])
18838 .args(["-i", "smptebars=size=1600x768:rate=24"])
18839 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
18840 .args(["-pix_fmt", "yuv420p"])
18841 .arg(&clip)
18842 .status()
18843 .expect("ffmpeg failed to run")
18844 .success();
18845 assert!(ok, "ffmpeg could not write the synthetic clip");
18846 let (width, height) = (1280usize, 768usize);
18847 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
18848 let _ = take_b128_residual_hits();
18849 let _ = crate::tile::take_sb128_residual_hits();
18850 force_b128_residual(true);
18851 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
18852 let (won, coded) = (
18853 take_b128_residual_hits(),
18854 crate::tile::take_sb128_residual_hits(),
18855 );
18856 eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
18857 assert!(
18858 coded > 0,
18859 "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
18860 );
18861 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18862 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18863 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18864 let recon = &frame.reconstruction;
18865 for (plane, got, want) in [
18866 ("luma", &dec.y, &recon.y),
18867 ("U", &dec.u, &recon.u),
18868 ("V", &dec.v, &recon.v),
18869 ] {
18870 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18871 assert_eq!(
18872 differ,
18873 0,
18874 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18875 own reconstruction",
18876 got.len()
18877 );
18878 assert_eq!(
18879 got.len(),
18880 want.len(),
18881 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
18882 got.len(),
18883 want.len()
18884 );
18885 }
18886 }
18887 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18888 assert_eq!(
18889 encoded.frames.len(),
18890 ff.len(),
18891 "frame count: ours vs ffmpeg"
18892 );
18893 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18894 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
18895 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
18896 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
18897 }
18898 }
18899
18900 /// lane-edge128: a 128x128 root block WITH a residual on a clip whose
18901 /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec
18902 /// 5.11.56) codes ONE literal for the block that first reaches a unit and
18903 /// copies it over every unit the block SPANS, so the four units of a 128
18904 /// root share one index -- while the encoder's CDEF search prices a
18905 /// preset per unit and its filter replay applied all four. Only the first
18906 /// reached the stream, so every decoder filtered the other three with the
18907 /// origin's strengths and the encoder's reconstruction (the picture the
18908 /// next frame predicts from) was a filter apart from what a decoder
18909 /// produces. RED before this lane on the native BD gate's bars 2160p row
18910 /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples,
18911 /// the rows above the 128 superblock's own edge); the stream itself was
18912 /// always right -- ffmpeg and our own decoder agreed with each other and
18913 /// disagreed with the encoder.
18914 ///
18915 /// `take_cdef_covered_units` is the gate on the fixture (class
18916 /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair
18917 /// for the whole frame codes no literal at all and witnesses nothing.
18918 ///
18919 /// cargo test -p ec-av1 --release --lib -- --ignored \
18920 /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture
18921 #[test]
18922 #[ignore = "sets the process-global superblock size: run it alone"]
18923 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
18924 let _knobs = crate::speed::knob_write();
18925 if !have_ffmpeg() {
18926 eprintln!("SKIP: no ffmpeg");
18927 return;
18928 }
18929 force_sb128(true);
18930 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
18931 std::fs::create_dir_all(&dir).unwrap();
18932 let clip = dir.join("testsrc2-1280x768.y4m");
18933 // Detailed synthetic content: its CDEF search spends more than one
18934 // strength pair, which is what puts a `cdef_idx` literal in the tile.
18935 let ok = Command::new("ffmpeg")
18936 .args(["-v", "error", "-y", "-f", "lavfi"])
18937 .args(["-i", "testsrc2=size=1280x768:rate=24"])
18938 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
18939 .arg(&clip)
18940 .status()
18941 .expect("ffmpeg failed to run")
18942 .success();
18943 assert!(ok, "ffmpeg could not write the synthetic clip");
18944 let (width, height) = (1280usize, 768usize);
18945 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
18946 force_b128_root(true);
18947 force_b128_residual(true);
18948 let _ = crate::tile::take_sb128_residual_hits();
18949 let _ = crate::filter_search::take_cdef_covered_units();
18950 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
18951 let coded = crate::tile::take_sb128_residual_hits();
18952 let covered = crate::filter_search::take_cdef_covered_units();
18953 eprintln!(
18954 "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
18955 another unit's literal: {covered}"
18956 );
18957 assert!(
18958 coded > 0,
18959 "no 128x128 block carried a residual on this clip"
18960 );
18961 assert!(
18962 covered > 0,
18963 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
18964 cannot witness the rule",
18965 );
18966 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18967 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18968 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18969 for (plane, got, want) in [
18970 ("luma", &dec.y, &frame.reconstruction.y),
18971 ("U", &dec.u, &frame.reconstruction.u),
18972 ("V", &dec.v, &frame.reconstruction.v),
18973 ] {
18974 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18975 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
18976 assert_eq!(
18977 got.len(),
18978 want.len(),
18979 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
18980 got.len(),
18981 want.len()
18982 );
18983 }
18984 }
18985 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18986 assert_eq!(
18987 encoded.frames.len(),
18988 ff.len(),
18989 "frame count: ours vs ffmpeg"
18990 );
18991 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18992 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
18993 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
18994 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
18995 }
18996 }
18997
18998 /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
18999 /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
19000 /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
19001 /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
19002 /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
19003 /// rect partition with [`force_b128_rect`]) so every inter root of the
19004 /// clip goes through it; the `coded > 0` assert is the guard that catches
19005 /// the next fixture drift (the whole-128 twin of this witness went RED
19006 /// twice that way).
19007 ///
19008 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
19009 /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
19010 #[test]
19011 #[ignore = "sets the process-global superblock size: run it alone"]
19012 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
19013 let _knobs = crate::speed::knob_write();
19014 if !have_ffmpeg() {
19015 eprintln!("SKIP: no ffmpeg");
19016 return;
19017 }
19018 force_sb128(true);
19019 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
19020 std::fs::create_dir_all(&dir).unwrap();
19021 let clip = dir.join("smpte-pan-1280x768.y4m");
19022 let ok = Command::new("ffmpeg")
19023 .args(["-v", "error", "-y", "-f", "lavfi"])
19024 .args(["-i", "smptebars=size=1600x768:rate=24"])
19025 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
19026 .args(["-pix_fmt", "yuv420p"])
19027 .arg(&clip)
19028 .status()
19029 .expect("ffmpeg failed to run")
19030 .success();
19031 assert!(ok, "ffmpeg could not write the synthetic clip");
19032 let (width, height) = (1280usize, 768usize);
19033 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
19034 force_b128_rect(1);
19035 force_b128_rectres(true);
19036 let _ = take_b128_rectres_hits();
19037 let _ = crate::tile::take_sb128_rectres_hits();
19038 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
19039 let (won, coded) = (
19040 take_b128_rectres_hits(),
19041 crate::tile::take_sb128_rectres_hits(),
19042 );
19043 eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
19044 assert!(
19045 coded > 0,
19046 "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
19047 );
19048 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19049 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19050 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19051 let recon = &frame.reconstruction;
19052 for (plane, got, want) in [
19053 ("luma", &dec.y, &recon.y),
19054 ("U", &dec.u, &recon.u),
19055 ("V", &dec.v, &recon.v),
19056 ] {
19057 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19058 assert_eq!(
19059 differ,
19060 0,
19061 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
19062 own reconstruction",
19063 got.len()
19064 );
19065 assert_eq!(
19066 got.len(),
19067 want.len(),
19068 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19069 got.len(),
19070 want.len()
19071 );
19072 }
19073 }
19074 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19075 assert_eq!(
19076 encoded.frames.len(),
19077 ff.len(),
19078 "frame count: ours vs ffmpeg"
19079 );
19080 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19081 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19082 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19083 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19084 }
19085 }
19086
19087 /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
19088 /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
19089 /// the two 64x64 squares through the one-chunk arm (the shape libaom's
19090 /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
19091 /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
19092 /// reference picture the GOP has not produced yet, which refuses before
19093 /// any AB root is coded.
19094 ///
19095 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
19096 /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
19097 #[test]
19098 #[ignore = "sets the process-global superblock size: run it alone"]
19099 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
19100 let _knobs = crate::speed::knob_write();
19101 if !have_ffmpeg() {
19102 eprintln!("SKIP: no ffmpeg");
19103 return;
19104 }
19105 force_sb128(true);
19106 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
19107 std::fs::create_dir_all(&dir).unwrap();
19108 let clip = dir.join("testsrc2-1280x768.y4m");
19109 let ok = Command::new("ffmpeg")
19110 .args(["-v", "error", "-y", "-f", "lavfi"])
19111 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19112 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19113 .arg(&clip)
19114 .status()
19115 .expect("ffmpeg failed to run")
19116 .success();
19117 assert!(ok, "ffmpeg could not write the synthetic clip");
19118 let (width, height) = (1280usize, 768usize);
19119 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19120 force_b128_ab(4);
19121 force_b128_rectres(true);
19122 let _ = take_b128_rectres_hits();
19123 let _ = crate::tile::take_sb128_rectres_hits();
19124 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
19125 let (won, coded) = (
19126 take_b128_rectres_hits(),
19127 crate::tile::take_sb128_rectres_hits(),
19128 );
19129 eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
19130 assert!(
19131 coded > 0,
19132 "no AB piece carried a residual on this clip, so it cannot witness the arm",
19133 );
19134 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19135 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19136 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19137 let recon = &frame.reconstruction;
19138 for (plane, got, want) in [
19139 ("luma", &dec.y, &recon.y),
19140 ("U", &dec.u, &recon.u),
19141 ("V", &dec.v, &recon.v),
19142 ] {
19143 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19144 assert_eq!(
19145 differ,
19146 0,
19147 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
19148 own reconstruction",
19149 got.len()
19150 );
19151 assert_eq!(
19152 got.len(),
19153 want.len(),
19154 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19155 got.len(),
19156 want.len()
19157 );
19158 }
19159 }
19160 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19161 assert_eq!(
19162 encoded.frames.len(),
19163 ff.len(),
19164 "frame count: ours vs ffmpeg"
19165 );
19166 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19167 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19168 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19169 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19170 }
19171 }
19172
19173 /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
19174 /// half WITH a residual under a clip whose CDEF search codes a
19175 /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
19176 /// and the decoder stamps BOTH units it spans with it, so the owner map
19177 /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
19178 /// collapse the pair -- exactly the bug class that broke bars 2160p at
19179 /// the whole-128 root. RED before this lane by construction: no rect
19180 /// piece could carry a residual, so no such literal existed.
19181 ///
19182 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
19183 /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
19184 #[test]
19185 #[ignore = "sets the process-global superblock size: run it alone"]
19186 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
19187 let _knobs = crate::speed::knob_write();
19188 if !have_ffmpeg() {
19189 eprintln!("SKIP: no ffmpeg");
19190 return;
19191 }
19192 force_sb128(true);
19193 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
19194 std::fs::create_dir_all(&dir).unwrap();
19195 let clip = dir.join("testsrc2-1280x768.y4m");
19196 // Detailed synthetic content: its CDEF search spends more than one
19197 // strength pair, which is what puts a `cdef_idx` literal in the tile.
19198 let ok = Command::new("ffmpeg")
19199 .args(["-v", "error", "-y", "-f", "lavfi"])
19200 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19201 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19202 .arg(&clip)
19203 .status()
19204 .expect("ffmpeg failed to run")
19205 .success();
19206 assert!(ok, "ffmpeg could not write the synthetic clip");
19207 let (width, height) = (1280usize, 768usize);
19208 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19209 force_b128_rect(1);
19210 force_b128_rectres(true);
19211 let _ = crate::tile::take_sb128_rectres_hits();
19212 let _ = crate::filter_search::take_cdef_covered_units();
19213 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
19214 let coded = crate::tile::take_sb128_rectres_hits();
19215 let covered = crate::filter_search::take_cdef_covered_units();
19216 eprintln!(
19217 "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
19218 another unit's literal: {covered}"
19219 );
19220 assert!(coded > 0, "no 128x64 half carried a residual on this clip");
19221 assert!(
19222 covered > 0,
19223 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
19224 cannot witness the rule",
19225 );
19226 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19227 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19228 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19229 for (plane, got, want) in [
19230 ("luma", &dec.y, &frame.reconstruction.y),
19231 ("U", &dec.u, &frame.reconstruction.u),
19232 ("V", &dec.v, &frame.reconstruction.v),
19233 ] {
19234 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19235 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
19236 assert_eq!(
19237 got.len(),
19238 want.len(),
19239 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19240 got.len(),
19241 want.len()
19242 );
19243 }
19244 }
19245 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19246 assert_eq!(
19247 encoded.frames.len(),
19248 ff.len(),
19249 "frame count: ours vs ffmpeg"
19250 );
19251 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19252 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19253 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19254 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19255 }
19256 }
19257
19258 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
19259 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
19260 /// `write_compound_block` chain every smaller compound block takes, at a
19261 /// window it had never been exercised at. RED before this lane: the
19262 /// search passed an empty compound list at the 128 root, so the count was
19263 /// 0 and no such block existed to decode.
19264 ///
19265 /// cargo test -p ec-av1 --release --lib -- --ignored \
19266 /// a_128_root_compound_block --nocapture
19267 #[test]
19268 #[ignore = "sets the process-global superblock size: run it alone"]
19269 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
19270 let _knobs = crate::speed::knob_write();
19271 if !have_ffmpeg() {
19272 eprintln!("SKIP: no ffmpeg");
19273 return;
19274 }
19275 force_sb128(true);
19276 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
19277 std::fs::create_dir_all(&dir).unwrap();
19278 let clip = dir.join("testsrc2-1280x768.y4m");
19279 // Moving objects that occlude each other: a pan is coded by one
19280 // reference outright, and a compound pair only pays where the two
19281 // references disagree.
19282 let ok = Command::new("ffmpeg")
19283 .args(["-v", "error", "-y", "-f", "lavfi"])
19284 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19285 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19286 .arg(&clip)
19287 .status()
19288 .expect("ffmpeg failed to run")
19289 .success();
19290 assert!(ok, "ffmpeg could not write the synthetic clip");
19291 let (width, height) = (1280usize, 768usize);
19292 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19293 // The compound candidate wins the 128 block's own search on this pan
19294 // but the root then loses to its four cells, so the root is forced
19295 // (the residual arm is left at its default, off).
19296 force_b128_root(true);
19297 let _ = take_b128_compound_hits();
19298 let _ = crate::tile::take_sb128_compound_hits();
19299 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19300 let (won, coded) = (
19301 take_b128_compound_hits(),
19302 crate::tile::take_sb128_compound_hits(),
19303 );
19304 eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
19305 assert!(
19306 coded > 0,
19307 "no compound 128x128 block was coded on this clip"
19308 );
19309 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19310 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19311 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19312 for (plane, got, want) in [
19313 ("luma", &dec.y, &frame.reconstruction.y),
19314 ("U", &dec.u, &frame.reconstruction.u),
19315 ("V", &dec.v, &frame.reconstruction.v),
19316 ] {
19317 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19318 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
19319 assert_eq!(
19320 got.len(),
19321 want.len(),
19322 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
19323 got.len(),
19324 want.len()
19325 );
19326 }
19327 }
19328 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19329 assert_eq!(
19330 encoded.frames.len(),
19331 ff.len(),
19332 "frame count: ours vs ffmpeg"
19333 );
19334 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19335 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
19336 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
19337 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
19338 }
19339 }
19340
19341 /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
19342 /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
19343 /// square. Three passes over one `testsrc2` clip:
19344 ///
19345 /// * HORZ forced at every root ([`force_b128_rect`]), so every context
19346 /// the 128x64 shape reads is exercised rather than the handful the RD
19347 /// would pick;
19348 /// * VERT forced the same way;
19349 /// * UNFORCED, which is the count the gate rows are read against -- the
19350 /// same clip with the RD free to choose among NONE / HORZ / VERT /
19351 /// four superblocks.
19352 ///
19353 /// Each pass is sample-exact against the encoder's own reconstruction
19354 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
19355 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
19356 /// before this lane by construction: `write_sb128_root` could only name
19357 /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
19358 ///
19359 /// cargo test -p ec-av1 --release --lib -- --ignored \
19360 /// a_128_root_horz_and_vert --nocapture
19361 #[test]
19362 #[ignore = "sets the process-global superblock size: run it alone"]
19363 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
19364 let _knobs = crate::speed::knob_write();
19365 if !have_ffmpeg() {
19366 eprintln!("SKIP: no ffmpeg");
19367 return;
19368 }
19369 force_sb128(true);
19370 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
19371 std::fs::create_dir_all(&dir).unwrap();
19372 let clip = dir.join("testsrc2-1280x768.y4m");
19373 let ok = Command::new("ffmpeg")
19374 .args(["-v", "error", "-y", "-f", "lavfi"])
19375 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19376 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19377 .arg(&clip)
19378 .status()
19379 .expect("ffmpeg failed to run")
19380 .success();
19381 assert!(ok, "ffmpeg could not write the synthetic clip");
19382 let (width, height) = (1280usize, 768usize);
19383 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19384 let mut unforced = (0usize, 0usize);
19385 for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
19386 force_b128_rect(force);
19387 let _ = take_b128_horz_hits();
19388 let _ = take_b128_vert_hits();
19389 let _ = crate::tile::take_sb128_horz_hits();
19390 let _ = crate::tile::take_sb128_vert_hits();
19391 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19392 let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
19393 let (coded_h, coded_v) = (
19394 crate::tile::take_sb128_horz_hits(),
19395 crate::tile::take_sb128_vert_hits(),
19396 );
19397 eprintln!(
19398 "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
19399 {coded_h} 128x64 + {coded_v} 64x128 halves"
19400 );
19401 match force {
19402 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
19403 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
19404 // The unforced count is REPORTED, not asserted: it is the
19405 // number the gate is read against, and a zero here would be
19406 // an RD result, not a defect (the forced passes already prove
19407 // the writer and the reader agree on the shape).
19408 _ => unforced = (won_h, won_v),
19409 }
19410 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19411 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
19412 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19413 for (plane, got, want) in [
19414 ("luma", &dec.y, &frame.reconstruction.y),
19415 ("U", &dec.u, &frame.reconstruction.u),
19416 ("V", &dec.v, &frame.reconstruction.v),
19417 ] {
19418 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19419 assert_eq!(
19420 differ, 0,
19421 "{label} frame {i}: {plane} -- {differ} samples differ"
19422 );
19423 assert_eq!(
19424 got.len(),
19425 want.len(),
19426 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
19427 got.len(),
19428 want.len()
19429 );
19430 }
19431 }
19432 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19433 assert_eq!(
19434 encoded.frames.len(),
19435 ff.len(),
19436 "{label}: frame count: ours vs ffmpeg"
19437 );
19438 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19439 assert_eq!(
19440 dec.y, frame.reconstruction.y,
19441 "{label} frame {i}: ffmpeg luma"
19442 );
19443 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
19444 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
19445 }
19446 }
19447 force_b128_rect(0);
19448 eprintln!(
19449 "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
19450 unforced.0, unforced.1
19451 );
19452 }
19453
19454 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
19455 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
19456 /// Five passes over the same `testsrc2` clip
19457 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
19458 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
19459 /// context and every visit order the shape reads is exercised rather than
19460 /// the handful the RD would pick, and then an UNFORCED pass whose
19461 /// per-shape count is REPORTED (it is the number the gate rows are read
19462 /// against).
19463 ///
19464 /// Each pass is sample-exact against the encoder's own reconstruction
19465 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
19466 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
19467 /// before this lane by construction: `write_sb128_root` could only name
19468 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
19469 ///
19470 /// cargo test -p ec-av1 --release --lib -- --ignored \
19471 /// a_128_root_ab_shapes --nocapture
19472 #[test]
19473 #[ignore = "sets the process-global superblock size: run it alone"]
19474 fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
19475 let _knobs = crate::speed::knob_write();
19476 if !have_ffmpeg() {
19477 eprintln!("SKIP: no ffmpeg");
19478 return;
19479 }
19480 force_sb128(true);
19481 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
19482 std::fs::create_dir_all(&dir).unwrap();
19483 let clip = dir.join("testsrc2-1280x768.y4m");
19484 let ok = Command::new("ffmpeg")
19485 .args(["-v", "error", "-y", "-f", "lavfi"])
19486 .args(["-i", "testsrc2=size=1280x768:rate=24"])
19487 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
19488 .arg(&clip)
19489 .status()
19490 .expect("ffmpeg failed to run")
19491 .success();
19492 assert!(ok, "ffmpeg could not write the synthetic clip");
19493 let (width, height) = (1280usize, 768usize);
19494 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
19495 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
19496 let mut unforced = [0usize; 4];
19497 for force in [4u8, 5, 6, 7, 0] {
19498 force_b128_ab(force);
19499 let label = if force == 0 {
19500 "unforced"
19501 } else {
19502 names[usize::from(force) - 4]
19503 };
19504 let _ = take_b128_ab_hits();
19505 let _ = crate::tile::take_sb128_ab_hits();
19506 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
19507 let won = take_b128_ab_hits();
19508 let coded = crate::tile::take_sb128_ab_hits();
19509 eprintln!(
19510 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
19511 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
19512 );
19513 if force == 0 {
19514 // The unforced counts are REPORTED, not asserted: a zero here
19515 // would be an RD result, not a defect (the four forced passes
19516 // already prove the writer and the reader agree on the shape).
19517 unforced = won;
19518 } else {
19519 let i = usize::from(force) - 4;
19520 assert!(
19521 coded[i] > 0,
19522 "no {label} root was coded with {label} forced"
19523 );
19524 }
19525 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19526 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
19527 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19528 for (plane, got, want) in [
19529 ("luma", &dec.y, &frame.reconstruction.y),
19530 ("U", &dec.u, &frame.reconstruction.u),
19531 ("V", &dec.v, &frame.reconstruction.v),
19532 ] {
19533 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
19534 assert_eq!(
19535 differ, 0,
19536 "{label} frame {i}: {plane} -- {differ} samples differ"
19537 );
19538 assert_eq!(
19539 got.len(),
19540 want.len(),
19541 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
19542 got.len(),
19543 want.len()
19544 );
19545 }
19546 }
19547 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
19548 assert_eq!(
19549 encoded.frames.len(),
19550 ff.len(),
19551 "{label}: frame count: ours vs ffmpeg"
19552 );
19553 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
19554 assert_eq!(
19555 dec.y, frame.reconstruction.y,
19556 "{label} frame {i}: ffmpeg luma"
19557 );
19558 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
19559 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
19560 }
19561 }
19562 force_b128_ab(0);
19563 eprintln!(
19564 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
19565 unforced[0], unforced[1], unforced[2], unforced[3],
19566 );
19567 }
19568
19569 #[test]
19570 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
19571 let _knobs = crate::speed::knob_read();
19572 let fctx = &crate::decode::FrameCtx::for_encoder();
19573 // 256x128, not the 128x64 this started at: once a leaf could search
19574 // its second reference (lane-av1comp4) the small card's every
19575 // eligible block went to a compound winner, which commits its flat
19576 // transform, and the split below stopped firing on content that
19577 // still splits at every larger size ([[gate-blind-to-feature]] --
19578 // the guard is right, the fixture had shrunk under it).
19579 let (width, height) = (256usize, 128usize);
19580 let pictures: Vec<Picture> = (0..5)
19581 .map(|i| panned_test_card(width, height, i * 3))
19582 .collect();
19583 let _ = take_inter_tx_split_hits();
19584 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19585 let raw = take_inter_tx_split_hits();
19586 // Summed over the four block classes the census keys on (leaf/32x32 x
19587 // single/compound): this assert is about the split firing at all.
19588 let split = [
19589 raw.iter().step_by(2).sum::<usize>(),
19590 raw.iter().skip(1).step_by(2).sum::<usize>(),
19591 ];
19592 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
19593 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
19594 // content splits -- a green round trip in which the split never fires
19595 // would prove only the flat path.
19596 if tx_select() && tx_select_inter() {
19597 assert!(split[1] > 0, "the inter var-tx split never fired");
19598 }
19599 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19600 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
19601 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
19602 let recon = &frame.reconstruction;
19603 for (plane, got, want, stride) in [
19604 ("luma", &dec.y, &recon.y, width),
19605 ("U", &dec.u, &recon.u, width / 2),
19606 ("V", &dec.v, &recon.v, width / 2),
19607 ] {
19608 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
19609 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
19610 panic!(
19611 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
19612 reconstruction {} ({} of {} samples differ)",
19613 at % stride,
19614 at / stride,
19615 got[at],
19616 want[at],
19617 got.iter().zip(want).filter(|(a, b)| a != b).count(),
19618 got.len(),
19619 );
19620 }
19621 }
19622 }
19623 }
19624
19625 /// The rate term the mode search ranks every decision by has to be the
19626 /// rate the writer then spends. The search prices a block's coefficients
19627 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
19628 /// against the default CDFs a tile starts from and the contexts of a
19629 /// block whose neighbours coded nothing -- while the tile writer codes
19630 /// them against a state that has been adapting all frame (the
19631 /// price-the-narrowing class). This measures that drift: the sum of what
19632 /// the search paid for the coefficients it kept, against the bytes the
19633 /// writer actually emitted for the whole tile (which also carries the
19634 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
19635 /// expected to be the larger of the two).
19636 #[test]
19637 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
19638 let _knobs = crate::speed::knob_read();
19639 let fctx = &crate::decode::FrameCtx::for_encoder();
19640 let (width, height) = (256usize, 128usize);
19641 let pictures: Vec<Picture> = (0..5)
19642 .map(|i| panned_test_card(width, height, i * 2))
19643 .collect();
19644 let _ = take_predicted_bits();
19645 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19646 let predicted = take_predicted_bits();
19647 assert_eq!(predicted.len(), encoded.frames.len());
19648
19649 eprintln!("frame predicted bits written bits drift");
19650 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
19651 // defect this gate exists to catch), a positive one is the written
19652 // side carrying syntax the coefficient sum leaves out -- and since
19653 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
19654 // on that side, so the two directions no longer share a bound.
19655 let mut worst_over: f64 = 0.0;
19656 let mut worst_under: f64 = 0.0;
19657 // The census is per CODED frame, so it is zipped in coding order --
19658 // which is not display order under a pyramid.
19659 let coded: Vec<&Encoded> = encoded
19660 .coding_order
19661 .iter()
19662 .map(|&i| &encoded.frames[i])
19663 .collect();
19664 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
19665 let written = frame.tile.len() as f64 * 8.0;
19666 let drift = (written - bits) / written;
19667 worst_over = worst_over.max(-drift);
19668 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
19669 // all (150-250 bits of tile, nearly all of it partition/mode/mv
19670 // syntax the coefficient sum never counts), so its ratio measures
19671 // that floor rather than any drift. Frames under 512 written bits
19672 // are left out of the under-price bound for that reason; the
19673 // over-price bound -- the defect direction, where the search pays
19674 // MORE than the writer -- still covers every frame.
19675 if written >= 512.0 {
19676 worst_under = worst_under.max(drift);
19677 }
19678 eprintln!(
19679 "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
19680 drift * 100.0
19681 );
19682 }
19683 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
19684 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
19685 // over-prices every frame but the last (its sum EXCLUDES the
19686 // partition/mode/skip/mv syntax the written side carries, so the true
19687 // coefficient over-price is larger still): the writer's CDFs adapt to
19688 // the content while the search's stay at the defaults. The bound is
19689 // set just above the worst measured point -- a widening drift is the
19690 // thing this gate exists to catch.
19691 assert!(
19692 worst_over <= 0.16,
19693 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
19694 worst_over * 100.0
19695 );
19696 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
19697 // the worst inter frame, where nearly every block now codes an MV
19698 // residual and a reference the coefficient sum never counts. Re-measured
19699 // at +29.6% once the encoder's grid published compound blocks properly
19700 // (compound share 8.8% -> 11.5%): a compound block carries a second
19701 // reference tree, a compound mode symbol and -- for the half-new modes
19702 // -- an MV residual, none of which the coefficient sum counts.
19703 // lane-av1txbits: pricing against the tables the frame's writer really
19704 // starts from collapses the over-price above to nothing, so the whole
19705 // remaining gap is the syntax the coefficient sum leaves out. That is
19706 // the default on a non-screen frame since lane-av1price2 (this
19707 // fixture is one), and it reads +32.6% here.
19708 // lane-av1obmc: every eligible single-reference inter block now also
19709 // carries a `motion_mode` symbol the coefficient sum never counts,
19710 // and an OBMC block carries the more expensive of the two values --
19711 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
19712 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
19713 // decisions, so this bound and the byte pins above FAIL BY DESIGN
19714 // under it; the default path (no motion_mode syntax at all) is the
19715 // one they are measured on.
19716 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
19717 // coding pyramid now, so the five frames are a key frame, a hidden
19718 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
19719 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
19720 // near-empty leaves below it. Both bounds stand where they were.
19721 // lane-av1rejudge: local warp is ON by default now, so every eligible
19722 // single-reference block carries that same `motion_mode` symbol (a
19723 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
19724 // +34.9% here, one point past the OBMC reading above. The bound moves
19725 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
19726 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
19727 // symbol and one or two magnitude symbols, none of which the
19728 // coefficient sum counts either -- +36.9% here against the same
19729 // fixture's +34.9% with `EC_AV1_CFL=0`.
19730 // ... and a directional block whose `angle_delta_y` is no longer
19731 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
19732 assert!(
19733 worst_under <= 0.40,
19734 "the writer spent {:.2}% more than the search priced -- more than \
19735 the mode/mv syntax outside the coefficient sum explains",
19736 worst_under * 100.0
19737 );
19738 }
19739
19740 /// The census behind step (1) of the pricer lane: for every transform
19741 /// block the writer really codes, what the search priced those levels at
19742 /// against what the writer spent on them, split by table set and non-zero
19743 /// count. One average hides the interesting part -- the classes the
19744 /// estimate is systematically wrong about (all-zero blocks, the
19745 /// one-coefficient blocks the inter search lives on) -- so the split is
19746 /// printed and only the total is asserted on.
19747 #[test]
19748 fn pricer_error_census_by_block_class() {
19749 let _knobs = crate::speed::knob_read();
19750 let fctx = &crate::decode::FrameCtx::for_encoder();
19751 let (width, height) = (256usize, 128usize);
19752 let pictures: Vec<Picture> = (0..5)
19753 .map(|i| panned_test_card(width, height, i * 2))
19754 .collect();
19755 crate::tile::pricer_census_on();
19756 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19757 let rows = crate::tile::take_pricer_census();
19758 assert!(!rows.is_empty(), "the census saw no transform block");
19759
19760 println!("| set | nz | blocks | priced bits | written bits | error |");
19761 println!("|---|---|---|---|---|---|");
19762 let (mut priced_all, mut written_all) = (0.0, 0.0);
19763 for ((set, bucket), (blocks, priced, written)) in &rows {
19764 priced_all += priced;
19765 written_all += written;
19766 println!(
19767 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
19768 crate::tile::census_bucket_label(*bucket),
19769 if *written > 0.0 {
19770 (priced - written) / written * 100.0
19771 } else {
19772 0.0
19773 }
19774 );
19775 }
19776 println!(
19777 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
19778 rows.values().map(|r| r.0).sum::<u64>(),
19779 (priced_all - written_all) / written_all * 100.0
19780 );
19781 assert!(written_all > 0.0);
19782 }
19783
19784 /// Step (2) of the pricer lane: the same census, but on the REAL clips
19785 /// the BD gate scores -- one film clip and the screen capture -- so the
19786 /// question the film/screen split raises can be answered from data. Real
19787 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
19788 /// the screen capture larger, and the census says why: on a screen
19789 /// capture the frame's own starting tables are the tables of a frame that
19790 /// coded PALETTE and long runs of zero blocks, so they are far from the
19791 /// tables the writer ends the frame with; the pricer error does not fall
19792 /// the way it does on film.
19793 ///
19794 /// Not a gate -- it prints. Run it once per mode:
19795 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
19796 /// --ignored pricer_error_census_on_clips --nocapture
19797 #[test]
19798 #[ignore = "reads the real library, needs ffmpeg"]
19799 fn pricer_error_census_on_clips() {
19800 let _knobs = crate::speed::knob_write();
19801 if !have_ffmpeg() {
19802 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
19803 return;
19804 }
19805 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first),
19806 // so this probe reads the same tree the preflight validates. Its
19807 // `assert!(!clips.is_empty())` below was already a hard failure, so no
19808 // skip shape changes here — only the root does.
19809 let fixtures = crate::library_fixture::root();
19810 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
19811 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
19812 if film.exists() {
19813 clips.push(("film 1080p".to_string(), film));
19814 }
19815 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
19816 && let Some(p) = manifest
19817 .lines()
19818 .skip(1)
19819 .filter_map(|l| l.split('\t').next())
19820 .find(|p| {
19821 p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
19822 })
19823 {
19824 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
19825 }
19826 assert!(!clips.is_empty(), "no source clip available");
19827 let (width, height, frames) = (640usize, 384usize, 6usize);
19828 for (name, path) in &clips {
19829 let fctx = &crate::decode::FrameCtx::for_encoder();
19830 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
19831 SCREEN_FRAMES.iter().for_each(|c| {
19832 c.store(0, std::sync::atomic::Ordering::Relaxed);
19833 });
19834 let _ = crate::tile::take_pricing_hits();
19835 crate::tile::pricer_census_on();
19836 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
19837 let rows = crate::tile::take_pricer_census();
19838 let (price_default, price_real) = crate::tile::take_pricing_hits();
19839 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
19840 println!(
19841 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
19842 {screen_on}, pricer armings default={price_default} real={price_real}"
19843 );
19844 println!("| set | nz | blocks | priced bits | written bits | error |");
19845 println!("|---|---|---|---|---|---|");
19846 let (mut priced_all, mut written_all) = (0.0, 0.0);
19847 for ((set, bucket), (blocks, priced, written)) in &rows {
19848 priced_all += priced;
19849 written_all += written;
19850 println!(
19851 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
19852 crate::tile::census_bucket_label(*bucket),
19853 if *written > 0.0 {
19854 (priced - written) / written * 100.0
19855 } else {
19856 0.0
19857 }
19858 );
19859 }
19860 println!(
19861 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
19862 rows.values().map(|r| r.0).sum::<u64>(),
19863 (priced_all - written_all) / written_all * 100.0
19864 );
19865 assert!(
19866 written_all > 0.0,
19867 "{name}: the census saw no transform block"
19868 );
19869 }
19870 }
19871
19872 /// Low motion has to actually buy something: at least one inter frame of
19873 /// a panning sequence has to cost fewer bytes than the key frame that
19874 /// starts it, and the inter-block share it prints has to be non-zero --
19875 /// a search that never picks an inter mode would still pass a rate gate
19876 /// on a picture with no motion in it (the class this repo calls
19877 /// gate-blind-to-feature), so the share is printed even though it is not
19878 /// asserted on beyond being reachable at all.
19879 #[test]
19880 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
19881 let _knobs = crate::speed::knob_read();
19882 let fctx = &crate::decode::FrameCtx::for_encoder();
19883 let (width, height) = (256usize, 128usize);
19884 let pictures: Vec<Picture> = (0..5)
19885 .map(|i| panned_test_card(width, height, i * 2))
19886 .collect();
19887 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
19888
19889 let key_bytes = encoded.frames[0].stream.len();
19890 eprintln!("frame bytes inter share");
19891 for (i, frame) in encoded.frames.iter().enumerate() {
19892 eprintln!(
19893 "{i:5} {:5} {:11.2}",
19894 frame.stream.len(),
19895 frame.inter_block_share
19896 );
19897 }
19898 assert!(
19899 encoded.frames[1..]
19900 .iter()
19901 .any(|f| f.stream.len() < key_bytes),
19902 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
19903 );
19904 assert!(
19905 encoded.frames[1..]
19906 .iter()
19907 .any(|f| f.inter_block_share > 0.0),
19908 "no inter frame coded a single inter block -- the search never fired"
19909 );
19910 }
19911
19912 /// A manual perf probe, not a gate: prints where a key frame's and an
19913 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
19914 /// measures before it optimizes rather than guessing. Run with
19915 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
19916 #[test]
19917 #[ignore = "a perf probe, not a gate"]
19918 fn stage_timing_breakdown() {
19919 let _knobs = crate::speed::knob_read();
19920 let fctx = &crate::decode::FrameCtx::for_encoder();
19921 use std::time::Instant;
19922
19923 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
19924 let picture = test_card(width, height);
19925
19926 let t = Instant::now();
19927 let dc_only =
19928 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
19929 let dc_only_t = t.elapsed();
19930
19931 let t = Instant::now();
19932 let non_directional =
19933 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx)
19934 .unwrap();
19935 let non_directional_t = t.elapsed();
19936
19937 let t = Instant::now();
19938 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
19939 let all_modes_t = t.elapsed();
19940
19941 eprintln!(
19942 "\n=== key frame {width}x{height} ===\n\
19943 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
19944 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
19945 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
19946 dc_only.stream.len(),
19947 non_directional.stream.len(),
19948 all_modes.stream.len(),
19949 );
19950
19951 // One inter frame predicting off the key frame's own
19952 // reconstruction, the (256, 256)-padded surface encode_sequence
19953 // itself would hand encode_inter_frame.
19954 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
19955 let padded_pic = picture.padded_to(SUPERBLOCK);
19956 let t = Instant::now();
19957 let inter = encode_inter_frame(
19958 &padded_pic,
19959 &padded_ref,
19960 100,
19961 0.5,
19962 1,
19963 flat_order_hints(1, 0, false),
19964 (width, height),
19965 None,
19966 None,
19967 None,
19968 None,
19969 fctx,
19970 None,
19971 &[],
19972 )
19973 .unwrap();
19974 let inter_t = t.elapsed();
19975 eprintln!(
19976 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
19977 {:.2})",
19978 inter.stream.len(),
19979 inter.inter_block_share
19980 );
19981 }
19982
19983 // Isolated per-call cost of the trial pipeline's own stages, at both
19984 // transform sizes the search runs, averaged over enough calls to
19985 // rise above `Instant::now`'s own noise.
19986 for side in [16usize, 32] {
19987 const N: u32 = 20_000;
19988 let residual: Vec<i32> = (0..side * side)
19989 .map(|i| ((i * 37 % 61) as i32) - 30)
19990 .collect();
19991
19992 let t = Instant::now();
19993 let mut levels = Vec::new();
19994 for _ in 0..N {
19995 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
19996 }
19997 let forward_t = t.elapsed() / N;
19998
19999 let t = Instant::now();
20000 for _ in 0..N {
20001 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
20002 }
20003 let inverse_t = t.elapsed() / N;
20004
20005 let set = if side == 32 {
20006 crate::cdf_state::TxbSet::Luma32
20007 } else {
20008 crate::cdf_state::TxbSet::Luma16
20009 };
20010 let t = Instant::now();
20011 for _ in 0..N {
20012 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
20013 }
20014 let entropy_t = t.elapsed() / N;
20015
20016 let above = vec![128u8; side * 2];
20017 let left = vec![128u8; side * 2];
20018 let mut prediction = vec![0u8; side * side];
20019 let t = Instant::now();
20020 for _ in 0..N {
20021 intra_predict_u8(
20022 D45_PRED,
20023 0,
20024 Some(&above),
20025 Some(&left),
20026 Some(128),
20027 side,
20028 side,
20029 false,
20030 false,
20031 &mut prediction,
20032 fctx,
20033 );
20034 }
20035 let predict_t = t.elapsed() / N;
20036
20037 eprintln!(
20038 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
20039 predict (1 directional mode): {predict_t:>9.2?}\n\
20040 forward_and_quantize: {forward_t:>9.2?}\n\
20041 dequant_and_inverse: {inverse_t:>9.2?}\n\
20042 coeff_bits: {entropy_t:>9.2?}"
20043 );
20044 }
20045 }
20046
20047 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
20048 /// plus what is left over once buckets 0/2/3 are subtracted.
20049 ///
20050 /// lane-av1probes: the two search-shaped buckets OVERLAP and the old
20051 /// print denied it. Bucket 0 is not "the motion search": `stage_since(0,
20052 /// ..)` fires only after `find_best_new_mv` and the global-MV search
20053 /// (`encode.rs:11959`, `:12080`), so it is the NEWMV/GLOBAL sub-search
20054 /// alone. Bucket 1 is EVERY `crate::mc::predict` call, from the search's
20055 /// candidates *and* from a committed inter block's final prediction --
20056 /// and that final prediction runs OUTSIDE any bucket-0 region. So bucket 1
20057 /// is neither inside bucket 0 nor smaller than it, and a print that shows
20058 /// it as "motion search (of which interpolation ...)" necessarily shows
20059 /// a sub-number bigger than its parent. Measured: bucket 0 = 17.82 ms,
20060 /// bucket 1 = 148.63 ms.
20061 ///
20062 /// Which number is real: BOTH timers are right; only the old ARITHMETIC
20063 /// was wrong. Bucket 1 is now printed as its own top-level row, the
20064 /// overlap is stated, and the residual is labelled for what it is -- it
20065 /// absorbs the committed block's own interpolation, so it is not a pure
20066 /// "13-mode intra candidate loop" figure either.
20067 ///
20068 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
20069 #[test]
20070 #[ignore = "a perf probe, not a gate"]
20071 fn stage_timing_breakdown_inter() {
20072 let _knobs = crate::speed::knob_read();
20073 let fctx = &crate::decode::FrameCtx::for_encoder();
20074 use std::time::Instant;
20075
20076 let (width, height) = (1280usize, 720);
20077 let picture = test_card(width, height);
20078 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
20079 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
20080 let padded_pic = picture.padded_to(SUPERBLOCK);
20081
20082 stage_reset();
20083 let t = Instant::now();
20084 let inter = encode_inter_frame(
20085 &padded_pic,
20086 &padded_ref,
20087 100,
20088 0.5,
20089 1,
20090 flat_order_hints(1, 0, false),
20091 (width, height),
20092 None,
20093 None,
20094 None,
20095 None,
20096 fctx,
20097 None,
20098 &[],
20099 )
20100 .unwrap();
20101 let total_t = t.elapsed();
20102 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
20103 // Buckets 0 and 2 and 3 are disjoint and additive. Bucket 1 (every
20104 // `mc::predict` call) is NOT added: it overlaps bucket 0 wherever a
20105 // search candidate calls predict, and it also covers the committed
20106 // block's final prediction, which no other bucket times. Adding it
20107 // would double-count the overlap; leaving it out puts the committed
20108 // prediction (and the intra candidate loop, RD glue, and the symbol
20109 // lookups outside `coeff_bits`) into the residual, which is what the
20110 // residual has always been.
20111 let accounted = motion_search + transform_quant + entropy;
20112 let other = total_t.saturating_sub(accounted);
20113 let overlap = interpolation.saturating_sub(motion_search);
20114
20115 eprintln!(
20116 "\n=== inter frame {width}x{height}, one frame ===\n\
20117 total: {total_t:>9.2?} ({} bytes)\n\
20118 NEWMV/GLOBAL sub-search (bucket 0): {motion_search:>9.2?}\n\
20119 transform + quantize (bucket 2): {transform_quant:>9.2?}\n\
20120 coeff_bits, entropy pricing (bucket 3): {entropy:>9.2?}\n\
20121 buckets 0+2+3 accounted: {accounted:>9.2?}\n\
20122 \n\
20123 OVERLAPPING, not additive: every mc::predict call (bucket 1) {interpolation:>9.2?}\n\
20124 \x20 -- of which {overlap:>9.2?} is OUTSIDE bucket 0 (a committed\n\
20125 \x20 inter block's final prediction, which no bucket above times)\n\
20126 \x20 and the rest is the search candidates' interpolation, already\n\
20127 \x20 inside bucket 0. It is deliberately NOT added to the total.\n\
20128 \n\
20129 residual (13-mode intra candidate loop, the committed block's\n\
20130 \x20 interpolation above, NEARESTMV's own predict, RD glue): {other:>9.2?}",
20131 inter.stream.len(),
20132 );
20133 }
20134
20135 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
20136 /// frames (a dark/flat one, a detailed one, a normal film one) at two
20137 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
20138 /// None`, the baseline this same build produces without
20139 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
20140 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
20141 /// go in the lane report, which is where "ship as default" is decided --
20142 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
20143 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
20144 #[test]
20145 // The three clip paths are HARD-CODED ABSOLUTES under /home/user, not
20146 // env-driven: off this workstation every row prints `SKIP <label>: <path>
20147 // not present on this machine` and the run exits 0 with no numbers. It is
20148 // a local-run probe; there is no fleet-host configuration that makes it
20149 // measure anything.
20150 #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
20151 fn prune_k_quality_sweep() {
20152 let _knobs = crate::speed::knob_read();
20153 let fctx = &crate::decode::FrameCtx::for_encoder();
20154 if !have_ffmpeg() {
20155 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
20156 return;
20157 }
20158 let (width, height) = (640usize, 352usize);
20159 let frames: &[(&str, &str, &str)] = &[
20160 // (label, clip, seek) -- a near-black scene, a busy one, and an
20161 // ordinary film frame, each from a different real file.
20162 (
20163 "dark/flat",
20164 "/home/user/Videos/reela.mp4",
20165 "3",
20166 ),
20167 (
20168 "detailed",
20169 "/home/user/Downloads/reelb.mkv",
20170 "1200",
20171 ),
20172 (
20173 "film",
20174 "/home/user/Videos/Films/reelc.mkv",
20175 "600",
20176 ),
20177 ];
20178 for &(label, clip, skip) in frames {
20179 if !std::path::Path::new(clip).exists() {
20180 eprintln!("SKIP {label}: {clip} not present on this machine");
20181 continue;
20182 }
20183 let picture = clip_frame(clip, skip, width, height);
20184 for &q in &[60u8, 150] {
20185 // SAFETY (not literally unsafe, just process-global): this is
20186 // a single-threaded #[ignore] probe, run by hand, never
20187 // alongside other tests that read Search::top_k.
20188 set_test_top_k_override(None);
20189 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
20190 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
20191 eprint!(
20192 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
20193 baseline.stream.len(),
20194 baseline_psnr
20195 );
20196 for &k in &[3usize, 4, 6] {
20197 set_test_top_k_override(Some(k));
20198 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
20199 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
20200 eprint!(
20201 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
20202 pruned.stream.len(),
20203 pruned_psnr,
20204 pruned_psnr - baseline_psnr
20205 );
20206 }
20207 eprintln!();
20208 }
20209 }
20210 set_test_top_k_override(None);
20211 }
20212
20213 /// Two consecutive decoded frames from one clip, for an inter-frame
20214 /// sweep -- [`clip_frame`] alone only ever gives one.
20215 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
20216 let out = Command::new("ffmpeg")
20217 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
20218 .args(["-vf", &format!("scale={width}:{height}")])
20219 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
20220 .output()
20221 .expect("ffmpeg failed to run");
20222 assert!(
20223 out.status.success(),
20224 "ffmpeg: {}",
20225 String::from_utf8_lossy(&out.stderr)
20226 );
20227 let (luma, chroma) = (width * height, width * height / 4);
20228 let frame_len = luma + 2 * chroma;
20229 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
20230 std::array::from_fn(|i| {
20231 let bytes = &out.stdout[i * frame_len..][..frame_len];
20232 Picture {
20233 width,
20234 height,
20235 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
20236 u: bytes[luma..luma + chroma]
20237 .iter()
20238 .map(|&v| u16::from(v))
20239 .collect(),
20240 v: bytes[luma + chroma..]
20241 .iter()
20242 .map(|&v| u16::from(v))
20243 .collect(),
20244 }
20245 })
20246 }
20247
20248 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
20249 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
20250 /// then one inter frame off it (`search_inter_block`'s own intra
20251 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
20252 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
20253 /// padding step complicates the comparison. Prints bytes and luma PSNR
20254 /// for the inter frame alone, unpruned vs each `K`.
20255 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
20256 #[test]
20257 // Same hard-coded /home/user clip paths as `prune_k_quality_sweep`;
20258 // off this workstation it SKIPs all three rows and prints nothing.
20259 #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
20260 fn prune_k_quality_sweep_inter() {
20261 let _knobs = crate::speed::knob_read();
20262 let fctx = &crate::decode::FrameCtx::for_encoder();
20263 if !have_ffmpeg() {
20264 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
20265 return;
20266 }
20267 let (width, height) = (1280usize, 704usize);
20268 let frames: &[(&str, &str, &str)] = &[
20269 (
20270 "dark/flat",
20271 "/home/user/Videos/reela.mp4",
20272 "3",
20273 ),
20274 (
20275 "detailed",
20276 "/home/user/Downloads/reelb.mkv",
20277 "1200",
20278 ),
20279 (
20280 "film",
20281 "/home/user/Videos/Films/reelc.mkv",
20282 "600",
20283 ),
20284 ];
20285 for &(label, clip, skip) in frames {
20286 if !std::path::Path::new(clip).exists() {
20287 eprintln!("SKIP {label}: {clip} not present on this machine");
20288 continue;
20289 }
20290 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
20291 for &q in &[60u8, 150] {
20292 // SAFETY (not literally unsafe, just process-global): a
20293 // single-threaded #[ignore] probe, run by hand, never
20294 // alongside other tests that read Search::top_k.
20295 set_test_top_k_override_inter(None);
20296 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
20297 let baseline = encode_inter_frame(
20298 &inter_source,
20299 &key.reconstruction,
20300 q,
20301 0.5,
20302 1,
20303 flat_order_hints(1, 0, false),
20304 (width, height),
20305 None,
20306 None,
20307 None,
20308 None,
20309 fctx,
20310 None,
20311 &[],
20312 )
20313 .unwrap();
20314 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
20315 eprint!(
20316 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
20317 baseline.stream.len(),
20318 baseline_psnr
20319 );
20320 for &k in &[3usize, 4, 6] {
20321 set_test_top_k_override_inter(Some(k));
20322 let pruned = encode_inter_frame(
20323 &inter_source,
20324 &key.reconstruction,
20325 q,
20326 0.5,
20327 1,
20328 flat_order_hints(1, 0, false),
20329 (width, height),
20330 None,
20331 None,
20332 None,
20333 None,
20334 fctx,
20335 None,
20336 &[],
20337 )
20338 .unwrap();
20339 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
20340 eprint!(
20341 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
20342 pruned.stream.len(),
20343 pruned_psnr,
20344 pruned_psnr - baseline_psnr
20345 );
20346 }
20347 eprintln!();
20348 }
20349 }
20350 set_test_top_k_override_inter(None);
20351 }
20352
20353 /// `frames` consecutive pictures out of a real clip, scaled to a whole
20354 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
20355 /// to an arbitrary count for the fixture regression gate below.
20356 fn clip_frames(
20357 clip: &str,
20358 skip: &str,
20359 width: usize,
20360 height: usize,
20361 frames: usize,
20362 ) -> Vec<Picture> {
20363 clip_frames_vf(
20364 clip,
20365 skip,
20366 &format!("scale={width}:{height}"),
20367 width,
20368 height,
20369 frames,
20370 )
20371 }
20372
20373 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
20374 /// for a native-resolution CROP instead of a downscale (the downscale is
20375 /// what destroys a screen capture's exact repeats -- class
20376 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
20377 fn clip_frames_vf(
20378 clip: &str,
20379 skip: &str,
20380 vf: &str,
20381 width: usize,
20382 height: usize,
20383 frames: usize,
20384 ) -> Vec<Picture> {
20385 // ONE definition of the gate's loader recipe, shared with
20386 // `examples/enc_probe` so the instrument cannot arm a different source
20387 // than the gate it reports on (class `instrument disagrees with the
20388 // gate`; lane-probe).
20389 crate::probe::source(clip, skip, vf, width, height, frames)
20390 }
20391
20392 /// The standing regression gate on real content: 12 frames of a real
20393 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
20394 /// this crate's own input regardless of its own source codec), encoded
20395 /// as an AV1 GOP and checked against three numeric floors so a
20396 /// compatibility or quality regression fails the suite instead of
20397 /// waiting for a downstream repo's gate to catch it (as happened for a
20398 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
20399 /// refusal, both caught only that way).
20400 ///
20401 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
20402 /// that geometry is already covered elsewhere), chosen only so encode
20403 /// time and gate numbers are not muddied by an edge-block class this
20404 /// test is not about.
20405 ///
20406 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
20407 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
20408 /// below carry a margin off those measured numbers (PSNR floor =
20409 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
20410 #[test]
20411 fn real_clip_encodes_within_its_quality_and_size_budget() {
20412 let _knobs = crate::speed::knob_read();
20413 let fctx = &crate::decode::FrameCtx::for_encoder();
20414 if !have_ffmpeg() {
20415 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
20416 return;
20417 }
20418 // lane-av1clipprobe: the clip's absence was a bare `clip.exists()`
20419 // -> SKIP with no env escape, so this gate reported green on a tree
20420 // with no root `fixtures/`. The probe prints that one line (naming the
20421 // resolved path) and fails under the require envs.
20422 let Some(clip) = crate::library_fixture::require(
20423 "video/h264-1080p-23.976-8bit.mp4",
20424 "real_clip_encodes_within_its_quality_and_size_budget",
20425 ) else {
20426 return;
20427 };
20428 let (width, height, frame_count) = (640usize, 384usize, 12usize);
20429 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
20430 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
20431 assert_eq!(encoded.frames.len(), frame_count);
20432
20433 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
20434 // stream and hands back every frame -- a stream a downstream
20435 // decoder refuses is the exact class of regression this gate
20436 // exists for.
20437 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
20438 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
20439
20440 // Gate 2: quality vs the source did not silently collapse.
20441 let mean_psnr: f64 = decoded
20442 .iter()
20443 .zip(&source)
20444 .map(|(d, s)| psnr(&d.y, &s.y))
20445 .sum::<f64>()
20446 / frame_count as f64;
20447 assert!(
20448 mean_psnr >= 44.91,
20449 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
20450 );
20451
20452 // Gate 3: the stream did not silently bloat.
20453 assert!(
20454 encoded.stream.len() <= 80_340,
20455 "stream grew to {} bytes, over the 80340-byte ceiling",
20456 encoded.stream.len()
20457 );
20458 }
20459
20460 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
20461 /// straddle size: 640x384 is exact on both axes (32-aligned), so
20462 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
20463 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
20464 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
20465 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
20466 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
20467 /// card; this one is the real-clip gate, same three floors.
20468 ///
20469 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
20470 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
20471 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
20472 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
20473 #[test]
20474 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
20475 let _knobs = crate::speed::knob_read();
20476 let fctx = &crate::decode::FrameCtx::for_encoder();
20477 if !have_ffmpeg() {
20478 eprintln!(
20479 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
20480 no ffmpeg"
20481 );
20482 return;
20483 }
20484 // lane-av1clipprobe: see the sibling gate above -- the bare
20485 // `clip.exists()` -> SKIP had no env escape.
20486 let Some(clip) = crate::library_fixture::require(
20487 "video/h264-1080p-23.976-8bit.mp4",
20488 "real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size",
20489 ) else {
20490 return;
20491 };
20492 let (width, height, frame_count) = (704usize, 400usize, 8usize);
20493 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
20494 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
20495 assert_eq!(encoded.frames.len(), frame_count);
20496
20497 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
20498 // stream and hands back every frame.
20499 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
20500 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
20501
20502 // Gate 2: quality vs the source did not silently collapse.
20503 let mean_psnr: f64 = decoded
20504 .iter()
20505 .zip(&source)
20506 .map(|(d, s)| psnr(&d.y, &s.y))
20507 .sum::<f64>()
20508 / frame_count as f64;
20509 assert!(
20510 mean_psnr >= 44.98,
20511 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
20512 );
20513
20514 // Gate 3: the stream did not silently bloat.
20515 assert!(
20516 encoded.stream.len() <= 62_703,
20517 "stream grew to {} bytes, over the 62703-byte ceiling",
20518 encoded.stream.len()
20519 );
20520 }
20521
20522 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
20523 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
20524 /// facade -- timed end to end, so the edith export-time projection is a
20525 /// real number rather than a guess from the isolated key/inter numbers
20526 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
20527 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
20528 #[test]
20529 #[ignore = "a perf probe, not a gate"]
20530 fn sequence_bench_sanity() {
20531 let _knobs = crate::speed::knob_read();
20532 let fctx = &crate::decode::FrameCtx::for_encoder();
20533 use std::time::Instant;
20534 let (width, height) = (1280usize, 720usize);
20535 let pictures: Vec<Picture> = (0..24)
20536 .map(|i| panned_test_card(width, height, i * 3))
20537 .collect();
20538 let t = Instant::now();
20539 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
20540 let elapsed = t.elapsed();
20541 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
20542 eprintln!(
20543 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
20544 elapsed / 24
20545 );
20546 }
20547
20548 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
20549 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
20550 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
20551 /// -- --ignored --nocapture`.
20552 #[test]
20553 #[ignore = "a calibration probe, not a gate"]
20554 fn calibration_sweep_base_q_idx() {
20555 let _knobs = crate::speed::knob_read();
20556 let fctx = &crate::decode::FrameCtx::for_encoder();
20557 if !have_ffmpeg() {
20558 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
20559 return;
20560 }
20561 let (width, height, frames) = (640usize, 384usize, 12usize);
20562 for clip in [
20563 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
20564 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
20565 ] {
20566 // lane-av1clipprobe: the crate's one fixture root and its one
20567 // presence probe -- the bare `path.exists()` -> SKIP -> `continue`
20568 // had no env escape, and with every clip absent the sweep looped
20569 // zero times and passed.
20570 let Some(path) = crate::library_fixture::require(
20571 &format!("video/{clip}"),
20572 &format!("calibration_sweep_base_q_idx: {clip}"),
20573 ) else {
20574 continue;
20575 };
20576 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
20577 eprintln!("--- {clip} ---");
20578 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
20579 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
20580 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
20581 let mean_psnr: f64 = decoded
20582 .iter()
20583 .zip(&source)
20584 .map(|(d, s)| psnr(&d.y, &s.y))
20585 .sum::<f64>()
20586 / frames as f64;
20587 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
20588 eprintln!(
20589 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
20590 encoded.stream.len()
20591 );
20592 }
20593 }
20594 }
20595
20596 // -----------------------------------------------------------------------
20597 // The encoder's standing BD-rate baseline against libaom and rav1e.
20598 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
20599 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
20600 // agreeing with our encoder proves nothing about the bitstream.
20601 // -----------------------------------------------------------------------
20602
20603 /// All-plane PSNR of a decoded picture against its source, on the same
20604 /// 8-bit scale [`psnr`] uses.
20605 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
20606 let cat = |p: &Picture| {
20607 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
20608 v.extend_from_slice(&p.y);
20609 v.extend_from_slice(&p.u);
20610 v.extend_from_slice(&p.v);
20611 v
20612 };
20613 psnr(&cat(decoded), &cat(source))
20614 }
20615
20616 /// The pictures back as the planar 8-bit bytes an encoder reads.
20617 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
20618 let mut raw = Vec::new();
20619 for p in source {
20620 for plane in [&p.y, &p.u, &p.v] {
20621 raw.extend(plane.iter().map(|&s| s as u8));
20622 }
20623 }
20624 raw
20625 }
20626
20627 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
20628 /// through ffmpeg: one point per entry of `points`, each a quality flag
20629 /// set. Returns the ladder ordered by fidelity and the total encode wall
20630 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
20631 /// so both curves are measured by the same decoder.
20632 fn external_ladder(
20633 source: &[Picture],
20634 width: usize,
20635 height: usize,
20636 encoder: &str,
20637 points: &[Vec<String>],
20638 ) -> (Vec<(f64, f64)>, f64) {
20639 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
20640 let dir = std::env::temp_dir();
20641 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
20642 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
20643 let mut ladder = Vec::new();
20644 let mut wall = 0.0;
20645 for (i, params) in points.iter().enumerate() {
20646 let obu = dir.join(format!(
20647 "ec-av1-bd-{}-{encoder}-{i}.obu",
20648 std::process::id()
20649 ));
20650 let start = std::time::Instant::now();
20651 let out = Command::new("ffmpeg")
20652 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
20653 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
20654 .arg(&raw_path)
20655 .args(["-an", "-threads", "1"])
20656 .args(["-g", &source.len().to_string(), "-c:v", encoder])
20657 .args(params)
20658 .args(["-f", "obu"])
20659 .arg(&obu)
20660 .output()
20661 .expect("ffmpeg failed to run");
20662 wall += start.elapsed().as_secs_f64();
20663 assert!(
20664 out.status.success(),
20665 "{encoder} {params:?}: {}",
20666 String::from_utf8_lossy(&out.stderr)
20667 );
20668 let stream = std::fs::read(&obu).expect("reference stream");
20669 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
20670 // lane-dkey: every reference point must also decode through OUR
20671 // decoder, sample-exact against ffmpeg's decode of the same bytes.
20672 // A BD table computed off streams we cannot read is a table about
20673 // an encoder we cannot check; this is the assertion that would
20674 // have caught the `force_integer_mv` defect (its stream decoded to
20675 // 25 dB garbage while this gate stayed green) and the crf-5 key
20676 // frame desync. A failure names the encoder, the point's flags and
20677 // the first differing frame/plane/sample.
20678 // lane-dpm1: a failing reference point is COLLECTED, not panicked
20679 // on, so one run still prints the whole BD table and names every
20680 // bad point instead of stopping at the first. The collection is
20681 // asserted empty by [`assert_ladder_decodes`] at the end of each
20682 // gate.
20683 match crate::stream::decode_stream(&stream) {
20684 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
20685 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
20686 ours.len(),
20687 decoded.len(),
20688 )),
20689 Ok(ours) => {
20690 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
20691 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
20692 note_ladder_failure(format!(
20693 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
20694 decoder decoded {got}, ffmpeg {want}"
20695 ));
20696 break;
20697 }
20698 }
20699 }
20700 Err(e) => note_ladder_failure(format!(
20701 "{encoder} {params:?}: our decoder refused the stream ({e})"
20702 )),
20703 }
20704 let mean: f64 = decoded
20705 .iter()
20706 .zip(source)
20707 .map(|(d, s)| psnr_all(d, s))
20708 .sum::<f64>()
20709 / source.len() as f64;
20710 ladder.push((mean, (stream.len() as f64).log10()));
20711 let _ = std::fs::remove_file(&obu);
20712 }
20713 let _ = std::fs::remove_file(&raw_path);
20714 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
20715 (ladder, wall)
20716 }
20717
20718 /// Every reference ladder point that did not decode sample-exactly
20719 /// through our own decoder, collected across a whole gate run so the BD
20720 /// table still prints and EVERY bad point is named
20721 /// (`encoder params frame plane sample`) instead of only the first.
20722 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
20723
20724 fn note_ladder_failure(msg: String) {
20725 eprintln!("LADDER DECODE FAILURE: {msg}");
20726 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
20727 }
20728
20729 /// Fail the gate at its END on everything [`external_ladder`] collected.
20730 fn assert_ladder_decodes() {
20731 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
20732 assert!(
20733 failures.is_empty(),
20734 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
20735 failures.len(),
20736 failures.join("\n"),
20737 );
20738 }
20739
20740 /// First differing sample between two pictures, as
20741 /// `(plane, index, left, right)` -- so a gate failure names the plane and
20742 /// the sample instead of just "differs". A length difference counts as a
20743 /// mismatch of that plane at the first index past the shorter one.
20744 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
20745 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
20746 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
20747 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
20748 }
20749 if l.len() != r.len() {
20750 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
20751 }
20752 }
20753 None
20754 }
20755
20756 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
20757 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
20758 /// stream is decoded twice -- by ffmpeg and by our own
20759 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
20760 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
20761 /// in Y, U and V over every shown frame in display order. That is itself
20762 /// a gate: it proves the bitstream says what the encoder thinks, in the
20763 /// only two decoders that read it.
20764 fn our_ladder(
20765 name: &str,
20766 source: &[Picture],
20767 width: usize,
20768 height: usize,
20769 fctx: &crate::decode::FrameCtx,
20770 ) -> (Vec<(f64, f64)>, f64) {
20771 let mut ladder = Vec::new();
20772 let mut wall = 0.0;
20773 for &q in &[150u8, 120, 90, 60] {
20774 let start = std::time::Instant::now();
20775 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
20776 // the gate has to be able to re-sweep it. 0.5 is the shipped one
20777 // (`crate::encoder::DEADZONE`).
20778 let deadzone = std::env::var("EC_AV1_DEADZONE")
20779 .ok()
20780 .and_then(|v| v.parse().ok())
20781 .unwrap_or(0.5);
20782 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
20783 wall += start.elapsed().as_secs_f64();
20784 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
20785 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
20786 assert_eq!(
20787 ours.len(),
20788 source.len(),
20789 "{name} q={q}: our decoder's display-order frame count"
20790 );
20791 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
20792 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
20793 panic!(
20794 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
20795 {got}, the encoder reconstructed {want}"
20796 );
20797 }
20798 }
20799 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
20800 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
20801 panic!(
20802 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
20803 {got}, the encoder reconstructed {want}"
20804 );
20805 }
20806 }
20807 let per_frame: Vec<f64> = decoded
20808 .iter()
20809 .zip(source)
20810 .map(|(d, s)| psnr_all(d, s))
20811 .collect();
20812 // lane-txrd: does a tool's loss start at the FIRST inter frame
20813 // (a local mispricing) or grow down the GOP (propagation into
20814 // the reference chain)? One line per q point answers it.
20815 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
20816 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
20817 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
20818 // lane-txrd: per PLANE, because an all-plane mean hides a
20819 // collapse in one of them (class `metric blind to a plane`).
20820 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
20821 let v: Vec<String> = decoded
20822 .iter()
20823 .zip(source)
20824 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
20825 .collect();
20826 v.join(" ")
20827 };
20828 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
20829 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
20830 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
20831 }
20832 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
20833 ladder.push((mean, (encoded.stream.len() as f64).log10()));
20834 }
20835 // What this clip asked for and what the content gate left it coding
20836 // under: a screen clip requests a pyramid and codes flat, and that
20837 // difference is what keeps its row identical to the flat baseline
20838 // (class `gate-blind-to-feature`).
20839 eprintln!(
20840 "{name}: sequence, pyramid requested {:?} effective {:?}",
20841 crate::encoder::Pyramid::from_env(),
20842 last_sequence_pyramid(),
20843 );
20844 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
20845 (ladder, wall)
20846 }
20847
20848 /// [`our_ladder`] through the streaming facade — the surface the editor's
20849 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
20850 /// each stream is also reordered (hidden `ALTREF` first,
20851 /// `show_existing_frame` last per group) and each level is coded at its
20852 /// own quantizer offset; without one it is the flat ladder, which
20853 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
20854 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
20855 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
20856 /// the whole ladder how many frames and how many bytes it spent, and the
20857 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
20858 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
20859 /// flat path, so a requested pyramid can come back `None` here.
20860 fn our_ladder_facade(
20861 name: &str,
20862 source: &[Picture],
20863 width: usize,
20864 height: usize,
20865 pyramid: Option<crate::encoder::Pyramid>,
20866 ) -> (
20867 Vec<(f64, f64)>,
20868 f64,
20869 [usize; 4],
20870 [usize; 4],
20871 Option<crate::encoder::Pyramid>,
20872 ) {
20873 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
20874 let slot = |l: Level| match l {
20875 Level::Key => 0,
20876 Level::Arf => 1,
20877 Level::Leaf => 2,
20878 Level::ShowExisting => 3,
20879 };
20880 let mut ladder = Vec::new();
20881 let mut wall = 0.0;
20882 let mut effective = None;
20883 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
20884 for &q in &[150u8, 120, 90, 60] {
20885 let config = EncoderConfig {
20886 width,
20887 height,
20888 base_q_idx: q,
20889 gop: source.len(),
20890 colour: Colour::Unspecified,
20891 tile_cols_log2: 0,
20892 tile_rows_log2: 0,
20893 };
20894 let start = std::time::Instant::now();
20895 let mut enc = match pyramid {
20896 None => Av1Encoder::new(config).unwrap(),
20897 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
20898 };
20899 let mut packets = Vec::new();
20900 for picture in source {
20901 packets.extend(enc.encode_frames(picture).unwrap());
20902 }
20903 packets.extend(enc.flush().unwrap());
20904 wall += start.elapsed().as_secs_f64();
20905 effective = enc.pyramid();
20906 let mut stream = Vec::new();
20907 for p in &packets {
20908 counts[slot(p.level)] += 1;
20909 bytes[slot(p.level)] += p.data.len();
20910 stream.extend_from_slice(&p.data);
20911 }
20912 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
20913 // correct if the DISPLAY-order output still has one frame per
20914 // source picture, in the right order -- checked against our own
20915 // decoder as well as ffmpeg's, both below.
20916 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
20917 assert_eq!(
20918 ours.len(),
20919 source.len(),
20920 "{name} q={q}: our display-order count"
20921 );
20922 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
20923 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
20924 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
20925 panic!(
20926 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
20927 decoded {got}, our decoder decoded {want}"
20928 );
20929 }
20930 }
20931 let mean: f64 = decoded
20932 .iter()
20933 .zip(source)
20934 .map(|(d, s)| psnr_all(d, s))
20935 .sum::<f64>()
20936 / source.len() as f64;
20937 ladder.push((mean, (stream.len() as f64).log10()));
20938 }
20939 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
20940 (ladder, wall, counts, bytes, effective)
20941 }
20942
20943 /// Byte-exactness gate for encoder work that is meant to change only
20944 /// how long the encoder takes.
20945 ///
20946 /// The BD gate above measures quality, which a speed lane can move by a
20947 /// hair without failing anything; this pins the streams themselves.
20948 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
20949 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
20950 /// in the tile) and again on lane-av1mv's merge of it: an extra
20951 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
20952 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
20953 /// prices coefficients against the tables the frame's writer really
20954 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
20955 /// decision change the BD gate judges. Re-pinned again on
20956 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
20957 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
20958 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
20959 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
20960 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
20961 /// by default ([`warp_on`], a sequence/frame header bit and a new
20962 /// motion_mode symbol on eligible blocks) and
20963 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
20964 /// every inter frame's superblocks now code at their own lambda
20965 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
20966 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
20967 /// and the two var-tx depth searches ([`tx32_depth_search`],
20968 /// [`compound_var_tx`]) are on by default, all three re-judged on the
20969 /// native gate's real film rows.
20970 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
20971 /// every block whose chroma takes it codes a different mode symbol, two
20972 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
20973 /// restores the previous streams. Re-pinned again in the same lane once
20974 /// directional luma winners searched their `angle_delta_y`
20975 /// (`EC_AV1_ANGLE=0` restores that half).
20976 #[test]
20977 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
20978 // These are DEFAULT-PRESET pins: a speed preset switches search levers
20979 // off, so it legitimately moves every byte. Encode at speed 0 whatever
20980 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
20981 let _knobs = crate::speed::knob_write();
20982 let was = crate::speed::speed();
20983 crate::speed::set_speed(0);
20984 if !have_ffmpeg() {
20985 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
20986 return;
20987 }
20988 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
20989 // so a tree with no root `fixtures/` reported this gate green having
20990 // compared nothing at all.
20991 let Some(clip) = crate::library_fixture::require(
20992 "video/h264-1080p-23.976-8bit.mp4",
20993 "the_encoders_own_streams_are_byte_identical_to_their_pins",
20994 ) else {
20995 return;
20996 };
20997 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
20998 // FNV-1a over the stream: a witness that every coded bit is where it
20999 // was, which a byte count alone is not.
21000 let fnv = |b: &[u8]| {
21001 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
21002 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
21003 })
21004 };
21005 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
21006 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
21007 // of 4, its leaves at q+8 and a `show_existing_frame` header per
21008 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
21009 // four frames; four pictures is one short mini-GOP, which is the
21010 // shape that pays least (the ARF's own quality has no later group to
21011 // carry it), so this is not the BD gate's number.
21012 // Re-taken again on lane-av1cfl: the chroma search offers
21013 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
21014 // so every block taking either codes different syntax and different
21015 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
21016 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
21017 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
21018 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
21019 // so these four pictures code as one truncated group -- a hidden
21020 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
21021 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
21022 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
21023 // Re-taken on lane-fintra: the sequence header sets
21024 // `enable_filter_intra`, so every DC_PRED intra block of at most
21025 // 32x32 without a luma palette carries a `use_filter_intra` flag and
21026 // the blocks that take one code a filter-intra mode, a different
21027 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
21028 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
21029 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
21030 // (default pyramid `8:-32:16`, one truncated group of 8 with its
21031 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
21032 // root can code a REAL residual now (one TX_64X64 luma transform and
21033 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
21034 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
21035 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
21036 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
21037 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
21038 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
21039 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
21040 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
21041 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
21042 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
21043 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
21044 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
21045 // these four pictures -- offers every superblock a 64x64 intra root
21046 // now. `EC_AV1_I64=0` restores 8557 / 33345.
21047 // Re-taken on lane-pricer: the inter RD search prices a single
21048 // reference through the tree and the neighbour contexts the writer
21049 // really codes it with, so every inter picture's reference decisions
21050 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
21051 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
21052 // for `skip`/`is_inter` and for the whole compound reference tree, so
21053 // every inter block's cost -- and with it the skip and reference
21054 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
21055 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
21056 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
21057 // single and compound are priced against the same syntax -- 8311 ->
21058 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
21059 // Re-taken on lane-newmv: the motion search charges its own rate term
21060 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
21061 // and each subpel stage re-runs from its own winner
21062 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
21063 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
21064 // and 33014 -> 33090 at q=60.
21065 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
21066 // from libaom's objective tpl mapping, so every inter picture's
21067 // quantizer grid -- and every decision priced against it -- moved
21068 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
21069 // at the merge of both lanes.
21070 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
21071 // per-superblock `delta_qindex` at 1.5x the preset's strength
21072 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
21073 // grids -- and every decision priced against them -- moved:
21074 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
21075 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
21076 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
21077 // pixels -- and the leaves that predict from them -- moved:
21078 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
21079 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
21080 // the shipped stream did not move.
21081 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
21082 // picture is coded in 128x128 superblocks now, the inter ones
21083 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
21084 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
21085 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
21086 // by default, on top of the ARF temporal filter).
21087 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
21088 // candidates the 64 root already did ([`b128_compound`]), so every
21089 // inter frame that carries `reference_select` codes different blocks
21090 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
21091 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
21092 // Re-taken on lane-arftf: that filter's strength swept on the deciding
21093 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
21094 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
21095 // 33017 at q=60 (the same LENGTH, different bytes).
21096 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
21097 // lane-rlclamp onto the 128 compound default.
21098 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
21099 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
21100 // so every inter frame whose RD takes one codes a different partition
21101 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
21102 // quantizer the rect cut never wins its own comparison on this clip.
21103 // `EC_AV1_B128HV=0` restores 8290 exactly.
21104 let pins: [(u8, usize, u64); 2] = [
21105 (150, 8291, 0x1f00bb0eb099a27f),
21106 (60, 33227, 0x57ee6b1f8eacd881),
21107 ];
21108 let coded: Vec<(u8, usize, u64)> = pins
21109 .iter()
21110 .map(|&(q, _, _)| {
21111 let e = encode_sequence(&source, q, 0.5).unwrap();
21112 (q, e.stream.len(), fnv(&e.stream))
21113 })
21114 .collect();
21115 crate::speed::set_speed(was);
21116 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
21117 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
21118 }
21119 }
21120
21121 /// A ladder is only a ladder if both axes rise together.
21122 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
21123 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
21124 for w in ladder.windows(2) {
21125 assert!(
21126 w[1].0 > w[0].0 && w[1].1 > w[0].1,
21127 "{name}: not monotone, {ladder:?}"
21128 );
21129 }
21130 }
21131
21132 /// The sweep behind [`screen_content`]'s constants
21133 /// (`unswept-decision-constants`), on the SAME five clips
21134 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
21135 /// same native crop: for each colour bound N the share of 16x16 luma
21136 /// blocks with 2..=N distinct colours, and the share of those whose
21137 /// per-pixel variance also clears a floor V -- libaom's
21138 /// `av1_set_screen_content_options` counts the variance-cleared blocks
21139 /// too (its `counts_2`, which gates intrabc), and without that term a
21140 /// smooth dark film frame reads as screen content.
21141 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
21142 #[test]
21143 #[ignore = "reads the real library"]
21144 fn probe_screen_detect() {
21145 let _knobs = crate::speed::knob_read();
21146 if !have_ffmpeg() {
21147 eprintln!("SKIP probe_screen_detect: no ffmpeg");
21148 return;
21149 }
21150 let limits = [4usize, 8, 16, 32, 64, 128];
21151 let floors = [0u64, 4, 16, 64, 256];
21152 // The census of one clip at one size: mean share, over the frames, of
21153 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
21154 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
21155 let mut acc = [[0f64; 5]; 6];
21156 for picture in frames {
21157 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
21158 let mut hit = [[0usize; 5]; 6];
21159 let mut blocks = 0usize;
21160 for by in (0..ch).step_by(16) {
21161 for bx in (0..cw).step_by(16) {
21162 let mut seen = [false; 256];
21163 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
21164 for row in 0..16 {
21165 for col in 0..16 {
21166 let v = y[(by + row) * cw + bx + col];
21167 sum += u64::from(v);
21168 sq += u64::from(v) * u64::from(v);
21169 if !seen[usize::from(v)] {
21170 seen[usize::from(v)] = true;
21171 colors += 1;
21172 }
21173 }
21174 }
21175 let var = (sq - sum * sum / 256) / 256;
21176 blocks += 1;
21177 for (li, &limit) in limits.iter().enumerate() {
21178 if colors > 1 && colors <= limit {
21179 for (fi, &floor) in floors.iter().enumerate() {
21180 hit[li][fi] += usize::from(var > floor);
21181 }
21182 }
21183 }
21184 }
21185 }
21186 for li in 0..6 {
21187 for fi in 0..5 {
21188 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
21189 }
21190 }
21191 }
21192 let n = frames.len().max(1) as f64;
21193 eprintln!(
21194 "{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:",
21195 frames.len()
21196 );
21197 eprintln!(
21198 " N \\ V |{}",
21199 floors.iter().map(|f| format!("{f:>8}")).collect::<String>()
21200 );
21201 for (li, &limit) in limits.iter().enumerate() {
21202 eprintln!(
21203 " {limit:>5} |{}",
21204 (0..5)
21205 .map(|fi| format!("{:>7.1}%", acc[li][fi] / n))
21206 .collect::<String>()
21207 );
21208 }
21209 };
21210 for (name, path, seek) in native_gate_clips() {
21211 let Some((nw, nh)) = probe_dims(&path) else {
21212 eprintln!("SKIP {name}: ffprobe gave no size");
21213 continue;
21214 };
21215 let cw = nw.min(1920) / 128 * 128;
21216 let ch = nh.min(1024) / 128 * 128;
21217 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21218 let frames = clip_frames_vf(
21219 &path,
21220 &seek,
21221 &format!("crop={cw}:{ch}:{x}:{y0}"),
21222 cw,
21223 ch,
21224 12,
21225 );
21226 census(&name, &frames, cw, ch);
21227 // The 640x384 gate scales instead of cropping, and the scaling
21228 // changes the census (bars smooth out): the constants have to
21229 // separate at BOTH sizes.
21230 let small = clip_frames(&path, &seek, 640, 384, 12);
21231 census(&name, &small, 640, 384);
21232 }
21233 }
21234
21235 /// The detector against the WHOLE real library (class
21236 /// `unswept-decision-constants`, user rule "his data is the gate"):
21237 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
21238 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
21239 /// duration, four frames each, 8-bit 4:2:0, at native size or a
21240 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
21241 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
21242 /// Prints per file and offset the share of qualifying 16x16 blocks, the
21243 /// [`screen_content`] verdict and a content hint (mean luma, luma
21244 /// standard deviation, inter MAD), then sweeps the colour bound against
21245 /// the variance floor over the whole library: for each (N, V) the worst
21246 /// (highest) share among the camera/film rows against the best (lowest)
21247 /// among the screen-recording rows, so the rule with the widest gap can
21248 /// be read off. Rows carry the manifest index, codec and size only --
21249 /// no titles, no home paths.
21250 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
21251 #[test]
21252 #[ignore = "reads the real library"]
21253 fn probe_screen_library() {
21254 let _knobs = crate::speed::knob_read();
21255 if !have_ffmpeg() {
21256 eprintln!("SKIP probe_screen_library: no ffmpeg");
21257 return;
21258 }
21259 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
21260 let fixtures = crate::library_fixture::root();
21261 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
21262 else {
21263 eprintln!("SKIP probe_screen_library: no real-library manifest");
21264 return;
21265 };
21266 let limits = [4usize, 8, 16, 32, 64];
21267 let floors = [0u64, 4, 8, 16, 32, 64, 128];
21268 // Whatever ffmpeg gave us, without the exact-count assertion the
21269 // gate loaders make: a seek near the end of a clip returns fewer
21270 // frames, and that is a row to print, not a panic.
21271 let decode =
21272 |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
21273 let out = Command::new("ffmpeg")
21274 .args(["-v", "error", "-ss", seek, "-i", clip])
21275 .args(["-frames:v", &n.to_string()])
21276 .args(["-vf", vf])
21277 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
21278 .output();
21279 let Ok(out) = out else { return Vec::new() };
21280 if !out.status.success() {
21281 return Vec::new();
21282 }
21283 let (luma, chroma) = (w * h, w * h / 4);
21284 let frame_len = luma + 2 * chroma;
21285 (0..out.stdout.len() / frame_len)
21286 .map(|i| {
21287 let b = &out.stdout[i * frame_len..][..frame_len];
21288 Picture {
21289 width: w,
21290 height: h,
21291 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
21292 u: b[luma..luma + chroma]
21293 .iter()
21294 .map(|&v| u16::from(v))
21295 .collect(),
21296 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
21297 }
21298 })
21299 .collect()
21300 };
21301 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
21302 // variance > V, for every (N, V) of the sweep grid, over one frame.
21303 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
21304 let mut hit = [[0usize; 7]; 5];
21305 let mut blocks = 0usize;
21306 for by in (0..h).step_by(16) {
21307 for bx in (0..w).step_by(16) {
21308 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
21309 let mut seen = [false; 256];
21310 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
21311 for row in 0..bh {
21312 for col in 0..bw {
21313 let v = y[(by + row) * w + bx + col];
21314 sum += u64::from(v);
21315 sq += u64::from(v) * u64::from(v);
21316 if !seen[usize::from(v)] {
21317 seen[usize::from(v)] = true;
21318 colors += 1;
21319 }
21320 }
21321 }
21322 let n = (bh * bw) as u64;
21323 let var = (sq - sum * sum / n) / n;
21324 blocks += 1;
21325 for (li, &limit) in limits.iter().enumerate() {
21326 if colors > 1 && colors <= limit {
21327 for (fi, &floor) in floors.iter().enumerate() {
21328 hit[li][fi] += usize::from(var > floor);
21329 }
21330 }
21331 }
21332 }
21333 }
21334 let mut out = [[0f64; 7]; 5];
21335 for li in 0..5 {
21336 for fi in 0..7 {
21337 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
21338 }
21339 }
21340 out
21341 };
21342 // (index, label, path, duration, screen-by-its-own-content). The
21343 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
21344 // are desktop recordings; everything else in this library is camera
21345 // or film material.
21346 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
21347 for (label, file) in [
21348 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
21349 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
21350 ] {
21351 let path = fixtures.join("video").join(file);
21352 if path.exists() {
21353 rows.push((
21354 "fx".into(),
21355 label.into(),
21356 path.to_str().unwrap().into(),
21357 10.0,
21358 false,
21359 ));
21360 }
21361 }
21362 for (i, line) in manifest.lines().skip(1).enumerate() {
21363 let f: Vec<&str> = line.split('\t').collect();
21364 if f.len() < 10 {
21365 continue;
21366 }
21367 let (path, codec) = (f[0], f[2]);
21368 if codec == "-" || codec.is_empty() {
21369 continue;
21370 }
21371 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
21372 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
21373 continue;
21374 };
21375 if !std::path::Path::new(path).exists() {
21376 eprintln!("SKIP {}: file is gone", i + 1);
21377 continue;
21378 }
21379 let name = path.rsplit('/').next().unwrap_or(path);
21380 let is_capture = path.contains("/OBS/")
21381 || (name.len() > 19
21382 && name.as_bytes()[4] == b'-'
21383 && name.as_bytes()[7] == b'-'
21384 && name.as_bytes()[10] == b' '
21385 && name.as_bytes()[13] == b'-');
21386 rows.push((
21387 format!("{}", i + 1),
21388 format!("{codec} {w}x{h}"),
21389 path.to_string(),
21390 f[8].parse::<f64>().unwrap_or(0.0),
21391 is_capture,
21392 ));
21393 }
21394 // Per (N, V): the worst camera/film row and the best screen row, so
21395 // the separation of the whole library is one subtraction.
21396 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
21397 eprintln!(
21398 "| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |"
21399 );
21400 for (idx, label, path, dur, is_capture) in &rows {
21401 let Some((nw, nh)) = probe_dims(path) else {
21402 eprintln!("SKIP {idx}: ffprobe gave no size");
21403 continue;
21404 };
21405 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
21406 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21407 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
21408 let mut file_grid = [[0f64; 7]; 5];
21409 let mut file_frames = 0usize;
21410 for pct in [10u32, 50, 90] {
21411 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
21412 let frames = decode(path, &seek, &vf, cw, ch, 4);
21413 if frames.is_empty() {
21414 eprintln!(
21415 "| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |",
21416 if *is_capture { "screen" } else { "camera" }
21417 );
21418 continue;
21419 }
21420 let (mut share, mut yes, mut mean, mut sd, mut mad) =
21421 (0f64, 0usize, 0f64, 0f64, 0f64);
21422 let mut prev: Option<Vec<u8>> = None;
21423 for picture in &frames {
21424 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
21425 let grid = census(&y, cw, ch);
21426 for li in 0..5 {
21427 for fi in 0..7 {
21428 file_grid[li][fi] += grid[li][fi];
21429 }
21430 }
21431 file_frames += 1;
21432 // The shipped rule is (16 colours, var > 16): grid row 2,
21433 // floor 16 is column 3.
21434 share += grid[2][3];
21435 yes += usize::from(screen_content(&y, cw, cw, ch));
21436 let n = y.len() as f64;
21437 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
21438 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
21439 mean += sum / n;
21440 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
21441 if let Some(p) = &prev {
21442 mad += p
21443 .iter()
21444 .zip(&y)
21445 .map(|(&a, &b)| f64::from(a.abs_diff(b)))
21446 .sum::<f64>()
21447 / n;
21448 }
21449 prev = Some(y);
21450 }
21451 let f = frames.len() as f64;
21452 eprintln!(
21453 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
21454 if *is_capture { "screen" } else { "camera" },
21455 share / f,
21456 if yes * 2 > frames.len() {
21457 "SCREEN"
21458 } else {
21459 "camera"
21460 },
21461 frames.len(),
21462 mean / f,
21463 sd / f,
21464 mad / (f - 1.0).max(1.0),
21465 );
21466 }
21467 if file_frames == 0 {
21468 continue;
21469 }
21470 for li in 0..5 {
21471 for fi in 0..7 {
21472 let s = file_grid[li][fi] / file_frames as f64;
21473 match is_capture {
21474 true => scr_min[li][fi] = scr_min[li][fi].min(s),
21475 false => cam_max[li][fi] = cam_max[li][fi].max(s),
21476 }
21477 }
21478 }
21479 }
21480 eprintln!(
21481 "sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):"
21482 );
21483 eprintln!(
21484 " N \\ V |{}",
21485 floors
21486 .iter()
21487 .map(|f| format!("{:>18}", format!("V>{f}")))
21488 .collect::<String>()
21489 );
21490 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
21491 for (li, &limit) in limits.iter().enumerate() {
21492 let mut row = String::new();
21493 for fi in 0..7 {
21494 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
21495 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
21496 if s - c > best {
21497 best = s - c;
21498 best_rule = (limit, floors[fi]);
21499 }
21500 }
21501 eprintln!(" {limit:>5} |{row}");
21502 }
21503 // The threshold sits at the midpoint of the widest gap; the shipped
21504 // constant is its reciprocal in whole parts of the frame.
21505 let (li, fi) = (
21506 limits.iter().position(|&l| l == best_rule.0).unwrap(),
21507 floors.iter().position(|&f| f == best_rule.1).unwrap(),
21508 );
21509 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
21510 eprintln!(
21511 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
21512 best_rule.0,
21513 best_rule.1,
21514 best,
21515 cam_max[li][fi],
21516 scr_min[li][fi],
21517 mid,
21518 (100.0 / mid.max(0.1)).round() as usize,
21519 );
21520 }
21521
21522 /// The missing instrument: what this encoder costs against libaom and
21523 /// rav1e at matched fidelity, and how long it takes to get there.
21524 ///
21525 /// Recipe, identical on all three sides: 12 consecutive frames of each
21526 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
21527 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
21528 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
21529 /// it by default), 4:2:0 8-bit in and out. Reference points:
21530 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
21531 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
21532 /// tile_cols=1:tile_rows=1:threads=1`
21533 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
21534 /// ffmpeg-decoded frames of each encoder's own stream.
21535 ///
21536 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
21537 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
21538 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
21539 /// four encodes of that ladder together):
21540 ///
21541 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
21542 /// |---|---|---|---|---|
21543 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
21544 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
21545 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
21546 ///
21547 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
21548 /// the encoder takes -- every stream it writes is byte-identical, so the
21549 /// BD columns are this box's own re-run of the same recipe rather than a
21550 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
21551 /// rav1e). What moved is the wall of the four encodes:
21552 ///
21553 /// | clip | wall ours before | after | instructions:u before -> after |
21554 /// |---|---|---|---|
21555 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
21556 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
21557 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
21558 ///
21559 /// Three exact steps, none of which touches a coded bit: the coefficient
21560 /// rate pricer stopped rebuilding every CDF table per candidate
21561 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
21562 /// tile once per candidate (`decode::FilterReplay`), and the forward
21563 /// transform stopped transforming the all-zero residual that 70% of its
21564 /// calls carry.
21565 ///
21566 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
21567 ///
21568 /// | step | 1080p | 2160p | screen |
21569 /// |---|---|---|---|
21570 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
21571 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
21572 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
21573 ///
21574 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
21575 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
21576 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
21577 /// -- all three decided on the REAL film rows of
21578 /// [`bd_rate_screen_native`], which this downscaled recipe does not
21579 /// carry:
21580 ///
21581 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
21582 /// |---|---|---|---|
21583 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
21584 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
21585 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
21586 ///
21587 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
21588 /// DEFAULT of the sequence path this gate codes through -- the bars are
21589 /// non-screen so they take it, the capture is gated flat:
21590 ///
21591 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
21592 /// |---|---|---|---|---|
21593 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
21594 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
21595 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
21596 ///
21597 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
21598 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
21599 /// facade arm -- which is what "one mini-GOP driver, two entry points"
21600 /// means here. This downscaled recipe HATES the pyramid (as it hates
21601 /// every knob the real film rows of `bd_rate_screen_native` keep, which
21602 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
21603 /// above. The capture's row is the flat row to the byte in both runs --
21604 /// that equality IS the content gate.
21605 ///
21606 /// Loop restoration is NOT in yet: it is the one filter whose parameters
21607 /// are per restoration UNIT inside the tile payload, so it needs both
21608 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
21609 /// buffer to solve against -- neither of which this frame-header-level
21610 /// search reaches.
21611 ///
21612 /// The baseline it replaced, before an inter frame's blocks chose their
21613 /// own partition, was +501.4/+504.4/+440.9 against libaom and
21614 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
21615 ///
21616 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
21617 /// fidelity, while spending far more time than either (the partition
21618 /// search's own cost, uncut: see the two intra-pruning variants measured
21619 /// and rejected in the lane report). No
21620 /// threshold is asserted yet -- this run sets the baseline; the gate
21621 /// asserts four monotone points per ladder, and at EVERY ladder point of
21622 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
21623 /// `crate::stream::decode_stream` -- and asserts the encoder's
21624 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
21625 /// and V over every shown frame in display order. A failure names the
21626 /// clip, the q, the frame, the plane and the first differing sample.
21627 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
21628 /// which exposes no per-packet reconstruction, so that path asserts the
21629 /// two decoders against each other on all three planes.)
21630 ///
21631 /// Run:
21632 /// cargo test -p ec-av1 --release --lib -- --ignored \
21633 /// bd_rate_vs_libaom_and_rav1e --nocapture
21634 #[test]
21635 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
21636 fn bd_rate_vs_libaom_and_rav1e() {
21637 let _knobs = crate::speed::knob_write();
21638 if !have_ffmpeg() {
21639 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
21640 return;
21641 }
21642 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
21643 let fixtures = crate::library_fixture::root();
21644 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
21645 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
21646 // rows for real content (the real rows live in the native gate).
21647 for (label, name) in [
21648 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
21649 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
21650 ] {
21651 // lane-av1clipprobe: the one probe, so a missing clip is RED under
21652 // the require envs instead of a drop-with-no-escape.
21653 if let Some(path) = crate::library_fixture::require(
21654 &format!("video/{name}"),
21655 &format!("bd_rate_vs_libaom_and_rav1e: {label}"),
21656 ) {
21657 clips.push((label.to_string(), path));
21658 }
21659 }
21660 // Screen capture: the repo carries no screen-capture fixture, so take
21661 // the first OBS recording the real-library manifest names.
21662 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
21663 Ok(manifest) => {
21664 let screen = manifest
21665 .lines()
21666 .skip(1)
21667 .filter_map(|l| l.split('\t').next())
21668 .find(|p| {
21669 p.contains("/OBS/")
21670 && p.ends_with(".mkv")
21671 && std::path::Path::new(p).exists()
21672 });
21673 match screen {
21674 Some(p) => clips.push((
21675 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
21676 std::path::PathBuf::from(p),
21677 )),
21678 None => {
21679 eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
21680 }
21681 }
21682 }
21683 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
21684 }
21685 assert!(!clips.is_empty(), "no source clip available");
21686
21687 let (width, height, frames) = (640usize, 384usize, 12usize);
21688 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
21689 .iter()
21690 .map(|q| {
21691 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
21692 .map(String::from)
21693 .to_vec()
21694 })
21695 .collect();
21696 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
21697 .iter()
21698 .map(|q| {
21699 vec![
21700 "-rav1e-params".to_string(),
21701 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
21702 ]
21703 })
21704 .collect();
21705 println!(
21706 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
21707 );
21708 println!(
21709 "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"
21710 );
21711 println!("|---|---|---|---|---|");
21712 for (name, path) in &clips {
21713 let fctx = &crate::decode::FrameCtx::for_encoder();
21714 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
21715 let _ = take_partition_hits();
21716 let _ = crate::tile::take_palette_hits();
21717 SCREEN_FRAMES.iter().for_each(|c| {
21718 c.store(0, std::sync::atomic::Ordering::Relaxed);
21719 });
21720 let _ = take_uv_mode_hits();
21721 let _ = crate::tile::take_inter_mode_hits();
21722 let _ = crate::tile::take_drl_hits();
21723 let _ = crate::tile::take_ref_hits();
21724 let _ = crate::tile::take_compound_mode_hits();
21725 let _ = crate::tile::take_compound_pair_hits();
21726 let _ = crate::tile::take_compound_size_hits();
21727 let _ = crate::tile::take_compound_leaf_mode_hits();
21728 let _ = take_b64_root_hits();
21729 let _ = take_b64_residual_hits();
21730 let _ = take_b64_compound_hits();
21731 let _ = crate::motion::take_census();
21732 // The entry-surface arm: run the SAME ladder through the
21733 // streaming facade the editor's export calls, which must print
21734 // the same BD numbers as the sequence path -- byte for byte the
21735 // same stream now that both drive one mini-GOP driver
21736 // (lane-av1pyrdef).
21737 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
21738 let (ours, ours_wall) = match facade {
21739 false => our_ladder(name, &source, width, height, fctx),
21740 true => {
21741 let pyramid = crate::encoder::Pyramid::from_env();
21742 let (ladder, wall, counts, bytes, effective) =
21743 our_ladder_facade(name, &source, width, height, pyramid);
21744 eprintln!(
21745 "{name}: facade, pyramid requested {pyramid:?} effective \
21746 {effective:?} -- frames key {} arf {} leaf {} \
21747 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
21748 counts[0],
21749 counts[1],
21750 counts[2],
21751 counts[3],
21752 bytes[0],
21753 bytes[1],
21754 bytes[2],
21755 bytes[3],
21756 );
21757 (ladder, wall)
21758 }
21759 };
21760 // How often the inter split actually fired over this clip's four
21761 // encodes, against the whole 32x32 that was the only outcome
21762 // before (gate-blind-to-feature).
21763 let [whole32, split32, whole16, split16] = take_partition_hits();
21764 // Which inter modes actually fired over this clip's four encodes,
21765 // and at which DRL index -- a mode nobody picks is a mode the BD
21766 // number cannot be crediting (gate-blind-to-feature).
21767 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
21768 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
21769 let refs = crate::tile::take_ref_hits();
21770 let modes_total = (nearest + near + global + new).max(1);
21771 eprintln!(
21772 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
21773 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
21774 {drl0}/{drl1}/{drl2}/{drl3}",
21775 100.0 * nearest as f64 / modes_total as f64,
21776 100.0 * near as f64 / modes_total as f64,
21777 100.0 * global as f64 / modes_total as f64,
21778 100.0 * new as f64 / modes_total as f64,
21779 );
21780 // The compound census: what share of the coded inter blocks took
21781 // a compound reference at all, which compound mode they took, and
21782 // which pair (gate-blind-to-feature -- a compound mode nobody
21783 // picks cannot be what a BD number credits).
21784 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
21785 // superblocks were left whole at all, and how many of those coded
21786 // a residual or took a compound reference.
21787 let (roots, root_res, root_comp) = (
21788 take_b64_root_hits(),
21789 take_b64_residual_hits(),
21790 take_b64_compound_hits(),
21791 );
21792 eprintln!(
21793 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
21794 );
21795 let comp_modes = crate::tile::take_compound_mode_hits();
21796 let comp_pairs = crate::tile::take_compound_pair_hits();
21797 let comp_sizes = crate::tile::take_compound_size_hits();
21798 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
21799 let comp_total: usize = comp_modes.iter().sum();
21800 eprintln!(
21801 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
21802 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
21803 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
21804 modes_total + comp_total,
21805 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
21806 comp_modes[0],
21807 comp_modes[1],
21808 comp_modes[2],
21809 comp_modes[3],
21810 comp_modes[6],
21811 comp_modes[7],
21812 comp_pairs[3],
21813 comp_pairs[6],
21814 );
21815 eprintln!(
21816 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
21817 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
21818 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6], comp_leaf[7],
21819 );
21820 eprintln!(
21821 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
21822 comp_sizes[1], comp_sizes[2], comp_sizes[3],
21823 );
21824 // Where the wall-owning stage actually goes: how many candidate
21825 // evaluations (one `mc::predict` + SAD each) a search spends, how
21826 // many of them are subpel, and how often the winner is the seed
21827 // it started from -- the census the seeded search is judged by.
21828 let [
21829 calls,
21830 evals,
21831 subpel,
21832 rounds,
21833 near_pred,
21834 unmoved,
21835 widest,
21836 widest_moves,
21837 ] = crate::motion::take_census();
21838 let per = |n: u64| n as f64 / calls.max(1) as f64;
21839 eprintln!(
21840 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
21841 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
21842 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
21843 per(evals),
21844 100.0 * subpel as f64 / evals.max(1) as f64,
21845 per(rounds),
21846 100.0 * near_pred as f64 / calls.max(1) as f64,
21847 100.0 * unmoved as f64 / calls.max(1) as f64,
21848 );
21849 // lane-newmv, class `instrument at bound`: how often the winner
21850 // was walked to at the log stage's own WIDEST step -- a high
21851 // share means the search stops where its step lets it, not where
21852 // the content is.
21853 eprintln!(
21854 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
21855 100.0 * widest as f64 / calls.max(1) as f64,
21856 per(widest_moves),
21857 );
21858 eprintln!(
21859 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
21860 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
21861 );
21862 eprintln!(
21863 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
21864 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
21865 whole32 + split32,
21866 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
21867 whole16 + split16,
21868 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
21869 );
21870 // The deblocking level each of this clip's frames chose
21871 // (lane-av1filt): 0 everywhere would mean the filter never fires.
21872 let levels = crate::filter_search::take_chosen_levels();
21873 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
21874 let mean = |f: fn(&Chosen) -> u8| {
21875 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
21876 };
21877 eprintln!(
21878 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
21879 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
21880 levels.len(),
21881 mean(|l| l.0.0),
21882 mean(|l| l.0.1),
21883 mean(|l| l.1.0),
21884 mean(|l| l.1.1),
21885 mean(|l| l.2.0),
21886 mean(|l| l.2.1),
21887 );
21888 // How many strength presets each frame's CDEF list carried and
21889 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
21890 // everywhere would mean the per-unit choice never fires.
21891 let presets = crate::filter_search::take_cdef_presets();
21892 let mut by_bits = [0usize; 4];
21893 for (b, _) in &presets {
21894 by_bits[usize::from(*b)] += 1;
21895 }
21896 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
21897 let on_extra: usize = presets.iter().flat_map(|(_, c)| c.iter().skip(1)).sum();
21898 eprintln!(
21899 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
21900 on a non-default preset ({:.1}%)",
21901 by_bits[0],
21902 by_bits[1],
21903 by_bits[2],
21904 by_bits[3],
21905 on_extra,
21906 units,
21907 100.0 * on_extra as f64 / units.max(1) as f64
21908 );
21909 // How the 64x64 luma restoration units split between
21910 // RESTORE_NONE and Wiener (lane-av1lr).
21911 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
21912 eprintln!(
21913 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
21914 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
21915 );
21916 // Which chroma modes the search actually wins with, against the
21917 // unconditional DC_PRED that was the only outcome before
21918 // (gate-blind-to-feature).
21919 // Screen-content detection and the palette it turns on
21920 // (gate-blind-to-feature): how many frames set
21921 // `allow_screen_content_tools`, how many blocks took a palette,
21922 // and of what size. A film clip must print `screen frames on=0`.
21923 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
21924 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
21925 // Which tables the SEARCH priced against, per frame arming
21926 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
21927 // real starting ones. A film clip must show every inter arming on
21928 // the real side, a screen clip none of them.
21929 let (price_default, price_real) = crate::tile::take_pricing_hits();
21930 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
21931 let palette = crate::tile::take_palette_hits();
21932 eprintln!(
21933 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
21934 palette[0],
21935 (2..=8)
21936 .filter(|&n| palette[n] > 0)
21937 .map(|n| format!("{n}={}", palette[n]))
21938 .collect::<Vec<_>>()
21939 .join(" ")
21940 );
21941 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
21942 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
21943 // only ever fires at one magnitude is a search that never left
21944 // its first candidate (gate-blind-to-feature).
21945 // The luma angle-delta histogram (lane-av1cfl): how many
21946 // directional blocks won at each delta. All-zero would mean the
21947 // refinement never beat the base angle.
21948 let deltas = take_angle_delta_hits();
21949 if deltas.iter().sum::<usize>() > 0 {
21950 eprintln!(
21951 "{name}: angle_delta_y {}",
21952 deltas
21953 .iter()
21954 .enumerate()
21955 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
21956 .collect::<Vec<_>>()
21957 .join(" ")
21958 );
21959 }
21960 let alphas = take_cfl_alpha_hits();
21961 if alphas.iter().sum::<usize>() > 0 {
21962 eprintln!(
21963 "{name}: cfl |alpha| {}",
21964 alphas
21965 .iter()
21966 .enumerate()
21967 .filter(|&(_, &n)| n > 0)
21968 .map(|(a, &n)| format!("{a}={n}"))
21969 .collect::<Vec<_>>()
21970 .join(" ")
21971 );
21972 }
21973 let palette_uv = crate::tile::take_palette_uv_hits();
21974 eprintln!(
21975 "{name}: chroma palette blocks {} sizes {}",
21976 palette_uv[0],
21977 (2..=8)
21978 .filter(|&n| palette_uv[n] > 0)
21979 .map(|n| format!("{n}={}", palette_uv[n]))
21980 .collect::<Vec<_>>()
21981 .join(" ")
21982 );
21983 let uv = take_uv_mode_hits();
21984 let uv_total: usize = uv.iter().sum();
21985 eprintln!(
21986 "{name}: uv modes {}",
21987 uv.iter()
21988 .enumerate()
21989 .filter(|&(_, &n)| n > 0)
21990 .map(|(m, &n)| format!(
21991 "{}={n} ({:.1}%)",
21992 UV_MODE_NAMES[m],
21993 100.0 * n as f64 / uv_total.max(1) as f64
21994 ))
21995 .collect::<Vec<_>>()
21996 .join(" ")
21997 );
21998 // Which transform depth the intra blocks of this clip's key
21999 // frames resolved to (lane-av1tx): depth 0 is one transform over
22000 // the whole block, 1 and 2 its halvings.
22001 let depths = take_tx_depth_hits();
22002 let depth_total: usize = depths.iter().sum();
22003 eprintln!(
22004 "{name}: intra tx depths {}",
22005 depths
22006 .iter()
22007 .enumerate()
22008 .map(|(d, &n)| format!(
22009 "{d}={n} ({:.1}%)",
22010 100.0 * n as f64 / depth_total.max(1) as f64
22011 ))
22012 .collect::<Vec<_>>()
22013 .join(" ")
22014 );
22015 print_inter_tx_census(name);
22016 // lane-av1obmc: how many blocks actually CODED a motion_mode
22017 // symbol and which value they took, by footprint -- "OBMC is on"
22018 // as a measurement rather than a claim (class
22019 // `gate-blind-to-feature`).
22020 let mm = crate::tile::take_motion_mode_hits();
22021 eprintln!(
22022 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
22023 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
22024 eligible)",
22025 mm[0],
22026 mm[1],
22027 mm[2],
22028 mm[3],
22029 mm[4],
22030 mm[5],
22031 mm[6],
22032 mm[7],
22033 mm[8],
22034 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22035 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22036 mm.iter().sum::<usize>(),
22037 );
22038 let (aom, aom_wall) =
22039 external_ladder(&source, width, height, "libaom-av1", &aom_points);
22040 let (rav1e, rav1e_wall) =
22041 external_ladder(&source, width, height, "librav1e", &rav1e_points);
22042 assert_monotone(&format!("{name}: ours"), &ours);
22043 assert_monotone(&format!("{name}: libaom"), &aom);
22044 assert_monotone(&format!("{name}: rav1e"), &rav1e);
22045 let points = ours
22046 .iter()
22047 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22048 .collect::<Vec<_>>()
22049 .join(", ");
22050 println!(
22051 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
22052 bd_rate(&aom, &ours) * 100.0,
22053 bd_rate(&rav1e, &ours) * 100.0,
22054 );
22055 println!(
22056 "| references | libaom {} | rav1e {} | | |",
22057 aom.iter()
22058 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22059 .collect::<Vec<_>>()
22060 .join(", "),
22061 rav1e
22062 .iter()
22063 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22064 .collect::<Vec<_>>()
22065 .join(", "),
22066 );
22067 }
22068 assert_ladder_decodes();
22069 }
22070 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
22071 /// split by block class in lane-av1txdepth): depth 0 is one transform over
22072 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
22073 /// leaves and the 32x32 root, each single-reference or compound. A class
22074 /// with no counts at all never reached `commit_inter_luma` -- which is
22075 /// what its knob being off looks like (class `gate-blind-to-feature`).
22076 fn print_inter_tx_census(name: &str) {
22077 let splits = take_inter_tx_split_hits();
22078 let total: usize = splits.iter().sum();
22079 let row = |label: &str, base: usize| {
22080 let (n0, n1) = (splits[base], splits[base + 1]);
22081 format!(
22082 "{label} 0={n0} 1={n1} ({:.1}% split)",
22083 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
22084 )
22085 };
22086 eprintln!(
22087 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
22088 row("leaf single", 0),
22089 row("leaf compound", 2),
22090 row("32x32 single", 4),
22091 row("32x32 compound", 6),
22092 );
22093 // lane-txrd: which types the two searches actually COMMITTED over
22094 // this row's four encodes -- the gate could not say whether a type
22095 // search fired at all (class `gate-blind-to-feature`).
22096 const NAMES: [&str; 16] = [
22097 "IDTX",
22098 "DCT_DCT",
22099 "ADST_ADST",
22100 "ADST_DCT",
22101 "DCT_ADST",
22102 "V_DCT",
22103 "H_DCT",
22104 "FLIPADST_DCT",
22105 "DCT_FLIPADST",
22106 "FLIPADST_FLIPADST",
22107 "ADST_FLIPADST",
22108 "FLIPADST_ADST",
22109 "V_ADST",
22110 "H_ADST",
22111 "V_FLIPADST",
22112 "H_FLIPADST",
22113 ];
22114 let name_of = |t: usize| NAMES[t];
22115 for (label, hits) in [
22116 ("inter", take_inter_tx_type_hits()),
22117 ("intra", take_tx_type_hits()),
22118 ] {
22119 let total: usize = hits.iter().sum();
22120 let live: Vec<String> = hits
22121 .iter()
22122 .enumerate()
22123 .filter(|&(_, &n)| n > 0)
22124 .map(|(t, &n)| {
22125 format!(
22126 "{}={n} ({:.1}%)",
22127 name_of(t),
22128 100.0 * n as f64 / total.max(1) as f64
22129 )
22130 })
22131 .collect();
22132 eprintln!(
22133 "{name}: {label} tx_type of {total} units -- {}",
22134 live.join(" ")
22135 );
22136 }
22137 let t = take_txrd_stats();
22138 if t[0] > 0 {
22139 eprintln!(
22140 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
22141 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
22142 t[0],
22143 t[1],
22144 t[3] as f64 / 64.0,
22145 t[2],
22146 t[4] as f64 / 64.0,
22147 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
22148 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
22149 );
22150 eprintln!(
22151 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
22152 flat: dsse {:+.2}%, dbits {:+.2}%)",
22153 t[5],
22154 t[6] as f64 / 64.0,
22155 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
22156 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
22157 );
22158 }
22159 }
22160
22161 /// The video stream's coded size, from ffprobe.
22162 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
22163 crate::probe::dims(clip)
22164 }
22165
22166 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
22167 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
22168 /// superblock-aligned one, still centred and still even for 4:2:0.
22169 ///
22170 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
22171 /// superblocks by design, so no default gate row has a block the frame
22172 /// edge cuts through -- while every arbitrary export size does (3840x1608
22173 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
22174 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
22175 /// read on.
22176 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
22177 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
22178 let (w, h) = spec
22179 .split_once('x')
22180 .expect("EC_AV1_NATIVE_CROP is <width>x<height>");
22181 let (cw, ch): (usize, usize) = (
22182 w.parse().expect("crop width"),
22183 h.parse().expect("crop height"),
22184 );
22185 let (nw, nh) = crate::probe::dims(clip)?;
22186 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
22187 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
22188 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
22189 }
22190
22191 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
22192 /// with `probe_screen_detect` so the detector sweep measures exactly the
22193 /// clips the keep table is read off. Selector env vars as documented on
22194 /// the gate; a missing clip prints a SKIP and drops its row.
22195 fn native_gate_clips() -> Vec<(String, String, String)> {
22196 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
22197 let fixtures = crate::library_fixture::root();
22198 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
22199 let (film, film4k, screen) = (
22200 on("EC_AV1_NATIVE_FILM"),
22201 on("EC_AV1_NATIVE_FILM4K"),
22202 on("EC_AV1_NATIVE_SCREEN"),
22203 );
22204 // No selector at all means every clip; any selector means that subset.
22205 let all = !(film || film4k || screen);
22206 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
22207 // not film -- they print as "bars" so no reader takes them for real
22208 // content -- and the two rows below them are the real AV1 films.
22209 let mut clips: Vec<(String, String, String)> = Vec::new();
22210 for (want, label, file) in [
22211 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
22212 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
22213 ] {
22214 if !want {
22215 continue;
22216 }
22217 // lane-av1clipprobe: the one probe, so a missing clip is RED under
22218 // the require envs instead of a dropped row with no escape.
22219 if let Some(path) = crate::library_fixture::require(
22220 &format!("video/{file}"),
22221 &format!("the native BD-rate gate: {label}"),
22222 ) {
22223 clips.push((
22224 label.to_string(),
22225 path.to_str().unwrap().to_string(),
22226 "0".into(),
22227 ));
22228 }
22229 }
22230 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
22231 // The real films, taken out of the real-library manifest by codec and
22232 // coded width so no title and no home path lives in this file. Each
22233 // seek is PINNED (class `seeded fixture not reproducible`) at a
22234 // moving, non-black window -- a black leader would make every arm
22235 // read +0.000 (class `flat sample window`). Both sources are 10-bit
22236 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
22237 // what all three encoders see, so the comparison stays
22238 // encoder-vs-encoder.
22239 let pick = |width: &str| -> Option<String> {
22240 let m = manifest.as_ref().ok()?;
22241 m.lines()
22242 .skip(1)
22243 .map(|l| l.split('\t').collect::<Vec<_>>())
22244 .find(|f| {
22245 f.len() > 4
22246 && f[2] == "av1"
22247 && f[3] == width
22248 && std::path::Path::new(f[0]).exists()
22249 })
22250 .map(|f| f[0].to_string())
22251 };
22252 for (want, label, width, seek) in [
22253 (all || film, "film A (1080p source)", "1920", "00:35:00"),
22254 (
22255 all || film4k,
22256 "film B (2160p HDR source)",
22257 "3840",
22258 "00:40:00",
22259 ),
22260 ] {
22261 if !want {
22262 continue;
22263 }
22264 match pick(width) {
22265 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
22266 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
22267 }
22268 }
22269 if all || screen {
22270 match &manifest {
22271 Ok(manifest) => match manifest
22272 .lines()
22273 .skip(1)
22274 .filter_map(|l| l.split('\t').next())
22275 .find(|p| {
22276 p.contains("/OBS/")
22277 && p.ends_with(".mkv")
22278 && std::path::Path::new(p).exists()
22279 }) {
22280 Some(p) => clips.push((
22281 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
22282 p.to_string(),
22283 "0".into(),
22284 )),
22285 None => {
22286 eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
22287 }
22288 },
22289 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
22290 }
22291 }
22292 clips
22293 }
22294
22295 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
22296 /// downscales the OBS capture to 640x384, which destroys exactly the
22297 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
22298 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
22299 /// on that recipe is taken on content the tool cannot serve. This arm
22300 /// crops -- never scales -- a superblock-aligned window out of the middle
22301 /// of the capture at its own resolution (at most 1920x1024, so the wall
22302 /// stays in the minutes) and runs the same 12-frame, four-quantizer
22303 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
22304 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
22305 /// sample-exactness assertion `our_ladder` makes.
22306 ///
22307 /// It is its own `--ignored` test so the default gate's wall does not
22308 /// grow. Every variant is an environment knob, and each of those is a
22309 /// `OnceLock` read once per process, so a variant is a separate run:
22310 ///
22311 /// cargo test -p ec-av1 --release --lib -- --ignored \
22312 /// bd_rate_screen_native --nocapture # baseline
22313 /// EC_AV1_INTRABC=1 ... same command # intra block copy
22314 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
22315 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
22316 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
22317 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
22318 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
22319 ///
22320 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
22321 /// through (lane-av1pyrdef); the run prints the requested and the
22322 /// effective pyramid per clip, and a screen clip's effective one is
22323 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
22324 /// streaming facade instead, which prints the per-level frame and byte
22325 /// census and asserts ffmpeg's decode against our own decoder on all
22326 /// three planes in display order; both arms code the same bytes
22327 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
22328 ///
22329 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
22330 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
22331 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
22332 /// cost -- so every "film" column in the historical tables of this file
22333 /// is that generator, not film. The real content is `film A`, `film B`
22334 /// (native crops out of the two AV1 films the real-library manifest
22335 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
22336 /// decision only the bars rows support is not supported.
22337 ///
22338 /// Measured 2026-09-07, the five rows before and after the screen
22339 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
22340 /// BOTH real films were classified as screen content on 48/48 frames, so
22341 /// their coefficients were priced against the DEFAULT CDFs and the
22342 /// palette search ran over film; after, both are non-screen (0/48) and
22343 /// the capture is unchanged at 48/48:
22344 ///
22345 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
22346 /// |---|---|---|---|
22347 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
22348 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
22349 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
22350 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
22351 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
22352 ///
22353 /// Both bars rows and the capture are byte-identical across that change
22354 /// (their classification never moved); the palette search over film was
22355 /// costing roughly a tenth of the film rows' wall.
22356 ///
22357 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
22358 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
22359 /// the capture is gated flat and does not move a byte:
22360 ///
22361 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
22362 /// |---|---|---|---|---|
22363 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
22364 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
22365 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
22366 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
22367 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
22368 ///
22369 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
22370 /// which is the point of the shared driver: the two entry points code one
22371 /// stream. The bars rows are fixtures (recorded, never a decision); the
22372 /// two real films are what the pyramid ships for.
22373 ///
22374 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
22375 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
22376 /// setting any one of them keeps only the selected rows (the two 1080p
22377 /// rows, the two 2160p rows, the capture row respectively). A missing
22378 /// real film SKIPs its row; it never fails the gate.
22379 #[test]
22380 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
22381 fn bd_rate_screen_native() {
22382 let _knobs = crate::speed::knob_read();
22383 native_bd_arm("bd_rate_screen_native", 12, false);
22384 }
22385
22386 /// The LONG-GOP arm of the native BD gate: the same recipe as
22387 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
22388 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
22389 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
22390 /// reaches libaom as `--kf-max-dist=48` and rav1e as
22391 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
22392 /// inter pictures.
22393 ///
22394 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
22395 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
22396 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
22397 /// above 12 codes the same stream there -- the shipped `16` was measured
22398 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
22399 /// group (class `instrument at bound` / `gate blind to feature`). The
22400 /// user's exports are long GOPs, so the pyramid shape is decided here.
22401 ///
22402 /// cargo test -p ec-av1 --release --lib -- --ignored \
22403 /// bd_rate_film_long_gop --nocapture
22404 ///
22405 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
22406 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
22407 /// Read every row off the log's own "pyramid requested/effective" print,
22408 /// never off the argument order of the runs (lane-pyr3 misattributed
22409 /// three rows that way).
22410 ///
22411 /// Table: `lanes/pyr4.sweep.txt`.
22412 #[test]
22413 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
22414 fn bd_rate_film_long_gop() {
22415 let _knobs = crate::speed::knob_write();
22416 native_bd_arm("bd_rate_film_long_gop", 48, true);
22417 }
22418
22419 /// The shared driver of the two native BD arms above: `frames` pictures
22420 /// per row (the sequence's `gop` is the same number, so one key frame),
22421 /// four quantizers, `films_only` dropping every row but the two real
22422 /// films.
22423 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
22424 if !have_ffmpeg() {
22425 eprintln!("SKIP {label}: no ffmpeg");
22426 return;
22427 }
22428 let mut clips = native_gate_clips();
22429 if films_only {
22430 clips.retain(|(name, _, _)| name.starts_with("film "));
22431 }
22432 if clips.is_empty() {
22433 eprintln!("SKIP {label}: no clip");
22434 return;
22435 }
22436
22437 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
22438 .iter()
22439 .map(|q| {
22440 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
22441 .map(String::from)
22442 .to_vec()
22443 })
22444 .collect();
22445 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
22446 .iter()
22447 .map(|q| {
22448 vec![
22449 "-rav1e-params".to_string(),
22450 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
22451 ]
22452 })
22453 .collect();
22454 println!(
22455 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
22456 intrabc {}, palette maxcolors {}",
22457 armed_tiles(),
22458 crate::par::tile_threads(),
22459 intrabc_enabled(),
22460 palette_max_colors(),
22461 );
22462 println!(
22463 "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |"
22464 );
22465 println!("|---|---|---|---|---|");
22466 for (name, path, seek) in &clips {
22467 let fctx = &crate::decode::FrameCtx::for_encoder();
22468 if probe_dims(path).is_none() {
22469 eprintln!("SKIP {name}: ffprobe gave no size");
22470 continue;
22471 }
22472 // A whole number of 128-wide superblocks, at most 1920x1024, out
22473 // of the middle of the frame; the offsets stay even for 4:2:0.
22474 // ONE definition, shared with `examples/enc_probe` so the probe
22475 // cannot measure a different window than this gate (lane-probe).
22476 let (vf, cw, ch) = match native_crop_override(path) {
22477 Some(over) => over,
22478 None => crate::probe::gate_crop(path),
22479 };
22480 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
22481 SCREEN_FRAMES.iter().for_each(|c| {
22482 c.store(0, std::sync::atomic::Ordering::Relaxed);
22483 });
22484 let _ = crate::tile::take_palette_hits();
22485 let _ = crate::tile::take_palette_uv_hits();
22486 let _ = crate::tile::take_intrabc_hits();
22487 let _ = take_intrabc_search();
22488 let _ = crate::tile::take_filter_intra_hits();
22489 let _ = take_edge_census();
22490 // The sequence path itself codes the pyramid now
22491 // (lane-av1pyrdef), and prints what it requested and what the
22492 // content gate left effective.
22493 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
22494 // lane-sse: the blocks the true frame edge cuts through, and how
22495 // much of their RAW squared error sat in the padding the encoder
22496 // invented past it -- what the inside-only score stopped ranking
22497 // on. Empty on a superblock-aligned crop, which is every default
22498 // gate row (class `gate-blind-to-feature`).
22499 if edge_census() {
22500 for (side, n, inside, padding) in take_edge_census() {
22501 eprintln!(
22502 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
22503 padding_sse={padding} ({:.1}% of raw)",
22504 100.0 * padding as f64 / (inside + padding).max(1) as f64,
22505 );
22506 }
22507 }
22508 // gate-blind-to-feature: what the screen tools actually did at
22509 // native resolution, over this clip's four encodes.
22510 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
22511 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
22512 // Which tables the SEARCH priced against, per frame arming
22513 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
22514 // real starting ones. A film clip must show every inter arming on
22515 // the real side, a screen clip none of them.
22516 let (price_default, price_real) = crate::tile::take_pricing_hits();
22517 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
22518 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
22519 // superblocks stayed whole, and how many of those coded a
22520 // residual, split that residual's luma, or took a compound
22521 // reference (class `gate-blind-to-feature`).
22522 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
22523 // the superblocks offered the trial were coded whole.
22524 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
22525 eprintln!(
22526 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
22527 {i64_edge} on a superblock the frame edge cuts",
22528 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
22529 );
22530 eprintln!(
22531 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
22532 {} (search) / {} (writer); rect/AB pieces with a residual \
22533 {} (search) / {} (writer)",
22534 take_b128_none_hits(),
22535 crate::tile::take_sb128_none_hits(),
22536 take_b128_residual_hits(),
22537 crate::tile::take_sb128_residual_hits(),
22538 take_b128_rectres_hits(),
22539 crate::tile::take_sb128_rectres_hits(),
22540 );
22541 eprintln!(
22542 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
22543 take_b64_root_hits(),
22544 take_b64_residual_hits(),
22545 take_b64_var_tx_hits(),
22546 take_b64_compound_hits(),
22547 );
22548 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
22549 // of every priced block): what the deadzone quantiser handed the
22550 // RDOQ pass and what the pass changed, over every TRIAL block of
22551 // this row's four encodes -- not over the coded stream, so it is
22552 // the bits AT STAKE in the search, not in the bitstream.
22553 let rq = crate::tile::take_rdoq_stats();
22554 if rq[0] > 0 {
22555 eprintln!(
22556 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
22557 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
22558 rq[0],
22559 rq[1],
22560 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
22561 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
22562 rq[4],
22563 rq[5],
22564 rq[7] as f64 / 64.0,
22565 rq[6] as f64 / 64.0,
22566 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
22567 );
22568 }
22569 // lane-av1obmc2: the same motion_mode census the 640x384 gate
22570 // prints (class `gate-blind-to-feature`) -- how many blocks coded
22571 // the symbol at each footprint and how many took OBMC. Without it
22572 // the native table, which is the standing keep table, could not
22573 // say whether the tool fired at all.
22574 let mm = crate::tile::take_motion_mode_hits();
22575 eprintln!(
22576 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
22577 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
22578 eligible)",
22579 mm[0],
22580 mm[1],
22581 mm[2],
22582 mm[3],
22583 mm[4],
22584 mm[5],
22585 mm[6],
22586 mm[7],
22587 mm[8],
22588 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22589 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
22590 mm.iter().sum::<usize>(),
22591 );
22592 print_inter_tx_census(name);
22593 // lane-last2 (class `gate-blind-to-feature`): which reference the
22594 // 32x32-and-below inter blocks of this clip's four encodes chose.
22595 // The native table is the standing keep table, so a second past
22596 // reference that never won a block has to be visible HERE and not
22597 // only in a synthetic witness.
22598 let rh = crate::encode::take_ref_frame_hits();
22599 let rtot: usize = rh.iter().sum();
22600 eprintln!(
22601 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
22602 (LAST2 {:.1}%)",
22603 rh[1],
22604 rh[2],
22605 rh[4],
22606 rh[7],
22607 rtot,
22608 100.0 * rh[2] as f64 / rtot.max(1) as f64,
22609 );
22610 let palette = crate::tile::take_palette_hits();
22611 let palette_uv = crate::tile::take_palette_uv_hits();
22612 let ibc = crate::tile::take_intrabc_hits();
22613 let search = take_intrabc_search();
22614 eprintln!(
22615 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
22616 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
22617 won {})",
22618 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
22619 palette[0],
22620 palette_uv[0],
22621 ibc[0],
22622 search[0],
22623 search[1],
22624 search[2],
22625 );
22626 // gate-blind-to-feature: how often the five recursive filter-intra
22627 // modes actually won a block over this clip's four encodes -- a
22628 // tool that never fires is not measured by the row above it.
22629 let fi = crate::tile::take_filter_intra_hits();
22630 eprintln!(
22631 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
22632 filter_intra_on(),
22633 fi[0],
22634 fi[1],
22635 fi[2],
22636 fi[3],
22637 fi[4],
22638 fi[5],
22639 );
22640 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
22641 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
22642 assert_monotone(&format!("{name}: ours"), &ours);
22643 assert_monotone(&format!("{name}: libaom"), &aom);
22644 assert_monotone(&format!("{name}: rav1e"), &rav1e);
22645 let points = ours
22646 .iter()
22647 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
22648 .collect::<Vec<_>>()
22649 .join(", ");
22650 println!(
22651 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
22652 bd_rate(&aom, &ours) * 100.0,
22653 bd_rate(&rav1e, &ours) * 100.0,
22654 );
22655 // lane-pareto2: the two references at THEIR fast presets, plus
22656 // SVT-AV1, measured in the SAME arm as the row above -- the only
22657 // way the wall column of a Pareto table means anything (class:
22658 // wall tables are comparable only inside one interleaved batch).
22659 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
22660 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
22661 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
22662 [50, 100, 150, 200]
22663 .iter()
22664 .map(|q| {
22665 vec![
22666 "-rav1e-params".to_string(),
22667 format!(
22668 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
22669 ),
22670 ]
22671 })
22672 .collect()
22673 };
22674 let aom_at = |cu: u32| -> Vec<Vec<String>> {
22675 [5, 20, 35, 45]
22676 .iter()
22677 .map(|q| {
22678 vec![
22679 "-cpu-used".to_string(),
22680 cu.to_string(),
22681 "-b:v".to_string(),
22682 "0".to_string(),
22683 "-crf".to_string(),
22684 q.to_string(),
22685 ]
22686 })
22687 .collect()
22688 };
22689 let svt_at = |pr: u32| -> Vec<Vec<String>> {
22690 [20, 35, 45, 55]
22691 .iter()
22692 .map(|q| {
22693 vec![
22694 "-preset".to_string(),
22695 pr.to_string(),
22696 "-crf".to_string(),
22697 q.to_string(),
22698 "-svtav1-params".to_string(),
22699 "lp=1".to_string(),
22700 ]
22701 })
22702 .collect()
22703 };
22704 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
22705 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
22706 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
22707 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
22708 ];
22709 if have_encoder("libsvtav1") {
22710 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
22711 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
22712 } else {
22713 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
22714 }
22715 for (label, encoder, points) in arms {
22716 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
22717 // A REFERENCE stream our decoder cannot read is a note in
22718 // this table, not a gate failure: these rows exist to
22719 // price the references, and `assert_ladder_decodes` keeps
22720 // its teeth for the two ladders the keep table is read off.
22721 let notes =
22722 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
22723 if !notes.is_empty() {
22724 eprintln!(
22725 "{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)",
22726 notes.len()
22727 );
22728 }
22729 assert_monotone(&format!("{name}: {label}"), &lad);
22730 println!(
22731 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
22732 bd_rate(&aom, &lad) * 100.0,
22733 bd_rate(&rav1e, &lad) * 100.0,
22734 );
22735 }
22736 }
22737 }
22738 assert_ladder_decodes();
22739 }
22740
22741 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
22742 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
22743 /// on the two film clips at their native gate crop. The 2160p clip loses
22744 /// at every arm of the propagating map and the named suspect was that its
22745 /// heavily filtered flat cells give a tiny denominator, so the dependence
22746 /// ratio explodes exactly where coding is cheap; this prints the numbers
22747 /// that confirm or refute it.
22748 #[test]
22749 // Reads ONLY `fixtures/video/h264-{1080p,2160p}-23.976-8bit.mp4` -- the
22750 // COLOUR-BARS fixtures, in a centred crop. It never opens a film, so the
22751 // old reason ("the film fixtures") sent readers looking for content the
22752 // test cannot read. 0.9 s; prints the per-cell intra-MAD distribution.
22753 #[ignore = "0.9 s; reads only the fixtures/video COLOUR-BARS clips (not the films) and prints the per-cell intra-MAD distribution"]
22754 fn tpl_intra_denominator_histogram() {
22755 let _knobs = crate::speed::knob_read();
22756 if !have_ffmpeg() {
22757 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
22758 return;
22759 }
22760 for (label, file) in [
22761 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
22762 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
22763 ] {
22764 // lane-av1clipprobe: the one probe, so a missing clip is RED under
22765 // the require envs. With both clips absent this histogram used to
22766 // loop zero times and pass having printed nothing.
22767 let Some(path) = crate::library_fixture::require(
22768 &format!("video/{file}"),
22769 &format!("tpl_intra_denominator_histogram: {label}"),
22770 ) else {
22771 continue;
22772 };
22773 let path = path.to_str().unwrap();
22774 let Some((nw, nh)) = probe_dims(path) else {
22775 eprintln!("SKIP {label}: ffprobe gave no size");
22776 continue;
22777 };
22778 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
22779 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
22780 let source = clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
22781 let mut costs: Vec<f64> = Vec::new();
22782 for pic in &source {
22783 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
22784 costs.extend(
22785 super::tpl_intra_costs(&y8, cw, ch)
22786 .iter()
22787 .map(|&c| f64::from(c)),
22788 );
22789 }
22790 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
22791 let mut sorted = costs.clone();
22792 sorted.sort_by(f64::total_cmp);
22793 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
22794 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
22795 eprintln!(
22796 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
22797 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
22798 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
22799 below 1.0x {} ({:.1}%)",
22800 costs.len(),
22801 q(0.0),
22802 q(0.01),
22803 q(0.05),
22804 q(0.25),
22805 q(0.50),
22806 q(0.75),
22807 q(0.99),
22808 q(1.0),
22809 below(0.25),
22810 100.0 * below(0.25) as f64 / costs.len() as f64,
22811 below(0.5),
22812 100.0 * below(0.5) as f64 / costs.len() as f64,
22813 below(1.0),
22814 100.0 * below(1.0) as f64 / costs.len() as f64,
22815 );
22816 }
22817 }
22818
22819 /// The probe arms the gate's source (lane-probe, class `instrument
22820 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
22821 /// command line and had no `-ss`, so it read film B from frame 0 -- a
22822 /// black leader -- and coded 59 kB where the gate's own ladder point
22823 /// coded 89 kB of the same title; every census taken through it was
22824 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
22825 /// the shared loader honours the seek (arming the probe's way and the
22826 /// gate's way gives byte-identical streams, and dropping the seek does
22827 /// not), on a synthetic clip whose content moves over time.
22828 #[test]
22829 fn the_probe_arms_the_gates_source() {
22830 let _knobs = crate::speed::knob_write();
22831 if !have_ffmpeg() {
22832 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
22833 return;
22834 }
22835 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
22836 std::fs::create_dir_all(&dir).unwrap();
22837 let clip = dir.join("testsrc2.y4m");
22838 // 384x202: neither side is a multiple of 128, so the gate's centre
22839 // window is a real derivation and not the frame itself -- exactly the
22840 // shape film B has (3840x1608, never 3840x2160).
22841 let ok = Command::new("ffmpeg")
22842 .args([
22843 "-v",
22844 "error",
22845 "-y",
22846 "-f",
22847 "lavfi",
22848 "-i",
22849 "testsrc2=size=384x202:rate=10",
22850 ])
22851 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
22852 .arg(&clip)
22853 .status()
22854 .expect("ffmpeg failed to run")
22855 .success();
22856 assert!(ok, "ffmpeg could not write the synthetic clip");
22857 let path = clip.to_str().unwrap();
22858
22859 // The window: superblock-aligned, centred, even offsets.
22860 let (vf, w, h) = crate::probe::gate_crop(path);
22861 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
22862
22863 let (seek, q) = ("00:00:01", 150u8);
22864 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
22865 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
22866 assert!(
22867 gate.iter()
22868 .zip(&probe)
22869 .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
22870 "the probe's source differs from the gate's at the same window"
22871 );
22872 let bytes = |src: &[Picture]| {
22873 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
22874 .unwrap()
22875 .stream
22876 };
22877 assert_eq!(
22878 bytes(&gate),
22879 bytes(&probe),
22880 "probe and gate code different bytes"
22881 );
22882 // The two witnesses that both halves of the arming reach ffmpeg: the
22883 // seek, and the crop's own offset (the film-B defect in miniature --
22884 // the probe was reading `crop=..:568` of a 1608-high frame).
22885 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
22886 assert_ne!(
22887 bytes(&gate),
22888 bytes(&unseeked),
22889 "seeked and unseeked arming coded the same bytes -- the seek is inert"
22890 );
22891 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
22892 assert_ne!(
22893 bytes(&gate),
22894 bytes(&offset),
22895 "centred and top-aligned windows coded the same bytes -- the crop is inert"
22896 );
22897 std::fs::remove_dir_all(&dir).ok();
22898 }
22899
22900 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
22901 /// point inside the test binary, to compare against `examples/enc_probe`.
22902 #[test]
22903 // Panics on the first `env::var(...).unwrap()` when unset -- it needs FIVE
22904 // variables, not "a clip": `EC_PARITY_DIMS`, `EC_PARITY_FRAMES`,
22905 // `EC_PARITY_Q`, `EC_PARITY_CLIP`, `EC_PARITY_SS`, `EC_PARITY_VF`. Prints
22906 // one PARITY line (bytes + fnv1a of the stream) to diff against
22907 // `examples/enc_probe`.
22908 #[ignore = "diagnostic: needs EC_PARITY_{DIMS,FRAMES,Q,CLIP,SS,VF} -- all five, it unwraps the first missing one; prints one PARITY hash line"]
22909 fn probe_parity_point() {
22910 let _knobs = crate::speed::knob_write();
22911 let g = |k: &str| std::env::var(k).unwrap();
22912 let (w, h) = g("EC_PARITY_DIMS")
22913 .split_once(':')
22914 .map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap()))
22915 .unwrap();
22916 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
22917 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
22918 let source = clip_frames_vf(
22919 &g("EC_PARITY_CLIP"),
22920 &g("EC_PARITY_SS"),
22921 &g("EC_PARITY_VF"),
22922 w,
22923 h,
22924 frames,
22925 );
22926 let fctx = &crate::decode::FrameCtx::for_encoder();
22927 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
22928 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
22929 for &b in &e.stream {
22930 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
22931 }
22932 eprintln!(
22933 "PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
22934 e.stream.len(),
22935 crate::speed::speed(),
22936 crate::encoder::Pyramid::from_env(),
22937 last_sequence_pyramid()
22938 );
22939 }
22940 /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The
22941 /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`):
22942 /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in
22943 /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32
22944 /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags
22945 /// the census's far row measures were already banked by `arf_altref`.
22946 /// This census stays the PRICING arm (class `gate-blind-to-feature`): its
22947 /// best-of-two SAD shares are read against the fire share the gate census
22948 /// prints (`references ... LAST2 n (n%)`) and the refutation in
22949 /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the
22950 /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off
22951 /// `LAST`, the backward `ALTREF`, and the rate term price in.
22952 ///
22953 /// The measurement is on the gate's own window and loader (`gate_crop`,
22954 /// 12 pictures) of the two real films: every 16x16 luma block of every
22955 /// picture gets one full-pel diamond search against the NEAR reference
22956 /// and the same search against the FAR one, at the two lags the pyramid
22957 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
22958 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
22959 /// reference wins at all and by more than 10%, and -- the number the
22960 /// decision is taken on -- the total SAD of best-of-{near, far} against
22961 /// the total SAD of near alone, which is the prediction energy a second
22962 /// reference could remove before any rate is paid for naming it.
22963 ///
22964 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
22965 #[test]
22966 #[ignore = "reads the real films"]
22967 fn last2_census() {
22968 if !have_ffmpeg() {
22969 eprintln!("SKIP last2_census: no ffmpeg");
22970 return;
22971 }
22972 const SIDE: usize = 16;
22973 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
22974 // `None` when the displaced block leaves the picture.
22975 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
22976 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
22977 if sy < 0 || sx < 0 {
22978 return None;
22979 }
22980 let (sy, sx) = (sy as usize, sx as usize);
22981 if sy + SIDE > r.height || sx + SIDE > r.width {
22982 return None;
22983 }
22984 let mut acc = 0u64;
22985 for row in 0..SIDE {
22986 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
22987 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
22988 acc += c
22989 .iter()
22990 .zip(p)
22991 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
22992 .sum::<u64>();
22993 }
22994 Some(acc)
22995 };
22996 // A log-step diamond from the zero motion vector: the cheapest search
22997 // that still finds real pans. Both references get exactly this one,
22998 // so the comparison is search-fair.
22999 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
23000 let mut best = (
23001 sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX),
23002 (0isize, 0isize),
23003 );
23004 let mut step = 16isize;
23005 while step >= 1 {
23006 let centre = best.1;
23007 for (dy, dx) in [
23008 (-1, -1),
23009 (-1, 0),
23010 (-1, 1),
23011 (0, -1),
23012 (0, 1),
23013 (1, -1),
23014 (1, 0),
23015 (1, 1),
23016 ] {
23017 let mv = (centre.0 + dy * step, centre.1 + dx * step);
23018 if let Some(s) = sad(cur, r, bx, by, mv) {
23019 if s < best.0 {
23020 best = (s, mv);
23021 }
23022 }
23023 }
23024 step /= 2;
23025 }
23026 best.0
23027 };
23028 println!(
23029 "| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |"
23030 );
23031 println!("|---|---|---|---|---|---|---|---|");
23032 for (name, path, seek) in native_gate_clips() {
23033 if !name.starts_with("film ") {
23034 continue;
23035 }
23036 let (vf, cw, ch) = crate::probe::gate_crop(&path);
23037 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
23038 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
23039 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
23040 let (mut near_sad, mut best_sad) = (0u64, 0u64);
23041 for i in far..pictures.len() {
23042 let cur = &pictures[i];
23043 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
23044 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
23045 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
23046 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
23047 blocks += 1;
23048 wins += u64::from(f < n);
23049 big += u64::from(f as f64 * 1.1 < n as f64);
23050 near_sad += n;
23051 best_sad += n.min(f);
23052 }
23053 }
23054 }
23055 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
23056 println!(
23057 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
23058 pct(wins),
23059 pct(big),
23060 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
23061 );
23062 }
23063 }
23064 }
23065
23066 /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
23067 /// temporal filter of its SOURCE would take off it, priced before any
23068 /// encoder change (class `gate-blind-to-feature`).
23069 ///
23070 /// The stream census says our top ARF costs 6992 B a frame against
23071 /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
23072 /// quality, and that 61% of the gap is residual, not syntax. Two
23073 /// explanations are separable here without an encoder: our anchor
23074 /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
23075 /// the residual it codes at that lag is dominated by film grain, which no
23076 /// motion search can predict (source noise). So, per ARF position of the
23077 /// gate's own 48-picture window:
23078 ///
23079 /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
23080 /// * the same at lag 8 with the CURRENT picture temporally filtered --
23081 /// a libaom-shaped motion-compensated average of the +-2 display
23082 /// neighbours, weights `exp(-mse / strength)` -- which is the residual
23083 /// energy an ARF temporal filter would remove, and
23084 /// * PSNR of that filtered picture against the unfiltered one, the
23085 /// CEILING the filtered ARF's own PSNR is then measured under (the
23086 /// BD gate scores against the unfiltered source).
23087 ///
23088 /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
23089 /// --ignored arf_pred_census --nocapture
23090 #[test]
23091 #[ignore = "reads the real films"]
23092 fn arf_pred_census() {
23093 if !have_ffmpeg() {
23094 eprintln!("SKIP arf_pred_census: no ffmpeg");
23095 return;
23096 }
23097 const SIDE: usize = 16;
23098 let strength: f64 = std::env::var("EC_ARF_TF_S")
23099 .ok()
23100 .and_then(|v| v.parse().ok())
23101 .unwrap_or(30.0);
23102 let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
23103 // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
23104 // when the displaced block leaves the picture.
23105 let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
23106 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
23107 if sy < 0 || sx < 0 {
23108 return None;
23109 }
23110 let (sy, sx) = (sy as usize, sx as usize);
23111 if sy + SIDE > r.height || sx + SIDE > r.width {
23112 return None;
23113 }
23114 let mut acc = 0u64;
23115 for row in 0..SIDE {
23116 let c = &cur[row * cw..][..SIDE];
23117 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
23118 acc += c
23119 .iter()
23120 .zip(p)
23121 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
23122 .sum::<u64>();
23123 }
23124 Some((acc, (sy, sx)))
23125 };
23126 // The same log-step diamond `last2_census` uses, so the two censuses'
23127 // SADs are comparable.
23128 let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
23129 let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
23130 Some(v) => v,
23131 None => return (u64::MAX, (by, bx)),
23132 };
23133 let mut centre = (0isize, 0isize);
23134 let mut step = 16isize;
23135 while step >= 1 {
23136 let from = centre;
23137 for (dy, dx) in [
23138 (-1, -1),
23139 (-1, 0),
23140 (-1, 1),
23141 (0, -1),
23142 (0, 1),
23143 (1, -1),
23144 (1, 0),
23145 (1, 1),
23146 ] {
23147 let mv = (from.0 + dy * step, from.1 + dx * step);
23148 if let Some(s) = at(cur, cw, r, bx, by, mv) {
23149 if s.0 < best.0 {
23150 best = s;
23151 centre = mv;
23152 }
23153 }
23154 }
23155 step /= 2;
23156 }
23157 best
23158 };
23159 println!(
23160 "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
23161 );
23162 println!("|---|---|---|---|---|---|---|");
23163 for (name, path, seek) in native_gate_clips() {
23164 if !name.starts_with("film ") {
23165 continue;
23166 }
23167 let (vf, cw, ch) = crate::probe::gate_crop(&path);
23168 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
23169 let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
23170 let (mut tf_sse, mut tf_px) = (0f64, 0u64);
23171 for i in (8..pictures.len()).step_by(8) {
23172 arfs += 1;
23173 let cur = &pictures[i];
23174 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
23175 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
23176 let block: Vec<u16> = (0..SIDE)
23177 .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
23178 .collect();
23179 n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
23180 n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
23181 // The temporal filter: each +-2 display neighbour is
23182 // motion-compensated onto this block and averaged in
23183 // with libaom's shape, a weight that falls with the
23184 // match's own mean squared error.
23185 let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
23186 let mut wsum = 1.0f64;
23187 // `EC_ARF_TF_PAST=1` restricts the filter to the
23188 // DISPLAY-PAST neighbours -- the only ones the
23189 // encoder's own group buffer holds when it codes its
23190 // top ARF (the group's future is not buffered yet).
23191 let offs: &[isize] = match past {
23192 true => &[-2, -1],
23193 false => &[-2, -1, 1, 2],
23194 };
23195 for &d in offs {
23196 let j = i as isize + d;
23197 let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
23198 else {
23199 continue;
23200 };
23201 let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
23202 let mut sse = 0f64;
23203 for row in 0..SIDE {
23204 for col in 0..SIDE {
23205 let d = f64::from(block[row * SIDE + col])
23206 - f64::from(nb.y[(sy + row) * nb.width + sx + col]);
23207 sse += d * d;
23208 }
23209 }
23210 let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp();
23211 for row in 0..SIDE {
23212 for col in 0..SIDE {
23213 acc[row * SIDE + col] +=
23214 w * f64::from(nb.y[(sy + row) * nb.width + sx + col]);
23215 }
23216 }
23217 wsum += w;
23218 }
23219 let filtered: Vec<u16> = acc
23220 .iter()
23221 .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16)
23222 .collect();
23223 for (a, b) in filtered.iter().zip(&block) {
23224 let d = f64::from(*a) - f64::from(*b);
23225 tf_sse += d * d;
23226 }
23227 tf_px += (SIDE * SIDE) as u64;
23228 ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0;
23229 px += (SIDE * SIDE) as u64;
23230 }
23231 }
23232 }
23233 let per = |v: u64| v as f64 / px.max(1) as f64;
23234 let mse = tf_sse / tf_px.max(1) as f64;
23235 println!(
23236 "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |",
23237 per(n8),
23238 per(n4),
23239 per(ntf),
23240 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64,
23241 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(),
23242 );
23243 }
23244 }
23245
23246 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
23247 /// hardwire the REGULAR kernel, so the encoder could not have coded a
23248 /// SMOOTH or SHARP frame even if the header had said so -- the search,
23249 /// the trials, the recon and the frame header now all read
23250 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
23251 /// distinct stream (a filter that never reached the prediction would code
23252 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
23253 /// reconstructs every frame of each of them exactly, which is what proves
23254 /// the header and the prediction agree.
23255 #[test]
23256 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
23257 let _knobs = crate::speed::knob_write();
23258 if !have_ffmpeg() {
23259 eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg");
23260 return;
23261 }
23262 let (width, height) = (256usize, 128usize);
23263 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
23264 // all three kernels would code the same bytes and the test would pass
23265 // on a wiring that does nothing (class `fixture proves the symbol, not
23266 // the signal`). `panned_test_card` shifts by whole pixels, so the
23267 // search finds the sub-pel positions off the reconstruction instead:
23268 // three frames of a slow diagonal pan.
23269 let pictures: Vec<Picture> = (0..3)
23270 .map(|i| panned_test_card(width, height, i * 3))
23271 .collect();
23272 let mut streams = Vec::new();
23273 for filter in [
23274 ec_av1_syntax::InterpolationFilter::Eighttap,
23275 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
23276 ec_av1_syntax::InterpolationFilter::EighttapSharp,
23277 ] {
23278 set_frame_interp(Some(filter));
23279 let fctx = &crate::decode::FrameCtx::for_encoder();
23280 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
23281 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
23282 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
23283 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
23284 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
23285 assert_eq!(
23286 decoded.y, frame.reconstruction.y,
23287 "{filter:?} frame {i}: luma"
23288 );
23289 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
23290 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
23291 }
23292 streams.push((filter, encoded.stream));
23293 }
23294 set_frame_interp(None);
23295 for (i, (fa, a)) in streams.iter().enumerate() {
23296 for (fb, b) in &streams[i + 1..] {
23297 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
23298 }
23299 }
23300 }
23301
23302 /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
23303 /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
23304 /// residual outright (`round_to_valid_mv` rounds it away first), so the
23305 /// finest vector the encoder could commit to was a quarter pel. With the
23306 /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
23307 /// non-zero component and the search's fourth stage refines to the
23308 /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
23309 /// on arm, and -- the part that makes it a signal rather than a symbol
23310 /// count (class `fixture proves the symbol, not the signal`) -- that some
23311 /// of them come out ZERO, i.e. name a vector the off arm cannot code at
23312 /// all. Both streams are decoded by ffmpeg AND by this crate's own
23313 /// decoder and asserted sample-exact against the encoder's own
23314 /// reconstruction, which is what proves the header bit and the symbols
23315 /// agree.
23316 #[test]
23317 fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
23318 let _knobs = crate::speed::knob_write();
23319 if !have_ffmpeg() {
23320 eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg");
23321 return;
23322 }
23323 let (width, height) = (256usize, 128usize);
23324 let pictures: Vec<Picture> = (0..3)
23325 .map(|i| panned_test_card(width, height, i * 3))
23326 .collect();
23327 let mut arms = Vec::new();
23328 for hp in [false, true] {
23329 set_high_precision_mv(Some(hp));
23330 let _ = crate::tile::take_hp_symbols();
23331 let fctx = &crate::decode::FrameCtx::for_encoder();
23332 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
23333 .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
23334 let (symbols, eighth) = crate::tile::take_hp_symbols();
23335 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
23336 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
23337 assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
23338 assert_eq!(
23339 ours.len(),
23340 pictures.len(),
23341 "hp={hp}: our decoder frame count"
23342 );
23343 for (i, e) in encoded.frames.iter().enumerate() {
23344 for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
23345 if let Some((plane, s, got, want)) =
23346 first_plane_mismatch(got, &e.reconstruction)
23347 {
23348 panic!(
23349 "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
23350 the encoder reconstructed {want}"
23351 );
23352 }
23353 }
23354 }
23355 arms.push((symbols, eighth, encoded.stream));
23356 }
23357 set_high_precision_mv(None);
23358 let (off, on) = (&arms[0], &arms[1]);
23359 assert_eq!(
23360 off.0, 0,
23361 "a frame without the header bit codes no hp symbol"
23362 );
23363 assert!(
23364 on.0 > 0,
23365 "a high-precision frame codes hp symbols (got {})",
23366 on.0
23367 );
23368 assert!(
23369 on.1 > 0,
23370 "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
23371 on.0
23372 );
23373 assert_ne!(off.2, on.2, "the two arms coded the same bytes");
23374 println!(
23375 "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
23376 off.0,
23377 off.2.len(),

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