forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBfef26dfTahinli2 months ago3246 commits

encode.rs21532 lines, 979.8 KiBHistoryRawDownload
1//! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out.
2//!
3//! This is the layer that turns the pieces below it — the intra predictors of
4//! [`crate::intra`], the forward transform and quantizer of
5//! [`crate::transform`], and the tile writer of [`crate::tile`] — into
6//! something that takes a picture. Every block is 32x32 (its chroma 16x16),
7//! which is the subset the tile writer codes, and each one picks its luma mode
8//! from the seven non-directional ones by rate-distortion; chroma searches
9//! its own `uv_mode` over the seven that read no further than the row above
10//! and the column to the left, its transform type derived from that mode the
11//! way the decoder derives it. Block sizes are what a loop above this would
12//! choose between.
13//!
14//! The encoder carries its own reconstruction, because prediction reads it: a
15//! block predicts from the reconstructed samples above and to its left, exactly
16//! as the decoder will. That makes the reconstruction a claim about what a
17//! decoder produces, and it is gated as one — sample for sample against ffmpeg.
18
19use crate::decode::WithRef;
20use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
21use ec_av1_syntax::{
22 CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams,
23 LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode,
24};
25use ec_core::{Error, Result};
26
27use crate::cdf;
28use crate::cdf_state::TxbSet;
29use crate::frame::frame_obu;
30use crate::intra::{
31 D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED,
32 SMOOTH_V_PRED, V_PRED,
33};
34use crate::mc;
35use crate::motion;
36use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16};
37use crate::obu::temporal_delimiter;
38use crate::quant::ac_q;
39use crate::sequence::sequence_header_obu;
40use crate::tile::{
41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
42};
43use crate::transform::{
44 TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
45 forward_and_quantize_typed_scaled,
46};
47#[cfg(test)]
48use crate::transform::forward_and_quantize;
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").ok().and_then(|v| v.parse().ok()) {
157 Some(f) => f,
158 None => HIDDEN_LAMBDA_FACTOR,
159 }
160}
161
162/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
163/// picks it is the thing running. A release build has no such knob.
164fn lambda_scale() -> f64 {
165 let swept = std::env::var("EC_AV1_LAMBDA")
166 .ok()
167 .and_then(|v| v.parse::<f64>().ok());
168 match swept {
169 Some(scale) if cfg!(test) => scale,
170 _ => LAMBDA_SCALE,
171 }
172}
173
174/// How a key frame's lambda differs from an inter frame's: libaom weighs the
175/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
176/// of 128), because every later frame predicts from the key frame, so an error
177/// left in it is paid for over the whole group. This encoder has no temporal
178/// propagation model at all, and this factor is the cheapest stand-in for one.
179/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
180///
181/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
182/// libaom / vs rav1e:
183///
184/// | k_key | 1080p | 2160p | screen |
185/// |---|---|---|---|
186/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
187/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
188/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
189/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
190///
191/// The two films want the key frame coded finer and the screen capture wants
192/// the opposite, by about the same amount, and at native the whole lever is
193/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
194/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
195/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
196/// per-frame-type weight; the real lever here is temporal propagation
197/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
198/// predict from, not each frame.
199const KEY_LAMBDA_FACTOR: f64 = 1.0;
200
201/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
202fn key_lambda_factor() -> f64 {
203 match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) {
204 Some(k) if cfg!(test) => k,
205 _ => KEY_LAMBDA_FACTOR,
206 }
207}
208
209// Every frame's predicted coefficient bits since the last
210// `take_predicted_bits`, in coding order -- the encoder half of
211// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
212#[cfg(test)]
213thread_local! {
214 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
215}
216
217/// Records one frame's predicted coefficient bits.
218#[cfg(test)]
219fn record_predicted_bits(bits: f64) {
220 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
221}
222
223/// Takes (and clears) what the frames encoded on this thread were predicted to
224/// spend on coefficients.
225#[cfg(test)]
226pub(crate) fn take_predicted_bits() -> Vec<f64> {
227 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
228}
229
230/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
231pub(crate) const SPLIT_INTER_8: bool = true;
232
233/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
234/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
235/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
236/// turns it off for an A/B on one build.
237/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
238/// residual as one transform over the whole block or as the four transforms
239/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
240/// intra block inside the inter frame. ON since lane-av1tx2, which found why
241/// the streams desynced -- the writer counted the [`crate::decode::
242/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
243/// reader drops the term -- and measured the split search: BD-rate vs libaom
244/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
245/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
246/// A/B on one build.
247fn tx_select_inter() -> bool {
248 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
249 crate::envflags::var("EC_AV1_TX_SELECT_INTER")
250 .ok()
251 .map(|v| !matches!(v.as_str(), "0" | "off"))
252 });
253 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
254}
255
256/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`, control
257/// vs arm): the capture row goes +27.8/-26.0 -> +20.8/-30.1 -- seven points
258/// against libaom -- while BOTH film rows LOSE (film A +21.7/-4.4 ->
259/// +22.1/-4.0, film B +26.9/-0.6 -> +28.1/+0.7) and 2160p bars lose 0.8/1.1.
260/// The keep rule wants both films down, so this takes the same content gate
261/// palette, intrabc and the angle-delta refinement already stand behind: a
262/// non-screen frame is byte-identical to the encoder before the lane.
263///
264/// The transform types an intra luma transform unit of `set` may be coded
265/// with -- exactly the alphabet the writer's `tx_type` symbol names for that
266/// set, so a searched type is always one the tile can express (lane-txset).
267/// `DCT_DCT` first: it is the incumbent every other candidate has to beat.
268///
269/// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16
270/// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types
271/// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all,
272/// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT`
273/// here.
274pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
275 const DCT: [TxType; 1] = [TxType::DctDct];
276 const INTRA1: [TxType; 7] = [
277 TxType::DctDct,
278 TxType::AdstAdst,
279 TxType::AdstDct,
280 TxType::DctAdst,
281 TxType::Idtx,
282 TxType::VDct,
283 TxType::HDct,
284 ];
285 const INTRA2: [TxType; 5] = [
286 TxType::DctDct,
287 TxType::AdstAdst,
288 TxType::AdstDct,
289 TxType::DctAdst,
290 TxType::Idtx,
291 ];
292 match set {
293 TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4
294 if intra_tx_search_on(screen) =>
295 {
296 &INTRA2
297 }
298 // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the
299 // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`;
300 // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two
301 // extra members are the 1-D DCTs, and the order is the reader's own
302 // map (`decode::tx_type_from_symbol`, 8-wide CDF).
303 TxbSet::Luma8Set1 | TxbSet::Luma4Set1
304 if intra_tx_search_on(screen) =>
305 {
306 &INTRA1
307 }
308 _ => &DCT,
309 }
310}
311
312/// The transform types an INTER luma transform unit of `set` may be coded
313/// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every
314/// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3`
315/// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two
316/// types, a symbol the writer already codes and never varied. 64x64 codes no
317/// `tx_type` symbol at all, so it is not offered one.
318/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`): the
319/// capture row goes +20.8/-30.1 -> +20.1/-30.4 while the two synthetic bars
320/// rows lose TWENTY points (-1.0/-16.8 -> +23.1/+3.3 and +9.4/-12.7 ->
321/// +31.2/+3.7) and film B 0.3 -- the `local-rd-on-references` class at its
322/// loudest, and restricting the offer to 16x16 and below does not soften it
323/// (`le16`: +22.9/+3.1, +31.6/+4.0). So this takes the same content gate the
324/// intra search, palette and intrabc stand behind: a non-screen frame is
325/// byte-identical to the encoder before the lane.
326///
327/// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), `le16`
328/// (16x16 and below, the sizes libaom's own census picks a non-`DCT_DCT`
329/// inter type on -- it never takes `IDTX` at 32x32 on film B), anything else
330/// on for every frame at every size.
331pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
332 const DCT: [TxType; 1] = [TxType::DctDct];
333 const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx];
334 const INTER_WIDE: [TxType; 7] = [
335 TxType::DctDct,
336 TxType::AdstAdst,
337 TxType::AdstDct,
338 TxType::DctAdst,
339 TxType::Idtx,
340 TxType::VDct,
341 TxType::HDct,
342 ];
343 let mode = inter_tx_type_search();
344 let on = match mode {
345 InterTxSearch::Off => false,
346 InterTxSearch::Screen => screen,
347 InterTxSearch::All | InterTxSearch::Le16 => true,
348 };
349 match set {
350 TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3,
351 TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3,
352 // lane-txi: a `reduced_tx_set == 0` frame's inter 16x16 reads the
353 // TWELVE-type `TX_SET_INTER_2` and its 8x8/4x4 `ALL16` (inter 32x32
354 // stays the two-type `DCT_IDTX`). The seven offered here are the
355 // members those two alphabets SHARE with the intra set -- the four
356 // DTT combinations, `IDTX` and the two 1-D DCTs -- which is the
357 // candidate list rav1e's speed 6 prunes to; the FLIPADST family and
358 // the 1-D ADSTs are codable and left unoffered (deferred).
359 TxbSet::Luma16InterSet1 | TxbSet::Luma8InterSet1 | TxbSet::Luma4InterSet1 if on => {
360 &INTER_WIDE
361 }
362 _ => &DCT,
363 }
364}
365
366/// lane-txi: does THIS frame code `reduced_tx_set = 0` (spec 5.9.2), i.e.
367/// the wider `tx_type` alphabets at intra 8x8/4x4 and inter 16x16 and below?
368/// `EC_AV1_TXSET_WIDE`: `0`/`off`, `screen` (screen frames only), anything
369/// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated
370/// like both halves of the type search itself.
371pub(crate) fn wide_tx_set(screen: bool) -> bool {
372 match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
373 0 => return false,
374 1 => return true,
375 _ => {}
376 }
377 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
378 crate::envflags::var("EC_AV1_TXSET_WIDE").ok().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 =
401 std::sync::atomic::AtomicU8::new(u8::MAX);
402
403/// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it.
404#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
405pub(crate) fn set_wide_tx_set(on: Option<bool>) {
406 WIDE_TX_OVERRIDE.store(
407 on.map_or(u8::MAX, u8::from),
408 std::sync::atomic::Ordering::Relaxed,
409 );
410}
411
412/// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes
413/// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own
414/// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read
415/// the same alphabet or the two disagree on what a `tx_type` symbol costs.
416pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet {
417 if wide_tx_set(screen) {
418 set.wide()
419 } else {
420 set
421 }
422}
423
424#[derive(Clone, Copy, PartialEq)]
425pub(crate) enum InterTxSearch {
426 Off,
427 Screen,
428 /// 16x16 and below only.
429 Le16,
430 All,
431}
432
433/// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the
434/// environment and the preset (`u8::MAX` = unset), the shape
435/// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness
436/// that has to see a non-`DCT_DCT` inter unit turns it on through this while
437/// holding [`crate::speed::knob_write`].
438static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
439 std::sync::atomic::AtomicU8::new(u8::MAX);
440
441/// Sets [`INTER_TX_OVERRIDE`]; `None` clears it.
442#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
443pub(crate) fn set_inter_tx_search(on: Option<bool>) {
444 INTER_TX_OVERRIDE.store(
445 on.map_or(u8::MAX, u8::from),
446 std::sync::atomic::Ordering::Relaxed,
447 );
448}
449
450fn inter_tx_type_search() -> InterTxSearch {
451 match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
452 0 => return InterTxSearch::Off,
453 1 => return InterTxSearch::All,
454 _ => {}
455 }
456 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
457 crate::envflags::var("EC_AV1_TXSET_INTER").ok().map(|v| match v.as_str() {
458 "0" | "off" => InterTxSearch::Off,
459 "screen" => InterTxSearch::Screen,
460 "le16" => InterTxSearch::Le16,
461 _ => InterTxSearch::All,
462 })
463 });
464 ENV.unwrap_or_else(|| {
465 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) {
466 InterTxSearch::Screen
467 } else {
468 InterTxSearch::Off
469 }
470 })
471}
472
473/// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the
474/// 64-point one (it codes no `tx_type` symbol).
475/// lane-txw history, resolved by lane-intertx: the INTER half of the
476/// widening was blocked by `refusal-from-own-desync` twice over. Half of it
477/// was this writer coding a `V_DCT`/`H_DCT` unit as `TX_CLASS_2D`
478/// (`tile::write_coeffs`, fixed by lane-txw, which unblocked the intra
479/// half). The other half was the CHROMA inheritance: an inter block's
480/// chroma transform type is the luma type reduced to the chroma size's set
481/// (`decode::reduce_inherited_chroma_tx_type`), and (a) the encoder never
482/// set `FrameCtx::reduced_tx_set_inter`, so [`recode_inter_chroma`] reduced
483/// against a STALE allowance, and (b) `tile::write_block_planes` coded
484/// every chroma plane as `DCT_DCT`, so an inherited 1-D type desynced the
485/// chroma exactly as luma did. lane-intertx fixed both -- the frame sets
486/// its own bit on the context (`encode_inter_frame`), the writer derives
487/// the chroma type from this frame's own header bit
488/// (`reduce_inherited_chroma_tx_type_flagged`) -- and the widened SEARCH
489/// names these sets through [`luma_set_for`] at its call sites, so the
490/// wider candidates are reachable and honestly priced. The intra half
491/// never needed either (an intra block's chroma type comes off its own UV
492/// mode, never off luma).
493fn inter_luma_set(tx: usize) -> Option<TxbSet> {
494 Some(match tx {
495 4 => TxbSet::Luma4Inter,
496 8 => TxbSet::Luma8Inter,
497 16 => TxbSet::Luma16Inter,
498 32 => TxbSet::Luma32Inter,
499 _ => return None,
500 })
501}
502
503fn tx_type_search() -> bool {
504 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
505 crate::envflags::var("EC_AV1_TXSET")
506 .ok()
507 .map(|v| !matches!(v.as_str(), "0" | "off"))
508 });
509 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
510}
511
512/// Whether an intra luma unit of this frame searches its own type at all:
513/// the preset lever ([`tx_type_search`]) under the screen content gate, which
514/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global
515/// [`set_intra_tx_search`] override wins over (the witness needs the search
516/// on a frame the detector called non-screen).
517fn intra_tx_search_on(screen: bool) -> bool {
518 match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
519 0 => return false,
520 1 => return true,
521 _ => {}
522 }
523 (screen || intra_tx_all_frames()) && tx_type_search()
524}
525
526/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
527/// shape [`set_inter_tx_search`] has.
528static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
529 std::sync::atomic::AtomicU8::new(u8::MAX);
530
531/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
532#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
533pub(crate) fn set_intra_tx_search(on: Option<bool>) {
534 INTRA_TX_OVERRIDE.store(
535 on.map_or(u8::MAX, u8::from),
536 std::sync::atomic::Ordering::Relaxed,
537 );
538}
539
540/// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY
541/// frame -- the unconditional arm the gate measures -- instead of the screen
542/// content gate [`tx_type_candidates`] ships behind. Any other value keeps
543/// the gate (`0`/`off` still switches the search off entirely).
544fn intra_tx_all_frames() -> bool {
545 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
546 crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all")
547 });
548 *ENV
549}
550
551fn tx_select() -> bool {
552 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
553 crate::envflags::var("EC_AV1_TX_SELECT")
554 .ok()
555 .map(|v| !matches!(v.as_str(), "0" | "off"))
556 });
557 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
558}
559
560fn split_inter_8() -> bool {
561 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
562 Some(v) if cfg!(test) => v != "0",
563 _ => crate::speed::at(&crate::speed::SPLIT_8),
564 }
565}
566
567/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
568/// NEARESTMV candidate it always had.
569pub(crate) const LEAF_NEW_MV: bool = true;
570
571/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
572/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
573/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
574/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
575pub(crate) const EXTRA_REF_NEW_MV: bool = true;
576
577/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
578/// own best vector before that reference's `NEWMV` search is skipped: a
579/// factor on the search cost scale, `1.0` meaning "as good or better".
580/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
581/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
582/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
583/// extra searches drop from +27% to +4% of the base count -- and on screen
584/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
585/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
586/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
587/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
588/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
589/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
590/// own noise. 0.35 stays; the lever that did move at the new rate weight is
591/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
592const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
593
594/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
595fn extra_new_skip_margin() -> f64 {
596 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
597 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
598 _ => EXTRA_NEW_SKIP_MARGIN,
599 }
600}
601
602/// The margin on a LEAF's SECOND-reference motion search, the same early-out
603/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
604/// `NEWMV`: the search is skipped when that reference's own
605/// `NEAREST_NEARESTMV` vector already prices this many times better than the
606/// leaf's `LAST` search found. `0.0` never skips.
607///
608/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
609/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
610/// 2160p (38195 with no second-reference search at all):
611/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
612/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
613/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
614/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
615/// of its extra searches; past it the calls double for another -0.3/-0.5.
616/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
617/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
618/// so the margin is pure wall on that content (+10% searches at 0.8).
619///
620/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
621/// the native gate with local warp on, BD vs libaom / vs rav1e:
622///
623/// | margin | film 1080p | film 2160p | screen |
624/// |---|---|---|---|
625/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
626/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
627/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
628/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
629/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
630///
631/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
632/// with screen flat -- and it beats never-skipping, i.e. the early-out is
633/// still worth having, just at a looser margin than the old rate weight
634/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
635/// 32.6s at 2160p), which is the price of the extra second-reference
636/// searches.
637const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
638
639/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
640/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
641fn leaf_second_new_margin() -> f64 {
642 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
643 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
644 None => LEAF_SECOND_NEW_MARGIN,
645 }
646}
647
648/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
649fn leaf_second_new_mv() -> bool {
650 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
651 Some(v) => v != "0",
652 None => crate::speed::at(&crate::speed::LEAF_SECOND),
653 }
654}
655
656/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
657/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
658/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
659/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
660/// was missing was the encoder ever forming one below 32x32.
661pub(crate) const LEAF_COMPOUND: bool = true;
662
663/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
664fn leaf_compound() -> bool {
665 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
666 Some(v) => v != "0",
667 None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
668 }
669}
670
671/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
672fn leaf_new_mv() -> bool {
673 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
674 Some(v) if cfg!(test) => v != "0",
675 _ => LEAF_NEW_MV,
676 }
677}
678
679/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
680/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
681/// the true frame edge cut through was ever split there; inside the frame
682/// every block was coded whole, which left the partition decision the key
683/// frame already makes unmade for eleven frames out of twelve.
684pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
685
686/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
687/// measurement that keeps it is running (test builds only, like
688/// [`lambda_scale`]).
689fn split_inter_blocks() -> bool {
690 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
691 Some(v) if cfg!(test) => v != "0",
692 _ => crate::speed::at(&crate::speed::SPLIT_INTER),
693 }
694}
695
696/// Whether the inter search offers the whole superblock as ONE 64x64 block
697/// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32
698/// quadrants it would otherwise always split into.
699///
700/// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6
701/// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of
702/// them skip at 328 bytes a frame -- while every block this encoder wrote was
703/// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669
704/// bits against rav1e's 61,988, about 46% of the film B gap.
705///
706/// lane-tx64: no longer skip-only. The root also prices a REAL residual --
707/// one TX_64X64 luma transform (`transform.rs`'s forward network has always
708/// reached 64 points; what was missing was the block coder and the writer
709/// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`],
710/// which carries that arm's own gate table. Still refused at the 64 root:
711/// compound references, a depth-1 4x32x32 var-tx tree, intra, and a
712/// superblock the true frame edge cuts through.
713///
714/// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the
715/// root and restores the skip-only shape lane-b64 shipped.
716pub(crate) const B64_ROOT: bool = true;
717
718/// How many superblocks took the 64x64 root since the last
719/// [`take_b64_root_hits`], so a gate reports how often it fires rather than
720/// assuming it does (class `gate-blind-to-feature`).
721static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
722
723/// The 64x64-root count since the last call, and zero it.
724pub fn take_b64_root_hits() -> usize {
725 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
726}
727
728/// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at
729/// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off,
730/// which is the attribution arm for a 128-superblock stream: it separates
731/// what the SIZE costs from what the 128x128 BLOCK buys.
732fn b128_root() -> bool {
733 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
734 crate::envflags::var("EC_AV1_B128").ok().is_none_or(|v| v != "0")
735 });
736 *ENV
737}
738
739/// lane-b128r: whether the 128 root prices a REAL residual as well as the
740/// skip arm -- four TX_64X64 luma units interleaved with a TX_32X32 chroma
741/// pair per 64x64 mu chunk, var-tx depth 0 (the shape
742/// [`crate::tile::write_inter_block_128`] codes and `decode_inter_block`
743/// reads). Written, witnessed and byte-exact through both decoders, and
744/// **off by default** (`EC_AV1_B128RES=1` turns it on) because it is INERT
745/// on content: the RD takes it 0.7-1.9 times per frame against thousands of
746/// whole 128 roots (lane-b128res census, native 12-frame gate, every clip),
747/// and the BD effect is inside the noise on both gates -- long-GOP films
748/// -0.1/+0.1 and all five 12-frame rows within 0.1 of the off default.
749///
750/// The historical reason for the parking is CLOSED: the bars 2160p q=90
751/// frame 11 disagreement with ffmpeg (8 luma samples at the rows above a
752/// 128-superblock horizontal edge) was the CDEF search pricing a preset per
753/// 64x64 unit under a root that codes ONE literal for all four -- lane-
754/// edge128's `crate::tile::cdef_unit_owner` collapses the four to the one
755/// the decoder derives, and on this HEAD the same row re-measures three-way
756/// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
757/// every plane, both gates). The knob stays as the arm's gate, not as a
758/// defect flag.
759fn b128_residual() -> bool {
760 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
761 crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
762 });
763 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
764 && b128_root()
765}
766/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
767/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
768/// plus one half) -- price a REAL residual in the RD as well as the skip arm
769/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
770/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
771/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
772/// no rect/AB piece can come out non-skip, so the writer's refusal is never
773/// reached. The residual shape is the whole 128 block's, halved or quartered
774/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
775/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
776/// for any inter partition shape).
777fn rectres() -> bool {
778 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
779 crate::envflags::var("EC_AV1_RECTRES")
780 .ok()
781 .map(|v| v != "0")
782 });
783 ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
784}
785
786/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
787/// witness clip codes the shape rather than waiting for content on which the
788/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
789/// root). Never read outside `#[cfg(test)]` builds.
790static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
791 std::sync::atomic::AtomicBool::new(false);
792
793/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
794#[cfg(test)]
795pub(crate) fn force_b128_rectres(on: bool) {
796 FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
797}
798
799/// How many rect/AB pieces the search left WITH a residual rather than
800/// skipped, since the last [`take_b128_rectres_hits`] (class
801/// `gate-blind-to-feature`).
802static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
803 std::sync::atomic::AtomicUsize::new(0);
804
805/// The rect/AB-piece-residual count since the last call, and zero it.
806pub fn take_b128_rectres_hits() -> usize {
807 B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
808}
809
810/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
811/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
812/// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's
813/// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this
814/// arm's attribution control; the writer has always had the path
815/// (`write_inter_block_128` calls `write_compound_block` for a block that
816/// names a second reference).
817fn b128_compound() -> bool {
818 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
819 crate::envflags::var("EC_AV1_B128COMP").ok().map(|v| v != "0")
820 });
821 ENV.unwrap_or(true) && b128_root()
822}
823
824/// How many 128 roots came out COMPOUND since the last
825/// [`take_b128_compound_hits`] (class `gate-blind-to-feature`).
826static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize =
827 std::sync::atomic::AtomicUsize::new(0);
828
829/// The compound-128 count since the last call, and zero it.
830pub fn take_b128_compound_hits() -> usize {
831 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
832}
833
834/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ`
835/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the
836/// same skip-only single-reference/compound machinery the NONE arm ships,
837/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
838/// `EC_AV1_B128HV=0` is this arm's attribution control.
839fn b128_rect() -> bool {
840 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
841 crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0")
842 });
843 ENV.unwrap_or(true) && b128_root()
844}
845
846/// lane-rectdq: whether the delta_q symbol group is priced on the root
847/// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's
848/// attribution control (the pre-lane pricing, where a 128 rect root and the
849/// four-superblock arm were both priced as if the group were free).
850fn rectdq() -> bool {
851 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
852 crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0")
853 });
854 ENV.unwrap_or(true)
855}
856
857/// lane-rectdq: what `crate::tile::write_delta_q` spends to move
858/// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of
859/// `res` -- the same three pieces that writer codes, in its order: the
860/// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the
861/// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from
862/// exactly this row), the escape literal pair when `abs >= 3`, and the sign
863/// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`).
864pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 {
865 if res <= 0 {
866 return 0.0;
867 }
868 /// spec `DELTA_Q_SMALL`, as in the writer.
869 const DELTA_Q_SMALL: usize = 3;
870 let reduced = (target - cur) / res;
871 let abs = reduced.unsigned_abs() as usize;
872 // A pricing coder, not a sum of table entries: the escape's literal bits
873 // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB`
874 // floor, so each really costs a little over one bit (class
875 // `price-the-narrowing-not-the-table`). Read off the same
876 // `SymbolEncoder::bits` account the writer's own coder keeps.
877 let mut enc = crate::msac::SymbolEncoder::pricer();
878 enc.reset_bits();
879 enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q);
880 if abs >= DELTA_Q_SMALL {
881 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
882 enc.literal(rem_bits - 1, 3);
883 enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits);
884 }
885 if abs != 0 {
886 enc.literal(u32::from(reduced < 0), 1);
887 }
888 enc.bits()
889}
890
891/// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64
892/// superblock units): the group every root shape but a SKIPPED
893/// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for
894/// `side == write_w == write_h == sb_px` and neither a rect half nor a 64
895/// superblock under a 128 grid is that.
896///
897/// The target is the root's own cell of the `sb_q` grid, exactly the entry
898/// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search --
899/// the writer's `plan.cur` only advances at the roots that really code a
900/// group, and which those are is decided by this very comparison -- so the
901/// PREVIOUS 128 root's target in raster order stands in for it (the frame's
902/// `base_q_idx` at the first root of the frame, which is also the writer's
903/// own per-tile reset). Wrong only where a neighbouring root came out a
904/// skipped NONE block, and then only by the difference of two adjacent tpl
905/// cells.
906fn delta_q_bits_at_root(
907 sb_q: Option<&Vec<u8>>,
908 sb_cols: usize,
909 base_q_idx: u8,
910 res: i32,
911 (root_r, root_c): (usize, usize),
912) -> f64 {
913 if !rectdq() || res <= 0 {
914 return 0.0;
915 }
916 let Some(q) = sb_q.filter(|q| !q.is_empty()) else {
917 return 0.0;
918 };
919 let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]);
920 let target = at(root_r, root_c);
921 let cur = if root_c >= 2 {
922 at(root_r, root_c - 2)
923 } else if root_r >= 2 {
924 // The last 128 root of the row above, i.e. the previous one in the
925 // writer's raster walk.
926 at(root_r - 2, (sb_cols.saturating_sub(1)) & !1)
927 } else {
928 i32::from(base_q_idx)
929 };
930 delta_q_bits(target, cur, res)
931}
932
933/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
934/// halves since the last take (class `gate-blind-to-feature`).
935static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
936/// The VERT twin of [`B128_HORZ_HITS`].
937static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
938
939/// The HORZ-128-root count since the last call, and zero it.
940pub fn take_b128_horz_hits() -> usize {
941 B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
942}
943
944/// The VERT-128-root count since the last call, and zero it.
945pub fn take_b128_vert_hits() -> usize {
946 B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
947}
948
949/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off,
950/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because
951/// synthetic content is where the shape is cheapest to decode-check and the
952/// RD there prefers one whole block; the gate census is the unforced count.
953static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
954
955/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
956#[cfg(test)]
957pub(crate) fn force_b128_rect(which: u8) {
958 FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
959}
960
961/// lane-ab128: whether the 128 superblock root offers its four AB shapes --
962/// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
963/// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128
964/// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is
965/// the same skip-only single-reference/compound block the NONE and HORZ/VERT
966/// arms ship, at its own footprint ([`search_root_128_ab`],
967/// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this
968/// arm's attribution control.
969///
970/// **Off by default** (`EC_AV1_B128AB=1` turns it on): measured on both gates
971/// and it does not pay. The shapes fire 0-2 roots a frame against ~1000 coded
972/// blocks (`EC_AV1_B128_CENSUS`), and every row is flat or 0.1 worse --
973/// long-GOP film A +22.0/-8.5 against a +21.9/-8.6 control, film B +75.8/+0.8
974/// against the same, 12-frame film A +18.1/-6.2 against +18.0/-6.3, film B
975/// +23.1/-3.3 against +23.0/-3.5, screen byte-identical (lane-ab128). The
976/// machinery is written, witnessed sample-exact through both decoders on all
977/// four shapes, and kept for the arm that makes it pay: a non-skip piece (the
978/// 64x64 pieces could carry the 64 root's residual, which is where libaom's
979/// AB shapes earn their keep) or a cheaper partition price.
980fn b128_ab() -> bool {
981 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
982 crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0")
983 });
984 ENV.unwrap_or(false) && b128_root()
985}
986
987/// How many 128 roots the search left as each AB shape since the last take,
988/// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class
989/// `gate-blind-to-feature`).
990static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
991 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
992
993/// The four per-shape AB-root counts since the last call, and zero them.
994pub fn take_b128_ab_hits() -> [usize; 4] {
995 std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
996}
997
998/// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then
999/// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic
1000/// content is where the shapes are cheapest to decode-check and the RD there
1001/// prefers one whole block).
1002static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1003
1004/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7).
1005#[cfg(test)]
1006pub(crate) fn force_b128_ab(which: u8) {
1007 FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed);
1008}
1009
1010/// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
1011/// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
1012/// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =
1013/// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR.
1014/// Each entry is the piece's own top-left in mode-info units and its
1015/// footprint in samples.
1016pub(crate) fn ab128_pieces(
1017 symbol: usize,
1018 (mi_row, mi_col): (usize, usize),
1019) -> [((usize, usize), (usize, usize)); 3] {
1020 const S: usize = SUPERBLOCK;
1021 let (r, c) = (mi_row, mi_col);
1022 let (r1, c1) = (mi_row + 16, mi_col + 16);
1023 match symbol {
1024 // PARTITION_HORZ_A
1025 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))],
1026 // PARTITION_HORZ_B
1027 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))],
1028 // PARTITION_VERT_A
1029 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))],
1030 // PARTITION_VERT_B
1031 _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))],
1032 }
1033}
1034
1035/// Test-only: take the 128 root's residual arm whatever it costs, so a
1036/// witness clip codes the shape rather than waiting for content on which the
1037/// RD picks it (the same role [`force_sb128`] plays for the superblock size).
1038/// Never read outside `#[cfg(test)]` builds.
1039static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
1040 std::sync::atomic::AtomicBool::new(false);
1041
1042/// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take
1043/// the 128 root whenever it produced a candidate at all, whatever its four
1044/// cells cost, so a witness codes the block it is about rather than waiting
1045/// for content on which the root also wins its own comparison.
1046static FORCE_B128_ROOT: std::sync::atomic::AtomicBool =
1047 std::sync::atomic::AtomicBool::new(false);
1048
1049/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
1050/// forced residual block only reaches the writer if its root is taken.
1051#[cfg(test)]
1052pub(crate) fn force_b128_residual(on: bool) {
1053 FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
1054 force_b128_root(on);
1055}
1056
1057/// Arms [`FORCE_B128_ROOT`] for the rest of the process.
1058#[cfg(test)]
1059pub(crate) fn force_b128_root(on: bool) {
1060 FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed);
1061}
1062
1063/// How many 128 roots came out cheaper WITH a residual than skipped, since
1064/// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
1065static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
1066 std::sync::atomic::AtomicUsize::new(0);
1067
1068/// The 128-residual count since the last call, and zero it.
1069pub fn take_b128_residual_hits() -> usize {
1070 B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1071}
1072
1073/// How many 128x128 `PARTITION_NONE` roots the search took since the last
1074/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
1075/// is only attributable once the fire count is known.
1076static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1077
1078/// The 128x128-root count since the last call, and zero it.
1079pub fn take_b128_none_hits() -> usize {
1080 B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1081}
1082
1083/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
1084/// Preset-gated: it re-prices the block once per candidate level, so it buys
1085/// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
1086///
1087/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
1088/// which is what the byte pins are taken under when they name it.
1089fn rdoq_on() -> bool {
1090 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1091 crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0")
1092 });
1093 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
1094}
1095
1096/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in
1097/// units of one squared AC quantiser step -- the search's own
1098/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency.
1099///
1100/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`],
1101/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock
1102/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here:
1103/// corner-cut, ceiling = a superblock the temporal map weighs away from the
1104/// frame average has its coefficients optimised at the frame's weight. The
1105/// upgrade is one `lambda` field on the trial call sites, which is the whole
1106/// mode-search argument list.
1107///
1108/// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom
1109/// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above
1110/// the mode search's own weight, and it is the same multiplier on all three
1111/// rows:
1112///
1113/// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen |
1114/// |---|---|---|---|
1115/// | 0.7 | +27.6 | +39.5 | +29.6 |
1116/// | 1.0 | +26.3 | +37.5 | +29.1 |
1117/// | 1.3 | +25.6 | +37.0 | +28.8 |
1118/// | 1.6 | +24.6 | +35.9 | +28.7 |
1119/// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 |
1120/// | 3.2 | +24.7 | +36.1 | +29.4 |
1121///
1122/// A coefficient's rate is worth twice here what the mode search prices it
1123/// at, and the likeliest reason is that the price is taken against tables
1124/// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded
1125/// late in a frame whose `txb_skip`/`base` tables have narrowed really costs
1126/// less than the pricer says, and this pass is the one decision taken per
1127/// COEFFICIENT, so it feels that error most. The honest fix is an adapted
1128/// price, not a fitted multiplier; this is the fitted multiplier, and its
1129/// bowl is measured rather than assumed.
1130const RDOQ_LAMBDA_MULT: f64 = 2.2;
1131
1132/// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term
1133/// calibration sweep).
1134fn rdoq_lambda() -> f64 {
1135 static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
1136 crate::envflags::var("EC_AV1_RDOQ_LAMBDA")
1137 .ok()
1138 .and_then(|v| v.parse().ok())
1139 .unwrap_or(RDOQ_LAMBDA_MULT)
1140 });
1141 lambda_scale() * *MULT
1142}
1143
1144/// [`B64_ROOT`], or what `EC_AV1_B64` names.
1145fn b64_root() -> bool {
1146 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1147 crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0")
1148 });
1149 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
1150}
1151
1152/// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched
1153/// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64
1154/// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner)
1155/// and one TX_32X32 per chroma plane -- and compared against the four 32x32
1156/// quadrants at the same lambda, exactly the shape the inter root
1157/// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to
1158/// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`);
1159/// nothing produced one, so the key frame -- 21.6% of a real film stream --
1160/// coded every superblock split while libaom and rav1e leave 45-54% of theirs
1161/// whole.
1162///
1163/// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on
1164/// it), no filter intra (`filter_intra_size_class` has no 64 row) and no
1165/// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32
1166/// level grid, so only depth 0 is representable) -- the root is refused
1167/// outright on an `allow_intrabc` frame, whose quadrant searches carry DV
1168/// state a discarded trial would desync.
1169///
1170/// Switched off by `EC_AV1_I64=0` in any build.
1171pub(crate) const I64_ROOT: bool = true;
1172
1173/// How many key-frame superblocks were coded as one 64x64 intra block since
1174/// the last [`take_i64_root_hits`], so a gate reports the fire rate rather
1175/// than assuming it (class `gate-blind-to-feature`).
1176/// Index 1 is how many were OFFERED the trial at all, so a gate reads a
1177/// SHARE and not a bare count, and index 2 how many of the whole ones sat on
1178/// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the
1179/// `gate-blind-to-feature` guard for the edge path, which no
1180/// superblock-aligned clip fires at all.
1181static I64_HITS: [std::sync::atomic::AtomicUsize; 3] =
1182 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
1183
1184/// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the
1185/// last call, and zero them.
1186pub fn take_i64_root_hits() -> [usize; 3] {
1187 std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1188}
1189
1190/// [`I64_ROOT`], or what `EC_AV1_I64` names.
1191fn i64_root() -> bool {
1192 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1193 crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0")
1194 });
1195 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
1196}
1197
1198/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
1199/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
1200/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
1201/// lane-b64 shipped, so the two can be measured against each other on the
1202/// same build.
1203///
1204/// MEASURED on the native gate (two arms of one build, baseline reproduced to
1205/// the tenth): both film rows improve on both columns -- film A
1206/// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and
1207/// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's
1208/// +-0.3 screen clause. So the caller gates this off on a screen frame
1209/// (`allow_screen_content_tools`), the same content gate the coding pyramid
1210/// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm
1211/// already codes them for nothing, and a residual there only spends bits the
1212/// intra/palette tools would have spent better.
1213///
1214/// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` +
1215/// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on:
1216///
1217/// | | skip-only | + residual |
1218/// |---|---|---|
1219/// | 64x64 share, all frames | 36.4% | 38.3% |
1220/// | 64x64 share, leaf frames | 53.3% | 56.0% |
1221/// | skip area, all frames | 80.4% | 78.8% |
1222/// | skip area, leaf frames | 90.2% | 88.5% |
1223/// | stream bytes | 34,366 | 34,295 |
1224/// | encoder wall | 13.4s | 9.6s |
1225///
1226/// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the
1227/// TX_64X64 coefficients are really being coded. The root wins MORE often
1228/// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is
1229/// 45.2%), which is also why the arm is 28% FASTER despite costing three more
1230/// transforms per superblock: a root that wins is four quadrant searches that
1231/// never run.
1232fn b64_residual() -> bool {
1233 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1234 crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0")
1235 });
1236 ENV.unwrap_or(true) && b64_root()
1237}
1238
1239/// How many 64x64 roots came out cheaper with a residual than skipped, since
1240/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
1241/// rather than assuming one (class `gate-blind-to-feature`).
1242static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1243
1244/// The non-skip 64x64-root count since the last call, and zero it.
1245pub fn take_b64_residual_hits() -> usize {
1246 B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1247}
1248
1249/// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the
1250/// `LAST` + extra-reference pairs the 32x32 level already offers, at the
1251/// three modes a root can form without a second 64x64 motion search --
1252/// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half
1253/// is the vector `search_skip_64`'s own single-reference search already
1254/// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own
1255/// `NEWMV` vector, which only a second search per superblock produces -- the
1256/// wall this root exists to save -- so they are not offered here.
1257///
1258/// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
1259fn b64_compound() -> bool {
1260 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1261 crate::envflags::var("EC_AV1_B64COMP").ok().map(|v| v != "0")
1262 });
1263 ENV.unwrap_or(true) && b64_root()
1264}
1265
1266/// How many 64x64 roots took a COMPOUND candidate since the last
1267/// [`take_b64_compound_hits`] (class `gate-blind-to-feature`).
1268static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1269
1270/// The compound 64x64-root count since the last call, and zero it.
1271pub fn take_b64_compound_hits() -> usize {
1272 B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1273}
1274
1275/// Whether a 64x64 root that codes a residual may SPLIT its luma transform
1276/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by
1277/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by
1278/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because
1279/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose
1280/// residual has detail in the other three quadrants cannot code it at all.
1281///
1282/// Off by `EC_AV1_B64VARTX=0`.
1283fn b64_var_tx() -> bool {
1284 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1285 crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0")
1286 });
1287 ENV.unwrap_or(true) && b64_root()
1288}
1289
1290/// How many 64x64 roots split their luma transform since the last
1291/// [`take_b64_var_tx_hits`].
1292static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1293
1294/// The split-luma 64x64-root count since the last call, and zero it.
1295pub fn take_b64_var_tx_hits() -> usize {
1296 B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1297}
1298
1299/// Whether a superblock the true frame edge CUTS THROUGH may be left whole
1300/// (lane-b64b). AV1 asks only that the block's own half is inside
1301/// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already
1302/// codes that case; what was missing was a trial whose SSE is scored over the
1303/// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse)
1304/// instead of over the padding the encoder
1305/// invented past the edge. Both gate films are superblock-aligned, so this
1306/// only reaches the user's own arbitrary export sizes.
1307///
1308/// Off by `EC_AV1_B64EDGE=0`.
1309fn b64_edge() -> bool {
1310 edge_root_enabled() && b64_root()
1311}
1312
1313/// What `EC_AV1_B64EDGE` names on its own, without the inter root's own
1314/// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag
1315/// but is gated by [`i64_root`].
1316fn edge_root_enabled() -> bool {
1317 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1318 crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0")
1319 });
1320 ENV.unwrap_or(true)
1321}
1322
1323/// How many 64x64 roots the frame edge cut through since the last
1324/// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are
1325/// superblock-aligned, so nothing but a synthetic size fires this).
1326static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1327
1328/// The edge 64x64-root count since the last call, and zero it.
1329pub fn take_b64_edge_hits() -> usize {
1330 B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1331}
1332
1333/// Whether the encoder searches loop restoration at all (spec 7.17): one
1334/// Wiener filter per 64x64 luma restoration unit, picked from
1335/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
1336/// test build, like [`lambda_scale`].
1337pub(crate) const RESTORATION: bool = true;
1338
1339/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
1340fn restoration_enabled() -> bool {
1341 match std::env::var("EC_AV1_LR").ok() {
1342 Some(v) if cfg!(test) => v != "0",
1343 _ => crate::speed::at(&crate::speed::RESTORATION),
1344 }
1345}
1346
1347/// libaom's `partition_search_breakout` shape: how many non-zero luma
1348/// coefficients per 256 luma samples a block may code and still be judged
1349/// well enough predicted that the split below it is not worth trying. `0`
1350/// disables the breakout (only the existing all-skip prune applies), which
1351/// is the default until the sweep below justifies otherwise.
1352///
1353/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
1354/// is where this lane's wall would have gone: 1 cuts the three clips'
1355/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
1356/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
1357/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
1358/// encoder's inter quality lives, so `0` ships and the knob stays for a
1359/// future explicit speed preset.
1360pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
1361
1362/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
1363/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
1364/// out under `threshold * lambda` is not offered the split at all, and a
1365/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
1366/// always, as before this lever.
1367///
1368/// The census is what points here: the split trial runs on nearly every
1369/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
1370/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
1371/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
1372/// points, so the gate has to read the block's own RD cost, not its levels.
1373///
1374/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
1375/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
1376/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
1377/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
1378/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
1379/// the largest threshold whose BD stays inside the +0.3 keep rule on every
1380/// clip.
1381/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
1382/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
1383/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
1384/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
1385/// the screen wall). Neither clears the keep rule; 0.125 stays.
1386pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
1387
1388/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
1389fn split_rd_threshold() -> f64 {
1390 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
1391 crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok())
1392 });
1393 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
1394}
1395
1396/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
1397/// [`split_rd_threshold`] withholds the split trial.
1398fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
1399 split_rd_breakout_at(split_rd_threshold(), cost, side, lambda)
1400}
1401
1402/// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own
1403/// early-out reads.
1404fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool {
1405 t > 0.0 && cost < t * lambda * (side * side) as f64
1406}
1407
1408/// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`]
1409/// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64).
1410///
1411/// The 32x32 level is allowed to loosen its breakout with the speed preset
1412/// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured
1413/// what that does one size up: at 0.5 a whole superblock is taken at 64x64
1414/// without its four quadrants ever being searched, and film B goes
1415/// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the
1416/// same per-pixel threshold withholds four times as much search -- the
1417/// preset's step is priced for the 32 level and does not carry up here.
1418fn b64_breakout_threshold() -> f64 {
1419 split_rd_threshold().min(SPLIT_RD_THRESHOLD)
1420}
1421
1422/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
1423/// build.
1424fn split_breakout_coeffs() -> usize {
1425 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
1426 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
1427 _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
1428 }
1429}
1430
1431/// How often each partition decision was taken since the last
1432/// [`take_partition_hits`], so a gate can report how often a new partition
1433/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
1434/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
1435/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
1436static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
1437 std::sync::atomic::AtomicUsize::new(0),
1438 std::sync::atomic::AtomicUsize::new(0),
1439 std::sync::atomic::AtomicUsize::new(0),
1440 std::sync::atomic::AtomicUsize::new(0),
1441];
1442
1443/// Records one such decision.
1444fn partition_hit(which: usize) {
1445 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1446}
1447
1448/// Takes (and clears) the counts.
1449#[cfg(test)]
1450pub(crate) fn take_partition_hits() -> [usize; 4] {
1451 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1452}
1453
1454/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
1455/// rate-distortion trials the block search actually runs, by kind, and where
1456/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
1457/// default, and a measurement build rather than a speed one -- the census
1458/// runs the SAD pre-pass the unpruned search otherwise skips.
1459pub fn census_on() -> bool {
1460 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1461 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
1462}
1463
1464/// What each [`CENSUS`] counter counts.
1465pub const CENSUS_KINDS: [&str; 11] = [
1466 "intra blocks searched (key frame + inter leaves)",
1467 "intra luma mode trials",
1468 "chroma searches",
1469 "chroma mode trials (each = 2 plane trials)",
1470 "tx-depth trials (transform units, depth >= 1)",
1471 "inter 32x32 blocks searched",
1472 "inter block intra-mode trials",
1473 "inter mv candidates (each = 3 mc trials)",
1474 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
1475 " of those, intra won",
1476 " of those, the NEARESTMV trial coded no residual",
1477];
1478
1479/// The census counters themselves, indexed by [`CENSUS_KINDS`].
1480static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
1481 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
1482
1483/// Where the RD winner sat in the SAD ranking, for the luma intra search and
1484/// the chroma mode search -- what says whether a top-N prune would have kept
1485/// the block the search actually chose.
1486static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
1487 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
1488static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
1489 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1490
1491fn census_add(kind: usize, n: usize) {
1492 if census_on() {
1493 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
1494 }
1495}
1496
1497/// Reads (and clears) the census, so a driver can attribute it to its own encode.
1498pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
1499 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
1500 (
1501 std::array::from_fn(|i| take(&CENSUS[i])),
1502 std::array::from_fn(|i| take(&LUMA_RANK[i])),
1503 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
1504 )
1505}
1506
1507/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
1508/// first -- the census's one shared rule, so the luma and chroma histograms
1509/// mean the same thing.
1510fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
1511 scored
1512 .iter()
1513 .filter(|&&(score, mode)| {
1514 mode != winner
1515 && score
1516 < scored
1517 .iter()
1518 .find(|&&(_, m)| m == winner)
1519 .map_or(f64::INFINITY, |&(s, _)| s)
1520 })
1521 .count()
1522}
1523
1524/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
1525/// four cost less. Set from the measurement in the lane report.
1526const SPLIT_BLOCKS: bool = true;
1527
1528/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
1529/// by calling [`encode_key_frame_inner`] both ways.
1530pub(crate) fn split_blocks() -> bool {
1531 SPLIT_BLOCKS
1532}
1533
1534/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
1535/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
1536/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
1537/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
1538/// stream's decode output actually carries 10-bit precision instead of
1539/// silently losing its low 2 bits). The encoder only ever produces values in
1540/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
1541/// decision); `Plane::source` narrows right back to `u8` at its two
1542/// construction sites, a lossless round trip for that range.
1543#[derive(Clone, Debug, PartialEq, Eq)]
1544pub struct Picture {
1545 /// The picture's width in luma samples.
1546 pub width: usize,
1547 /// Its height in luma samples.
1548 pub height: usize,
1549 /// The luma plane, `width * height` samples in raster order.
1550 pub y: Vec<u16>,
1551 /// The U plane, at half the width and half the height.
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], fctx: &crate::decode::FrameCtx,
1675) {
1676 // Three heap allocations per call became three stack buffers: this runs
1677 // once per mode per trial, and an edge is at most `bw + bh` samples while
1678 // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's
1679 // 64x64 intra root predicts through here too, and reads up to `2 * bw`
1680 // samples above).
1681 let mut above_buf = [0u16; 2 * SUPERBLOCK];
1682 let mut left_buf = [0u16; 2 * SUPERBLOCK];
1683 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
1684 // trial of every block, and a 4x4 block writes 32 bytes of it. The
1685 // predictor fills every sample it is handed, so the zeros are dead
1686 // either way -- size the scratch to the block instead of to the largest
1687 // block there is.
1688
1689 let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| {
1690 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1691 *d = u16::from(v);
1692 }
1693 };
1694 if let Some(s) = above {
1695 widen(s, &mut above_buf);
1696 }
1697 if let Some(s) = left {
1698 widen(s, &mut left_buf);
1699 }
1700 let above16 = above.map(|s| &above_buf[..s.len()]);
1701 let left16 = left.map(|s| &left_buf[..s.len()]);
1702 let mut run = |dst16: &mut [u16]| {
1703 crate::intra::predict(
1704 mode,
1705 angle_delta,
1706 above16,
1707 left16,
1708 corner.map(u16::from),
1709 bw,
1710 bh,
1711 enable_edge_filter,
1712 smooth_neighbor,
1713 dst16, fctx,
1714 );
1715 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
1716 *d = s as u8;
1717 }
1718 };
1719 let n = bw * bh;
1720 if n <= 64 {
1721 run(&mut [0u16; 64][..n]);
1722 } else if n <= 256 {
1723 run(&mut [0u16; 256][..n]);
1724 } else if n <= BLOCK * BLOCK {
1725 run(&mut [0u16; BLOCK * BLOCK][..n]);
1726 } else {
1727 run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]);
1728 }
1729}
1730
1731/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
1732/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
1733/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
1734fn filter_intra_predict_u8(
1735 mode: usize,
1736 above: Option<&[u8]>,
1737 left: Option<&[u8]>,
1738 corner: Option<u8>,
1739 side: usize,
1740 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1741) {
1742 let mut above_buf = [0u16; 2 * BLOCK];
1743 let mut left_buf = [0u16; 2 * BLOCK];
1744 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
1745 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1746 *d = u16::from(v);
1747 }
1748 };
1749 if let Some(a) = above {
1750 widen(a, &mut above_buf);
1751 }
1752 if let Some(l) = left {
1753 widen(l, &mut left_buf);
1754 }
1755 let mut dst16 = [0u16; BLOCK * BLOCK];
1756 let n = side * side;
1757 crate::intra::predict_filter_intra(
1758 mode,
1759 above.map(|a| &above_buf[..a.len()]),
1760 left.map(|l| &left_buf[..l.len()]),
1761 corner.map(u16::from),
1762 side,
1763 side,
1764 &mut dst16[..n], fctx,
1765 );
1766 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
1767 *d = v as u8;
1768 }
1769}
1770
1771/// Pads one plane to `(padded_width, padded_height)` by repeating its last
1772/// row and column, so the block coder always sees a whole number of blocks.
1773/// [`crop_plane`] undoes this on the way back out.
1774fn pad_plane<T: Copy + Default>(
1775 source: &[T],
1776 width: usize,
1777 height: usize,
1778 padded_width: usize,
1779 padded_height: usize,
1780) -> Vec<T> {
1781 let mut out = vec![T::default(); padded_width * padded_height];
1782 for row in 0..padded_height {
1783 let src = source[row.min(height - 1) * width..][..width].as_ref();
1784 let dst = &mut out[row * padded_width..][..padded_width];
1785 dst[..width].copy_from_slice(src);
1786 dst[width..].fill(src[width - 1]);
1787 }
1788 out
1789}
1790
1791/// The top-left `width` x `height` region of a plane that is `padded_width`
1792/// wide, which is the render-size crop [`Picture::padded`]'s replication
1793/// exists to let a decoder undo.
1794fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
1795 let mut out = Vec::with_capacity(width * height);
1796 for row in 0..height {
1797 out.extend_from_slice(&source[row * padded_width..][..width]);
1798 }
1799 out
1800}
1801
1802/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
1803/// region a decoder produces, which is the public contract for what a caller
1804/// sees back — the padded planes the encoder coded against never leave this
1805/// module. Identity when the reconstruction is already that size.
1806pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1807 let reconstruction = &encoded.reconstruction;
1808 let cropped = if reconstruction.width == width && reconstruction.height == height {
1809 reconstruction.clone()
1810 } else {
1811 Picture {
1812 width,
1813 height,
1814 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1815 u: crop_plane(
1816 &reconstruction.u,
1817 reconstruction.width / 2,
1818 width / 2,
1819 height / 2,
1820 ),
1821 v: crop_plane(
1822 &reconstruction.v,
1823 reconstruction.width / 2,
1824 width / 2,
1825 height / 2,
1826 ),
1827 }
1828 };
1829 Encoded {
1830 stream: encoded.stream.clone(),
1831 modes: encoded.modes.clone(),
1832 inter_block_share: encoded.inter_block_share,
1833 reconstruction: cropped,
1834 tile: encoded.tile.clone(),
1835 mi_cols: encoded.mi_cols,
1836 mi_rows: encoded.mi_rows,
1837 base_q_idx: encoded.base_q_idx,
1838 tx_select: encoded.tx_select,
1839 switchable_motion_mode: encoded.switchable_motion_mode,
1840 screen: encoded.screen,
1841 reduced_tx_set: encoded.reduced_tx_set,
1842 start_cdfs: encoded.start_cdfs.clone(),
1843 next_cdfs: encoded.next_cdfs.clone(),
1844 loop_filter: encoded.loop_filter,
1845 loop_restoration: encoded.loop_restoration,
1846 allow_intrabc: encoded.allow_intrabc,
1847 delta: encoded.delta.clone(),
1848 cdef: encoded.cdef,
1849 }
1850}
1851
1852/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1853/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1854#[derive(Clone)]
1855pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1856
1857impl std::fmt::Debug for CdfSnapshot {
1858 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1859 f.write_str("CdfSnapshot")
1860 }
1861}
1862
1863/// What one call to [`encode_key_frame`] produced.
1864#[derive(Clone, Debug)]
1865pub struct Encoded {
1866 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1867 /// OBU carrying one tile.
1868 pub stream: Vec<u8>,
1869 /// What a decoder will produce from `stream` — the encoder's own
1870 /// reconstruction, which its prediction was built on.
1871 pub reconstruction: Picture,
1872 /// The luma intra mode each block was coded under, in the order the blocks
1873 /// are coded — raster order among the quadrants of each superblock, and
1874 /// among the four 16x16 blocks of a quadrant that was split.
1875 pub modes: Vec<u8>,
1876 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1877 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1878 /// for a key frame, which has no such choice — so a caller can tell a
1879 /// frame with no motion worth coding from one that never got the chance.
1880 pub inter_block_share: f64,
1881 /// The tile payload alone, undecorated by any OBU framing, and the frame
1882 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1883 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1884 /// off the wire by parsing `stream`'s OBUs instead.
1885 pub(crate) tile: Vec<u8>,
1886 pub(crate) mi_cols: u32,
1887 pub(crate) mi_rows: u32,
1888 pub(crate) base_q_idx: u8,
1889 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1890 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1891 /// and reading it off `stream`'s header is what `decode_stream` does. A
1892 /// test that decodes `tile` directly must pass this one along, or it reads
1893 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1894 /// block.
1895 pub(crate) tx_select: bool,
1896 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1897 /// bit that makes every eligible single-reference inter block carry a
1898 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1899 /// decoding `tile` directly must pass it along or it desyncs at the
1900 /// first eligible block.
1901 pub(crate) switchable_motion_mode: bool,
1902 /// The CDF state this frame's tile writer started from -- the defaults
1903 /// for a key frame and for the first inter frame, and the previous
1904 /// frame's stored tables after that. A test that decodes `tile` directly
1905 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1906 /// the frame's `primary_ref_frame` slot holds (same class as
1907 /// `tx_select`: a header bit a raw tile decode cannot guess).
1908 pub(crate) start_cdfs: CdfSnapshot,
1909 /// What this frame stores into the slots it refreshes (spec 7.20,
1910 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1911 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1912 /// started from when it is on.
1913 pub(crate) next_cdfs: CdfSnapshot,
1914 /// This frame header's chosen deblocking parameters
1915 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1916 /// picture the decoder produces UNDER them, so a test that decodes
1917 /// `tile` directly must pass these along, exactly as it must `tx_select`
1918 /// (class: test asserts against a stale header).
1919 pub(crate) loop_filter: LoopFilterParams,
1920 /// This frame header's chosen CDEF parameters, threaded for the same
1921 /// reason as `loop_filter`.
1922 pub(crate) cdef: CdefParams,
1923 /// This frame header's `allow_screen_content_tools`
1924 /// ([`screen_content`]) -- every intra block of the tile carries the two
1925 /// palette-mode symbols under it, so a raw tile decode that guessed
1926 /// `false` would desync at the first block (same class as `tx_select`).
1927 pub(crate) screen: bool,
1928 /// This frame header's own `reduced_tx_set` (spec 5.9.2) -- the bit that
1929 /// picks the inter `tx_type` alphabets AND, on an inter block, the
1930 /// allowance the chroma transform's inherited type reduces against
1931 /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). A raw tile
1932 /// decode that guesses `true` here mis-derives every inherited chroma
1933 /// type on a `reduced_tx_set = 0` frame (lane-intertx; same class as
1934 /// `tx_select`/`screen` above).
1935 pub(crate) reduced_tx_set: bool,
1936 /// This frame header's chosen loop restoration parameters, threaded for
1937 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1938 /// filters themselves are coded in `tile`, so a decode of it under a
1939 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1940 pub(crate) loop_restoration: LoopRestorationParams,
1941 /// This frame header's `allow_intrabc` -- every intra block of the tile
1942 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1943 /// guessed `false` would desync at the first block (same class as
1944 /// `screen`/`tx_select`).
1945 pub(crate) allow_intrabc: bool,
1946 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1947 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1948 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1949 /// decode that guessed the defaults desyncs at the first superblock
1950 /// (same class as `screen`/`tx_select`).
1951 pub(crate) delta: ec_av1_syntax::DeltaParams,
1952}
1953
1954thread_local! {
1955 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
1956 /// for on the last key frame encoded on this thread -- read by the gates,
1957 /// which print it beside the block counts (class `gate-blind-to-feature`).
1958 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
1959}
1960
1961/// [`IBC_SHARE`] for the last key frame encoded on this thread.
1962#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1963pub(crate) fn intrabc_source_share() -> f64 {
1964 IBC_SHARE.with(std::cell::Cell::get)
1965}
1966
1967thread_local! {
1968 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
1969 /// header offers the per-frame `allow_screen_content_tools` bit at all.
1970 /// Armed once by the key frame ([`encode_key_frame_inner`], from
1971 /// [`screen_content`]) and read by every header builder after it, so that
1972 /// the inter frames of a screen sequence lay their headers out the same
1973 /// way the sequence header the key frame wrote says they do -- a per-call
1974 /// parameter would have to thread through `inter_frame_headers`' four
1975 /// public entry points and every hand-built-stream test that calls them.
1976 /// A sequence with no screen content leaves this false and writes exactly
1977 /// the bits it wrote before this lane.
1978 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1979}
1980
1981thread_local! {
1982 /// Overrides [`screen_content`] for the calling thread, which is what the
1983 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
1984 /// codes every block losslessly, so both arms of a mode ablation reach
1985 /// infinite PSNR and the ablation measures nothing at all (the
1986 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
1987 /// variable cannot do this -- the tests run in one process, in parallel.
1988 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1989}
1990
1991thread_local! {
1992 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
1993 /// under, AFTER the content gate: the pyramid, or `None` for a stream
1994 /// that stayed flat. Read by the BD gates, which print the requested and
1995 /// the effective pyramid side by side -- a screen clip requests one and
1996 /// codes flat, and that difference is the gate (class
1997 /// `gate-blind-to-feature`).
1998 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
1999 const { std::cell::Cell::new(None) };
2000}
2001
2002/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
2003#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2004pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
2005 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
2006}
2007
2008#[cfg(test)]
2009pub(crate) fn force_screen(value: Option<bool>) {
2010 SCREEN_FORCE.with(|c| c.set(value));
2011}
2012
2013// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
2014// ablation can measure the mode search alone. Setting it also clears the
2015// sequence header's own `enable_filter_intra` bit, so the stream the arm
2016// writes is exactly the one this encoder wrote before the lane.
2017#[cfg(test)]
2018thread_local! {
2019 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2020}
2021
2022#[cfg(test)]
2023pub(crate) fn force_filter_intra(value: Option<bool>) {
2024 FILTER_INTRA_FORCE.with(|c| c.set(value));
2025}
2026
2027pub(crate) fn arm_seq_screen(on: bool) {
2028 SEQ_SCREEN.with(|c| c.set(on));
2029}
2030
2031fn seq_screen() -> bool {
2032 SEQ_SCREEN.with(std::cell::Cell::get)
2033}
2034
2035/// How many distinct colours a 16x16 luma block may hold and still count as
2036/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
2037/// `av1_set_screen_content_options` bound is 4, which separates nothing on
2038/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
2039/// the variance floor below on the five gate clips at BOTH the native crop
2040/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
2041/// the frame is the widest-margin split of those ten rows -- every
2042/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
2043/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
2044/// native and 17.9% scaled.
2045fn screen_colors() -> usize {
2046 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2047 *N.get_or_init(|| {
2048 std::env::var("EC_AV1_SCREEN_COLORS")
2049 .ok()
2050 .and_then(|v| v.parse().ok())
2051 .unwrap_or(16)
2052 })
2053}
2054
2055/// The reciprocal of the frame area those blocks must cover, in tenths --
2056/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
2057/// 8 (an eighth) is the midpoint of the two populations
2058/// `probe_screen_detect` measures at the colour bound and variance floor
2059/// around it. `EC_AV1_SCREEN_PCT`.
2060fn screen_pct() -> usize {
2061 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2062 *N.get_or_init(|| {
2063 std::env::var("EC_AV1_SCREEN_PCT")
2064 .ok()
2065 .and_then(|v| v.parse().ok())
2066 .unwrap_or(10)
2067 })
2068}
2069
2070/// The per-pixel variance a few-colour block must clear before it counts as
2071/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
2072/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
2073/// a smooth dark film frame is all few-colour blocks and reads as a desktop
2074/// capture -- which is exactly what this detector did until 2026-09-07, when
2075/// it called BOTH real films screen content on 48/48 frames, priced every
2076/// coefficient against the default CDFs and ran the palette search over
2077/// film. `probe_screen_detect`: at 16 colours the floor takes both films
2078/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
2079/// 23.6%.
2080fn screen_var() -> u64 {
2081 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
2082 *N.get_or_init(|| {
2083 std::env::var("EC_AV1_SCREEN_VAR")
2084 .ok()
2085 .and_then(|v| v.parse().ok())
2086 .unwrap_or(16)
2087 })
2088}
2089
2090/// How many frames [`screen_content`] said yes/no to, so a gate can print
2091/// whether the detector fired at all (class `gate-blind-to-feature`).
2092pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
2093 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2094
2095/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
2096/// the distinct colours of every 16x16 block and turn the screen-content
2097/// tools on when the blocks holding between 2 and [`screen_colors`] of them
2098/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
2099/// frame. `width` is the plane's
2100/// stride, `true_*` the frame's real (decodable) extent.
2101fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
2102 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
2103 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2104 return forced;
2105 }
2106 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
2107 let on = v != "0";
2108 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2109 return on;
2110 }
2111 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
2112 let mut counted = 0usize;
2113 for by in (0..true_height).step_by(blk) {
2114 for bx in (0..true_width).step_by(blk) {
2115 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
2116 let mut seen = [false; 256];
2117 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
2118 for row in 0..h {
2119 for col in 0..w {
2120 let v = y[(by + row) * width + bx + col];
2121 sum += u64::from(v);
2122 sq += u64::from(v) * u64::from(v);
2123 if !seen[usize::from(v)] {
2124 seen[usize::from(v)] = true;
2125 colors += 1;
2126 }
2127 }
2128 }
2129 // Per-pixel variance over the block's real (edge-clipped) extent.
2130 let n = (h * w) as u64;
2131 let var = (sq - sum * sum / n) / n;
2132 if colors > 1 && colors <= limit && var > floor {
2133 counted += 1;
2134 }
2135 }
2136 }
2137 let on = counted * blk * blk * screen_pct() > true_width * true_height;
2138 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2139 on
2140}
2141
2142/// Whether this SOURCE picture reads as screen content, for a caller that has
2143/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
2144/// gates its coding pyramid on this (a desktop capture keeps the flat
2145/// one-in-one-out structure the BD gate measured it on, camera material takes
2146/// the mini-GOP). The key frame runs the same detector again when it builds
2147/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
2148/// count, so this probe undoes its own tick and leaves the gate prints
2149/// reading one detection per coded frame.
2150pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
2151 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
2152 let on = screen_content(&y, picture.width, picture.width, picture.height);
2153 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2154 on
2155}
2156
2157/// The sequence and frame headers a picture of this size is coded under: one
2158/// tile, one transform size per block, no in-loop filter parameters yet
2159/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
2160/// CDEF strengths in once the tile is coded), no CDF adaptation
2161/// and no tool the tile writer does not code.
2162///
2163/// # Errors
2164/// Returns an error when the picture is larger than the 16-bit frame size the
2165/// sequence header carries.
2166pub fn key_frame_headers(
2167 width: usize,
2168 height: usize,
2169 base_q_idx: u8,
2170) -> Result<(SequenceHeader, FrameHeader)> {
2171 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
2172}
2173
2174/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
2175/// studio (limited) range: what this crate's sequence header carried before
2176/// [`crate::encoder`]'s facade could configure it, and what
2177/// [`key_frame_headers`] still asks for.
2178fn unspecified_color_config() -> ColorConfig {
2179 ColorConfig {
2180 bit_depth: 8,
2181 mono_chrome: false,
2182 num_planes: 3,
2183 color_primaries: 2,
2184 transfer_characteristics: 2,
2185 matrix_coefficients: 2,
2186 color_range: false,
2187 subsampling_x: 1,
2188 subsampling_y: 1,
2189 chroma_sample_position: ChromaSamplePosition::Unknown,
2190 separate_uv_delta_q: false,
2191 }
2192}
2193
2194/// [`key_frame_headers`] with the sequence header's colour config named
2195/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
2196/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
2197/// which is all a player picks a colour transform from and which
2198/// [`crate::encoder::Colour`] is the facade's own name for.
2199///
2200/// # Errors
2201/// The same as [`key_frame_headers`].
2202pub(crate) fn key_frame_headers_colour(
2203 width: usize,
2204 height: usize,
2205 base_q_idx: u8,
2206 color_config: ColorConfig,
2207) -> Result<(SequenceHeader, FrameHeader)> {
2208 let bits = |n: usize| -> Result<u32> {
2209 let n = u32::try_from(n).map_err(|_| too_large())?;
2210 if n == 0 || n > 1 << 16 {
2211 return Err(too_large());
2212 }
2213 Ok((32 - (n - 1).leading_zeros()).max(1))
2214 };
2215 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
2216 let (w, h) = (width as u32, height as u32);
2217 let seq = SequenceHeader {
2218 seq_profile: 0,
2219 operating_points: vec![OperatingPoint {
2220 seq_level_idx: 8,
2221 ..OperatingPoint::default()
2222 }],
2223 frame_width_bits,
2224 frame_height_bits,
2225 max_frame_width: w,
2226 max_frame_height: h,
2227 use_128x128_superblock: sb128_on(),
2228 // lane-fintra: the encoder's intra search offers the five recursive
2229 // filter-intra modes on eligible blocks, so the sequence bit is set
2230 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
2231 // off and restores the streams this encoder wrote before the lane).
2232 enable_filter_intra: filter_intra_on(),
2233 enable_intra_edge_filter: false,
2234 enable_order_hint: true,
2235 order_hint_bits: 7,
2236 enable_superres: false,
2237 // spec 5.9.19: with the sequence bit set every frame header carries
2238 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
2239 // pair for the whole frame, chosen by `crate::filter_search` -- so no
2240 // `cdef_idx` literal is coded in the tile and a frame that wants no
2241 // CDEF simply carries zero strengths.
2242 enable_cdef: true,
2243 enable_restoration: true,
2244 // SELECT (2) when this sequence's key frame detected screen content
2245 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
2246 // is then coded in every frame header, and only the frames that want
2247 // the palette syntax set it. 0 -- the forced-off form, no bit at all
2248 // -- otherwise, which is what every non-screen stream this encoder
2249 // writes still carries.
2250 seq_force_screen_content_tools: if seq_screen() {
2251 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
2252 } else {
2253 0
2254 },
2255 seq_force_integer_mv: 0,
2256 color_config,
2257 still_picture: false,
2258 reduced_still_picture_header: false,
2259 timing_info: None,
2260 decoder_model_info: None,
2261 initial_display_delay_present_flag: false,
2262 operating_point: 0,
2263 operating_point_idc: 0,
2264 frame_id_numbers_present_flag: false,
2265 delta_frame_id_length: 0,
2266 additional_frame_id_length: 0,
2267 enable_interintra_compound: false,
2268 enable_masked_compound: false,
2269 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
2270 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
2271 // header is byte-identical to the streams before this lane.
2272 enable_warped_motion: warp_on(),
2273 enable_dual_filter: false,
2274 enable_jnt_comp: false,
2275 enable_ref_frame_mvs: false,
2276 film_grain_params_present: false,
2277 };
2278 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
2279 // own (true, unpadded) width and height, not from any block-grid
2280 // alignment — a decoder derives these straight from `frame_width`/
2281 // `frame_height` below, so this must match it exactly.
2282 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
2283 let header = FrameHeader {
2284 frame_type: FrameType::Key,
2285 frame_is_intra: true,
2286 show_frame: true,
2287 error_resilient_mode: true,
2288 // The tile writer keeps the same CDF state the decoder does and
2289 // updates it in the same order, so the frame lets the decoder adapt.
2290 disable_cdf_update: false,
2291 // Nothing reads the state this frame leaves behind: a key frame always
2292 // starts from the defaults, and this encoder emits one frame.
2293 disable_frame_end_update_cdf: true,
2294 force_integer_mv: true,
2295 refresh_frame_flags: 0xFF,
2296 primary_ref_frame: PRIMARY_REF_NONE,
2297 frame_width: w,
2298 frame_height: h,
2299 upscaled_width: w,
2300 render_width: w,
2301 render_height: h,
2302 mi_cols,
2303 mi_rows,
2304 tile_info: TileInfo {
2305 uniform_spacing: true,
2306 cols: 1,
2307 rows: 1,
2308 mi_col_starts: vec![0, mi_cols],
2309 mi_row_starts: vec![0, mi_rows],
2310 tile_size_bytes: 1,
2311 ..TileInfo::default()
2312 },
2313 quantization: QuantizationParams {
2314 base_q_idx,
2315 ..QuantizationParams::default()
2316 },
2317 tx_mode: TxMode::Largest,
2318 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
2319 // intra transform below 32x32, not only 16x16 -- the set this crate
2320 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
2321 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
2322 // so a decoder honouring the header picks the same CDF the writer
2323 // used only if this is set here too, not only on the inter variant
2324 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
2325 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
2326 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
2327 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
2328 // the arithmetic coder's `rng` register from the very first 8x8-leaf
2329 // luma transform onward with no symbol value ever differing.
2330 reduced_tx_set: true,
2331 ..FrameHeader::default()
2332 };
2333 Ok((seq, header))
2334}
2335
2336/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
2337/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
2338/// 1 still holds the key frame however long the GOP runs.
2339pub const GOLDEN_SLOT: u8 = 1;
2340
2341/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
2342/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
2343/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
2344/// one filter for the whole frame, which is what libaom does on this content
2345/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
2346/// stream, so a per-BLOCK filter search has no bits to win). The kernel
2347/// reaches the search, the trials and the recon through
2348/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
2349/// prediction the search priced are the same one.
2350/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the
2351/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
2352/// the witness that has to see a non-REGULAR kernel coded and decoded turns
2353/// it on through this while holding [`crate::speed::knob_write`].
2354static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 =
2355 std::sync::atomic::AtomicU8::new(u8::MAX);
2356
2357/// Sets [`INTERP_OVERRIDE`]; `None` clears it.
2358#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
2359pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) {
2360 INTERP_OVERRIDE.store(
2361 filter.map_or(u8::MAX, |f| f as u8),
2362 std::sync::atomic::Ordering::Relaxed,
2363 );
2364}
2365
2366fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
2367 use ec_av1_syntax::InterpolationFilter as F;
2368 match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2369 0 => return F::Eighttap,
2370 1 => return F::EighttapSmooth,
2371 2 => return F::EighttapSharp,
2372 _ => {}
2373 }
2374 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2375 crate::envflags::var("EC_AV1_INTERP").ok().map(|v| match v.as_str() {
2376 "smooth" => F::EighttapSmooth,
2377 "sharp" => F::EighttapSharp,
2378 _ => F::Eighttap,
2379 })
2380 });
2381 ENV.unwrap_or(F::Eighttap)
2382}
2383
2384/// The frame header for a shown inter frame that predicts from the single
2385/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
2386/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
2387/// reused verbatim: an inter frame never changes the sequence.
2388///
2389/// # Errors
2390/// Returns an error under the same conditions as [`key_frame_headers`].
2391pub fn inter_frame_headers(
2392 width: usize,
2393 height: usize,
2394 base_q_idx: u8,
2395 order_hint: u32,
2396 last_slot: u8,
2397) -> Result<(SequenceHeader, FrameHeader)> {
2398 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
2399}
2400
2401/// [`inter_frame_headers`] with the three slots named apart: the one read as
2402/// `LAST_FRAME`, the one this frame refreshes, and the one read as
2403/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
2404/// so that the frame two back is still intact in the slot this one is about
2405/// to overwrite -- read before write, spec 7.20's decode order.
2406///
2407/// # Errors
2408/// As [`inter_frame_headers`].
2409pub fn inter_frame_headers_slots(
2410 width: usize,
2411 height: usize,
2412 base_q_idx: u8,
2413 order_hint: u32,
2414 last_slot: u8,
2415 self_slot: u8,
2416 altref_slot: u8,
2417) -> Result<(SequenceHeader, FrameHeader)> {
2418 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
2419 let header = FrameHeader {
2420 frame_type: FrameType::Inter,
2421 frame_is_intra: false,
2422 show_frame: true,
2423 error_resilient_mode: false,
2424 disable_cdf_update: false,
2425 // The tile writer hands its end-of-tile tables to the next frame
2426 // (`encode_sequence_with_ctx`), so the frame stores them the way the
2427 // decoder will load them (spec 7.20).
2428 disable_frame_end_update_cdf: false,
2429 force_integer_mv: false,
2430 order_hint,
2431 primary_ref_frame: 0,
2432 refresh_frame_flags: 1 << self_slot,
2433 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
2434 // names the slot this frame both predicts from and refreshes;
2435 // GOLDEN names slot 1, which the key frame wrote when it refreshed
2436 // all eight and which no inter frame ever overwrites, so it holds
2437 // the key frame's own picture for the whole GOP.
2438 ref_frame_idx: {
2439 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
2440 idx[3] = GOLDEN_SLOT;
2441 idx[6] = altref_slot;
2442 idx
2443 },
2444 // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`:
2445 // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's
2446 // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in
2447 // every frame this constructor builds, so no further guard is needed.
2448 allow_high_precision_mv: high_precision_mv_at(base_q_idx),
2449 // A FIXED frame-level filter, so no block codes an `interp_filter`
2450 // symbol. lane-obmc3 instrumented whether that costs anything: a
2451 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
2452 // (45941 B, the same point `lanes/libcen.report.md` matched) read
2453 // back through `EC_AV1_BITCENSUS=1 syntax_census` codes
2454 // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed
2455 // frame filter here too, so there are ZERO per-block filter bits at
2456 // stake on this content and the per-block switchable search was not
2457 // built (the charter's premise that libaom codes switchable interp
2458 // per block on film B is refuted by its own stream).
2459 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
2460 // lane-av1obmc: with this bit set every single-reference inter block
2461 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
2462 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
2463 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
2464 // to the OBMC knob rather than always on: with every block choosing
2465 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
2466 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
2467 // and stays byte-identical to the streams before this lane.
2468 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
2469 // `allow_warped_motion` besides -- which is what makes an eligible
2470 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
2471 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2472 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
2473 || warp_on(),
2474 allow_warped_motion: warp_on(),
2475 use_ref_frame_mvs: false,
2476 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
2477 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
2478 // set this crate carries a table for at 16x16 (see
2479 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
2480 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
2481 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
2482 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
2483 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
2484 // path) -- with this flag set, `get_tx_set`'s intra branch returns
2485 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
2486 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
2487 reduced_tx_set: true,
2488 ..key
2489 };
2490 Ok((seq, header))
2491}
2492
2493fn too_large() -> Error {
2494 Error::unsupported(
2495 "AV1 encode",
2496 "the picture is larger than a frame size can carry",
2497 )
2498}
2499
2500/// One plane of the picture being coded, and the reconstruction being built
2501/// beside it.
2502/// What one committed 4x4 cell left behind for the coefficient contexts of
2503/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
2504/// is the same state decode.rs records.
2505#[derive(Clone, Copy, Default, PartialEq, Eq)]
2506struct CoefCtx {
2507 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
2508 level: u8,
2509 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
2510 /// the DC itself was zero (tile.rs `dc_vote`).
2511 dc: i8,
2512}
2513
2514/// One plane's coefficient contexts, committed in CODING ORDER: the search
2515/// prices partition TREES, so the neighbour state a candidate reads has to be
2516/// whatever the blocks coded before it left -- the parent's committed
2517/// neighbours for a tree's first child, the just-committed sibling for the
2518/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
2519/// writer's two running bands is what makes that fall out: a trial commits
2520/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
2521/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
2522/// to its left is exactly what the tile writer's `Neighbours` bands will hold
2523/// when it gets there.
2524///
2525/// Before this map the pricer took both contexts as zero, which is exact for
2526/// a luma transform covering its whole block and the largest remaining row of
2527/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
2528#[derive(Default)]
2529struct CoefCtxMap {
2530 cells: Vec<CoefCtx>,
2531 stride: usize,
2532 /// Whether the transforms being priced right now are SMALLER than the
2533 /// block they sit in -- a `TxMode::Select` depth split
2534 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
2535 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
2536 /// trial cannot tell, and it is what decides whether luma reads context 0
2537 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
2538 tu_split: bool,
2539}
2540
2541/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
2542/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
2543/// padding-inclusive score the search used before lane-sse, which is how the
2544/// before/after arms of the straddling gate rows are read off ONE binary.
2545fn edge_sse() -> bool {
2546 static ENV: std::sync::LazyLock<Option<bool>> =
2547 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGESSE").ok().map(|v| v != "0"));
2548 ENV.unwrap_or(true)
2549}
2550
2551/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
2552/// through and the share of their raw squared error that sat in the padding
2553/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
2554/// it, but the numbers are an instrument, not a decision (class
2555/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
2556/// without this census no gate row can say the clip fires at all).
2557fn edge_census() -> bool {
2558 static ENV: std::sync::LazyLock<bool> =
2559 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1"));
2560 *ENV
2561}
2562
2563/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
2564/// 128x128): how many scores clipped, the inside squared error they kept and
2565/// the padding squared error they dropped.
2566static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
2567 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
2568
2569/// One clipped score, for [`take_edge_census`].
2570fn record_edge_score(side: usize, inside: u64, padding: u64) {
2571 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
2572 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2573 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
2574 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
2575}
2576
2577/// The straddling-block census since the last call, and zero it: one
2578/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
2579#[must_use]
2580pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
2581 EDGE_SCORES
2582 .iter()
2583 .enumerate()
2584 .filter_map(|(log2, row)| {
2585 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
2586 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
2587 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
2588 (n != 0).then_some((1usize << log2, n, inside, padding))
2589 })
2590 .collect()
2591}
2592
2593struct Plane<'a> {
2594 source: &'a [u8],
2595 reconstruction: Vec<u8>,
2596 width: usize,
2597 height: usize,
2598 /// The frame's true, decodable extent in this plane's own units --
2599 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
2600 /// not `width`/`height` above, which is the padded coding-surface size.
2601 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
2602 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
2603 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
2604 /// this bound, even though the padded reconstruction buffer holds real
2605 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
2606 /// those instead of stopping here is what desyncs prediction at the true
2607 /// edge.
2608 true_width: usize,
2609 true_height: usize,
2610 /// This plane's own tile's pixel bounds, in this plane's units -- the
2611 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
2612 /// prediction never reaches across a tile edge even though the
2613 /// neighbouring tile's real samples sit right there in the shared
2614 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
2615 /// leaves every edge exactly as it was before tiles existed.
2616 tile_x0: usize,
2617 tile_y0: usize,
2618 tile_x1: usize,
2619 tile_y1: usize,
2620 /// [`CoefCtxMap`]: what the blocks already committed left for the
2621 /// coefficient contexts of the ones still being priced. Sized on the
2622 /// first commit, so a plane literal does not have to know its own extent
2623 /// twice.
2624 ctx: CoefCtxMap,
2625}
2626
2627impl Plane<'_> {
2628 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
2629 /// called at every superblock of the frame-raster search with the rect
2630 /// of the tile that superblock belongs to.
2631 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
2632 self.tile_x0 = x0;
2633 self.tile_y0 = y0;
2634 self.tile_x1 = x1.min(self.width);
2635 self.tile_y1 = y1.min(self.height);
2636 }
2637 /// The reconstructed samples a block at `(x, y)` predicts from: the row
2638 /// above it, the column to its left and the sample between them, each
2639 /// missing where the block sits against an edge of the frame.
2640 ///
2641 /// `reach` says whether the samples above the block's right and below its
2642 /// left are decoded, which is what a directional mode reads into; where
2643 /// they are not, or where the frame ends first, the edge is shorter and
2644 /// the predictor repeats its last sample, exactly as the decoder's clamp
2645 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
2646 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
2647 /// a free per mode per block, on the search's hottest path -- while an
2648 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
2649 /// samples, on the caller's stack.
2650 fn edges_into<'a>(
2651 &self,
2652 x: usize,
2653 y: usize,
2654 side: usize,
2655 reach: Reach,
2656 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
2657 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
2658 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
2659 // Even a block's *own* edge is clamped to the true frame bound, not
2660 // just a `reach` extension: libaom's `av1_predict_intra_block`
2661 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
2662 // this block's own right/bottom to the frame edge -- from
2663 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
2664 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
2665 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
2666 // samples the row/column above/left holds before the decoder starts
2667 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
2668 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
2669 // extent straddles that edge legally (`has_half`) -- the transform
2670 // still covers the whole block, but prediction does not get to read
2671 // real reconstructed pixels past the true edge for its own row/column,
2672 // only for the padded tail it invents.
2673 let own_across = x + side.min(self.true_width.saturating_sub(x));
2674 let across = if reach.above_right {
2675 own_across + side.min(self.true_width.saturating_sub(own_across))
2676 } else {
2677 own_across
2678 }
2679 .min(self.width);
2680 let own_down = y + side.min(self.true_height.saturating_sub(y));
2681 let down = if reach.below_left {
2682 own_down + side.min(self.true_height.saturating_sub(own_down))
2683 } else {
2684 own_down
2685 }
2686 .min(self.height);
2687 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
2688 // whose own origin already sits past the true edge -- only reachable
2689 // through a partition trial priced for comparison on a split this
2690 // frame's straddling quadrant will go on to refuse (see
2691 // `a_picture_off_the_block_grid_is_refused`), never through a block
2692 // this encoder actually commits. Such a block has no true-edge
2693 // samples above or left of it at all, same as `y == 0`/`x == 0`.
2694 let across = across.min(self.tile_x1);
2695 let down = down.min(self.tile_y1);
2696 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
2697 if let Some(n) = above_n {
2698 above_buf[..n]
2699 .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
2700 }
2701 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
2702 if let Some(n) = left_n {
2703 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
2704 *d = self.reconstruction[row * self.width + x - 1];
2705 }
2706 }
2707 let corner = (x > self.tile_x0 && y > self.tile_y0)
2708 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
2709 (
2710 above_n.map(|n| &above_buf[..n]),
2711 left_n.map(|n| &left_buf[..n]),
2712 corner,
2713 )
2714 }
2715
2716 /// Codes one block under one mode without committing it: hands back the
2717 /// levels, the block the decoder would reconstruct, the squared error
2718 /// against the source and an estimate of what the levels cost in bits.
2719 fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
2720 self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx)
2721 }
2722
2723 /// [`Self::trial`] under a named transform type -- what an intra chroma
2724 /// block gets, since chroma codes no `tx_type` symbol and the decoder
2725 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
2726 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
2727 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
2728 #[allow(clippy::too_many_arguments)]
2729 /// Sum of absolute differences between the source block at `(x, y)` and a
2730 /// `side x side` prediction, as the whole number it is.
2731 ///
2732 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
2733 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
2734 /// exactly, so no add here rounds and the order of the adds cannot change
2735 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
2736 /// integer division per sample -- is what lets the row walk vectorize.
2737 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
2738 let mut sad = 0u32;
2739 for row in 0..side {
2740 let source = &self.source[(y + row) * self.width + x..][..side];
2741 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
2742 sad += u32::from(s.abs_diff(p));
2743 }
2744 }
2745 f64::from(sad)
2746 }
2747
2748 /// Squared error between the source block at `(x, y)` and a reconstruction
2749 /// of it, over the part of the block that is INSIDE the true frame.
2750 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
2751 /// `255^2 * 64 * 64`, under 2^28.
2752 ///
2753 /// A block the frame edge cuts through is still coded whole -- the
2754 /// decoder reconstructs its outside samples too and the display crop
2755 /// throws them away -- so scoring the padding would rank a mode, a
2756 /// transform or a partition tree by how well it codes samples the source
2757 /// does not have (libaom clips the same way: `av1_dist_block` measures
2758 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
2759 /// edge pixels, so predicting it is nearly free, but coding coefficients
2760 /// for it spends real bits. Both gate films are superblock-aligned; this
2761 /// only reaches arbitrary export sizes (lane-sse, generalising
2762 /// lane-b64b's 64-root-only rescore of the 64 root).
2763 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
2764 let inside_rows = side.min(self.true_height.saturating_sub(y));
2765 let inside_cols = side.min(self.true_width.saturating_sub(x));
2766 let straddles = inside_rows < side || inside_cols < side;
2767 // The knob is read only for a block the edge cuts, so the interior
2768 // path -- the hot one -- carries no extra load at all.
2769 let (rows, cols) = match straddles && !edge_sse() {
2770 true => (side, side),
2771 false => (inside_rows, inside_cols),
2772 };
2773 let mut sse = 0u64;
2774 for row in 0..rows {
2775 let source = &self.source[(y + row) * self.width + x..][..cols];
2776 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
2777 let d = u32::from(s.abs_diff(r));
2778 sse += u64::from(d * d);
2779 }
2780 }
2781 if straddles && edge_census() {
2782 let (mut inside, mut whole) = (0u64, 0u64);
2783 for row in 0..side {
2784 let source = &self.source[(y + row) * self.width + x..][..side];
2785 for (col, (&s, &r)) in
2786 source.iter().zip(&reconstruction[row * side..][..side]).enumerate()
2787 {
2788 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
2789 whole += d;
2790 if row < inside_rows && col < inside_cols {
2791 inside += d;
2792 }
2793 }
2794 }
2795 record_edge_score(side, inside, whole - inside);
2796 }
2797 sse as f64
2798 }
2799
2800 fn trial_typed(
2801 &self,
2802 at: At,
2803 mode: u8,
2804 // This block's `angle_delta_y`/`angle_delta_uv` (spec
2805 // `read_intra_angle_info`, -3..=3), zero for every non-directional
2806 // mode -- the predictor's own `angle_delta` argument.
2807 angle_delta: i32,
2808 base_q_idx: u8,
2809 deadzone: f64,
2810 tx_type: TxType,
2811 fctx: &crate::decode::FrameCtx,
2812 ) -> Trial {
2813 let At {
2814 x, y, side, reach, ..
2815 } = at;
2816 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2817 let (above, left, corner) =
2818 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2819 // Per-candidate scratch on the search's hottest path, so both buffers
2820 // live on the stack -- `side` is at most `BLOCK` -- rather than
2821 // costing a malloc/free pair per trial (`mc_trial` already does this).
2822 let mut prediction = [0u8; BLOCK * BLOCK];
2823 let prediction = &mut prediction[..side * side];
2824 intra_predict_u8(
2825 mode,
2826 angle_delta,
2827 above,
2828 left,
2829 corner,
2830 side,
2831 side,
2832 false,
2833 false,
2834 prediction, fctx,
2835 );
2836
2837 let mut residual = [0i32; BLOCK * BLOCK];
2838 let residual = &mut residual[..side * side];
2839 for row in 0..side {
2840 for col in 0..side {
2841 residual[row * side + col] =
2842 i32::from(self.source[(y + row) * self.width + x + col])
2843 - i32::from(prediction[row * side + col]);
2844 }
2845 }
2846 #[cfg(test)]
2847 let t = stage_start();
2848 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
2849 // reconstruction below and the price further down are both of the
2850 // grid this trial would really code.
2851 let (levels, rdoq_bits) = if rdoq_on() {
2852 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2853 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2854 );
2855 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2856 let bits = crate::tile::rdoq(
2857 &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(),
2858 tx_type,
2859 );
2860 (levels, Some(bits))
2861 } else {
2862 (
2863 forward_and_quantize_typed(
2864 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2865 ),
2866 None,
2867 )
2868 };
2869 // lane-av1speed2: 60% of the transform units of an inter stream carry
2870 // no coefficient at all, and the square entry point re-inflates that
2871 // case into `side * side` zeros (one allocate-and-memset per trial)
2872 // only for the sum below to add them to the prediction. The `_wh`
2873 // entry hands back the empty all-zero marker instead, and a zero
2874 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
2875 // `p` for a `u8`, so the bytes are the same.
2876 let coded = dequant_and_inverse_typed_wh(
2877 &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, None,
2878 );
2879 #[cfg(test)]
2880 stage_since(2, t);
2881
2882 let reconstruction: Vec<u8> = if coded.is_empty() {
2883 prediction.to_vec()
2884 } else {
2885 prediction
2886 .iter()
2887 .zip(&coded)
2888 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2889 .collect()
2890 };
2891 let sse = self.block_sse(x, y, side, &reconstruction);
2892 // What the levels cost is priced through the same CDFs the tile writer
2893 // will code them with, so the search ranks modes -- and the partition
2894 // trial ranks trees -- by the bits they actually spend.
2895 #[cfg(test)]
2896 let t = stage_start();
2897 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2898 // What the search used before it could price a block exactly: a
2899 // level costs its magnitude's width plus a sign and a run. Kept
2900 // reachable from the sweep so the two rate terms can be compared
2901 // on one build.
2902 levels
2903 .iter()
2904 .filter(|&&level| level != 0)
2905 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2906 .sum()
2907 } else if let Some(bits) = rdoq_bits {
2908 // Already priced, against the grid the pass settled on.
2909 bits
2910 } else {
2911 {
2912 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2913 crate::tile::coeff_bits_typed(
2914 &levels,
2915 at.set,
2916 crate::decode::q_ctx_of(base_q_idx),
2917 skip_ctx,
2918 sign_ctx,
2919 tx_type,
2920 )
2921 }
2922 };
2923 #[cfg(test)]
2924 stage_since(3, t);
2925 Trial {
2926 levels,
2927 reconstruction,
2928 sse,
2929 bits,
2930 }
2931 }
2932
2933 /// [`Self::trial`] with the prediction already built, so that an inter
2934 /// block's motion-compensated prediction can go through the same
2935 /// residual/quantize/reconstruct path an intra block's does. `skip`
2936 /// takes the prediction as the reconstruction outright, coding no
2937 /// residual at all — what a `NEARESTMV` block that names no coefficients
2938 /// codes.
2939 #[allow(clippy::too_many_arguments)]
2940 fn code_from_prediction(
2941 &self,
2942 x: usize,
2943 y: usize,
2944 side: usize,
2945 prediction: &[u8],
2946 skip: bool,
2947 base_q_idx: u8,
2948 deadzone: f64,
2949 set: TxbSet,
2950 ) -> Trial {
2951 self.code_from_prediction_typed(
2952 x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct,
2953 )
2954 }
2955
2956 /// [`Self::code_from_prediction`] coding the residual with a NAMED
2957 /// transform type (lane-txset2): the inter luma sets carry a two-type
2958 /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
2959 /// a symbol for, and [`commit_inter_luma`] prices both through this.
2960 #[allow(clippy::too_many_arguments)]
2961 fn code_from_prediction_typed(
2962 &self,
2963 x: usize,
2964 y: usize,
2965 side: usize,
2966 prediction: &[u8],
2967 skip: bool,
2968 base_q_idx: u8,
2969 deadzone: f64,
2970 set: TxbSet,
2971 tx_type: TxType,
2972 ) -> Trial {
2973 if skip {
2974 let sse = self.block_sse(x, y, side, prediction);
2975 return Trial {
2976 levels: vec![0i32; side * side],
2977 reconstruction: prediction.to_vec(),
2978 sse,
2979 bits: 0.0,
2980 };
2981 }
2982 // A 64x64 root's residual is four times the scratch every other
2983 // block coder here sizes for [`BLOCK`]; only that one case pays for
2984 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
2985 let mut small = [0i32; BLOCK * BLOCK];
2986 let mut big = if side > BLOCK {
2987 vec![0i32; side * side]
2988 } else {
2989 Vec::new()
2990 };
2991 let residual: &mut [i32] = if side > BLOCK {
2992 &mut big
2993 } else {
2994 &mut small[..side * side]
2995 };
2996 for row in 0..side {
2997 for col in 0..side {
2998 residual[row * side + col] =
2999 i32::from(self.source[(y + row) * self.width + x + col])
3000 - i32::from(prediction[row * side + col]);
3001 }
3002 }
3003 #[cfg(test)]
3004 let t = stage_start();
3005 // lane-rdoq, as in [`Self::trial_typed`].
3006 let (levels, rdoq_bits) = if rdoq_on() {
3007 let (mut levels, scaled) =
3008 forward_and_quantize_typed_scaled(
3009 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
3010 );
3011 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3012 let bits = crate::tile::rdoq(
3013 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),
3014 tx_type,
3015 );
3016 (levels, Some(bits))
3017 } else {
3018 (
3019 forward_and_quantize_typed(
3020 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
3021 ),
3022 None,
3023 )
3024 };
3025 // The same all-zero shortcut [`Self::trial_typed`] takes.
3026 let coded = dequant_and_inverse_typed_wh(
3027 &levels,
3028 side,
3029 side,
3030 8,
3031 i32::from(base_q_idx),
3032 0,
3033 0,
3034 tx_type,
3035 None,
3036 );
3037 #[cfg(test)]
3038 stage_since(2, t);
3039 let reconstruction: Vec<u8> = if coded.is_empty() {
3040 prediction.to_vec()
3041 } else {
3042 prediction
3043 .iter()
3044 .zip(&coded)
3045 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
3046 .collect()
3047 };
3048 let sse = self.block_sse(x, y, side, &reconstruction);
3049 // A 64-point transform codes only its top-left 32x32 corner (spec
3050 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
3051 // key frame writer takes a 32x32 level grid for one). The inverse
3052 // above reads the whole 64x64 array, but the price below and the
3053 // levels the writer takes are that corner.
3054 let levels = if side > BLOCK {
3055 coded_corner(&levels, side, BLOCK)
3056 } else {
3057 levels
3058 };
3059 #[cfg(test)]
3060 let t = stage_start();
3061 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
3062 levels
3063 .iter()
3064 .filter(|&&level| level != 0)
3065 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
3066 .sum()
3067 } else if let Some(bits) = rdoq_bits {
3068 bits
3069 } else {
3070 {
3071 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3072 crate::tile::coeff_bits_typed(
3073 &levels,
3074 set,
3075 crate::decode::q_ctx_of(base_q_idx),
3076 skip_ctx,
3077 sign_ctx,
3078 tx_type,
3079 )
3080 }
3081 };
3082 #[cfg(test)]
3083 stage_since(3, t);
3084 Trial {
3085 levels,
3086 reconstruction,
3087 sse,
3088 bits,
3089 }
3090 }
3091
3092 /// Codes this block's luma at transform depth `depth`: the
3093 /// `(side >> depth)^2` transform units in raster order, each predicted
3094 /// from the reconstruction the units before it left behind -- exactly
3095 /// what the decoder's multi-transform-unit branch does (decode.rs
3096 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
3097 /// reconstructed on its own. Commits the result and hands back the
3098 /// block-coordinate levels, the block's squared error and what its
3099 /// coefficients cost.
3100 #[allow(clippy::too_many_arguments)]
3101 fn code_tx_depth(
3102 &mut self,
3103 at: At,
3104 mode: u8,
3105 angle_delta: i32,
3106 depth: usize,
3107 // This block's `filter_intra_mode` when it is coded with one, in
3108 // which case every transform unit predicts recursively off the
3109 // reconstruction the units before it left -- what the decoder does
3110 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
3111 // `filter_intra`), not once over the whole block.
3112 filter_intra: Option<u8>,
3113 search: &Search, fctx: &crate::decode::FrameCtx,
3114 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
3115 let At { x, y, side, reach, .. } = at;
3116 let tx = side >> depth;
3117 let n = 1usize << depth;
3118 let set = luma_set_for(
3119 match tx {
3120 32 => TxbSet::Luma32,
3121 16 => TxbSet::Luma16,
3122 8 => TxbSet::Luma8,
3123 _ => TxbSet::Luma4,
3124 },
3125 search.screen,
3126 );
3127 let mut levels = vec![0i32; side * side];
3128 census_add(4, n * n);
3129 // A unit smaller than its block reads the neighbour magnitude table
3130 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
3131 self.ctx.tu_split = n > 1;
3132 let (mut sse, mut bits) = (0.0, 0.0);
3133 // One entry per unit at its own `tu_row * n + tu_col`, which is how
3134 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
3135 // frame edge cuts away is never coded there, so a compacted list
3136 // would slide every later unit's type onto the wrong transform.
3137 let mut tx_types = vec![TxType::DctDct; n * n];
3138 for tu_row in 0..n {
3139 for tu_col in 0..n {
3140 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3141 let tu = At {
3142 x: x + col_off,
3143 y: y + row_off,
3144 side: tx,
3145 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
3146 set,
3147 };
3148 let trial = match filter_intra {
3149 Some(fi) => {
3150 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3151 let (above, left, corner) =
3152 self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf);
3153 let mut prediction = vec![0u8; tx * tx];
3154 filter_intra_predict_u8(
3155 usize::from(fi),
3156 above,
3157 left,
3158 corner,
3159 tx,
3160 &mut prediction,
3161 fctx,
3162 );
3163 self.code_from_prediction(
3164 tu.x,
3165 tu.y,
3166 tx,
3167 &prediction,
3168 false,
3169 search.base_q_idx,
3170 search.deadzone,
3171 set,
3172 )
3173 }
3174 None => {
3175 // lane-txset: the unit picks its own transform type
3176 // out of the set the writer can name it in, priced
3177 // through the same RDOQ'd trial path (its `bits`
3178 // already carry the `tx_type` symbol itself).
3179 let mut best: Option<(f64, TxType, Trial)> = None;
3180 for &tx_type in tx_type_candidates(set, search.screen) {
3181 let candidate = self.trial_typed(
3182 tu, mode, angle_delta, search.base_q_idx, search.deadzone,
3183 tx_type, fctx,
3184 );
3185 // lane-txi: a non-`DCT_DCT` type is charged its
3186 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
3187 // search's weight (default 1 = unchanged). The
3188 // film rows buy 0.04 dB for 1.2% more bytes at
3189 // weight 1 on every frame and every PLANE, key
3190 // frame included -- a rate term this decision
3191 // under-charges (class
3192 // `rd-rate-term-calibration`), not the
3193 // propagation loss the leaves would have shown.
3194 let cost = candidate.sse
3195 + search.lambda * candidate.bits
3196 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
3197 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
3198 best = Some((cost, tx_type, candidate));
3199 }
3200 }
3201 let (_, tx_type, trial) =
3202 best.expect("the candidate list is never empty");
3203 tx_types[tu_row * n + tu_col] = tx_type;
3204 TX_TYPE_HITS[tx_type as usize]
3205 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3206 trial
3207 }
3208 };
3209 sse += trial.sse;
3210 bits += trial.bits;
3211 self.commit(tu.x, tu.y, tx, &trial);
3212 for row in 0..tx {
3213 levels[(row_off + row) * side + col_off..][..tx]
3214 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3215 }
3216 }
3217 }
3218 self.ctx.tu_split = false;
3219 (levels, sse, bits, tx_types)
3220 }
3221
3222 /// Writes a trial's reconstruction back into the plane, and the
3223 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
3224 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
3225 for row in 0..side {
3226 self.reconstruction[(y + row) * self.width + x..][..side]
3227 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
3228 }
3229 self.commit_ctx(x, y, side, &trial.levels);
3230 }
3231
3232 /// Publishes one committed transform's own context over every 4x4 cell it
3233 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
3234 /// which is what the writer will read when it reaches the next block.
3235 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
3236 if self.ctx.cells.is_empty() {
3237 self.ctx.stride = self.width.div_ceil(4);
3238 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
3239 }
3240 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
3241 let state = CoefCtx {
3242 level: cul,
3243 dc: match levels[0].signum() {
3244 0 => 0,
3245 -1 => -1,
3246 _ => 1,
3247 },
3248 };
3249 let n = (side / 4).max(1);
3250 // Only up to the frame's TRUE extent: the writer's own
3251 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
3252 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
3253 // and leaves the cells past it uncoded even mid-block, so a
3254 // straddling block publishes context for its inside part only.
3255 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
3256 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
3257 for row in 0..rows {
3258 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3259 let end = (start + cols).min(self.ctx.cells.len());
3260 if start < end {
3261 self.ctx.cells[start..end].fill(state);
3262 }
3263 }
3264 }
3265
3266 /// A block committed without any residual at all ([`ibc_commit`]): the
3267 /// cells it covers coded nothing, and leaving an earlier trial's state
3268 /// there would price its neighbours off a block that was never coded.
3269 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
3270 self.commit_ctx(x, y, side, &[0i32]);
3271 }
3272
3273 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
3274 /// plane reads, off what the blocks before it in coding order committed
3275 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
3276 /// the above/left neighbours coded anything (tile.rs
3277 /// `write_block_planes`), luma reads context 0 when its transform covers
3278 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
3279 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
3280 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
3281 /// the same neighbours (tile.rs `dc_sign_ctx`).
3282 ///
3283 /// A neighbour outside this plane's own TILE does not exist, exactly as
3284 /// the writer's per-tile `Neighbours` bands start blank.
3285 ///
3286 /// CLOSED (lane-av1straddle): the decisions this price changes used to
3287 /// make `decode_stream_round_trips_an_odd_size_gop` and
3288 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
3289 /// fail at 216x96. Never this map: the writer coded the phantom
3290 /// transform units of a right-edge-straddling 32x32 (tile.rs
3291 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
3292 /// like decode.rs and libaom), which libdav1d and libaom both refused
3293 /// outright while a decision change was what first walked into it.
3294 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
3295 if self.ctx.cells.is_empty() {
3296 return (0, 0);
3297 }
3298 let n = (side / 4).max(1);
3299 let (cx, cy) = (x / 4, y / 4);
3300 let (mut top, mut left) = (0u8, 0u8);
3301 let mut vote = 0i32;
3302 if y > self.tile_y0 && cy > 0 {
3303 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
3304 top |= cell.level;
3305 vote += i32::from(cell.dc);
3306 }
3307 }
3308 if x > self.tile_x0 && cx > 0 {
3309 for row in 0..n {
3310 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
3311 left |= cell.level;
3312 vote += i32::from(cell.dc);
3313 }
3314 }
3315 let skip_ctx = if set.is_chroma() {
3316 usize::from(top != 0) + usize::from(left != 0)
3317 } else if self.ctx.tu_split {
3318 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3319 } else {
3320 0
3321 };
3322 let sign_ctx = match vote.signum() {
3323 0 => 0,
3324 -1 => 1,
3325 _ => 2,
3326 };
3327 (skip_ctx, sign_ctx)
3328 }
3329
3330 /// The source samples of one square, contiguous — what a motion search
3331 /// compares its candidates' predictions against ([`motion::search`]'s
3332 /// `source`), since [`Self::source`] itself is the whole plane, strided
3333 /// by [`Self::width`].
3334 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
3335 rows_of(self.source, self.width, x, y, side)
3336 }
3337
3338 /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
3339 /// root's own HORZ/VERT motion search.
3340 fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
3341 let mut out = vec![0u8; w * h];
3342 for row in 0..h {
3343 out[row * w..][..w]
3344 .copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3345 }
3346 out
3347 }
3348
3349 /// The reconstructed samples of one square, so that a partition trial can
3350 /// be undone.
3351 /// The reconstructed samples of one square AND the coefficient contexts
3352 /// its cells hold, so that a partition trial can be undone whole: a
3353 /// losing trial that left its own nz/DC state behind would price the
3354 /// blocks after it off a block the tile writer never codes.
3355 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
3356 (
3357 rows_of(&self.reconstruction, self.width, x, y, side),
3358 self.ctx_rows(x, y, side),
3359 )
3360 }
3361
3362 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
3363 if self.ctx.cells.is_empty() {
3364 return Vec::new();
3365 }
3366 let n = (side / 4).max(1);
3367 (0..n)
3368 .flat_map(|row| {
3369 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3370 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
3371 })
3372 .collect()
3373 }
3374
3375 /// Puts a snapshot back.
3376 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
3377 for row in 0..side {
3378 self.reconstruction[(y + row) * self.width + x..][..side]
3379 .copy_from_slice(&saved.0[row * side..][..side]);
3380 }
3381 if saved.1.is_empty() {
3382 return;
3383 }
3384 let n = (side / 4).max(1);
3385 for row in 0..n {
3386 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3387 let end = (start + n).min(self.ctx.cells.len());
3388 if start < end {
3389 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
3390 }
3391 }
3392 }
3393
3394 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
3395 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
3396 /// prescreen by the identical rule rather than a second one that could
3397 /// drift from it.
3398 fn intra_scores(
3399 &self,
3400 at: At,
3401 modes: &[u8],
3402 mode_bits: &[f64; 13],
3403 lambda: f64, fctx: &crate::decode::FrameCtx,
3404 ) -> Vec<(f64, u8)> {
3405 let At {
3406 x, y, side, reach, ..
3407 } = at;
3408 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3409 let (above, left, corner) =
3410 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3411 modes
3412 .iter()
3413 .map(|&mode| {
3414 let mut prediction = vec![0u8; side * side];
3415 intra_predict_u8(
3416 mode,
3417 0,
3418 above,
3419 left,
3420 corner,
3421 side,
3422 side,
3423 false,
3424 false,
3425 &mut prediction, fctx,
3426 );
3427 let sad = self.block_sad(x, y, side, &prediction);
3428 (sad + lambda * mode_bits[usize::from(mode)], mode)
3429 })
3430 .collect()
3431 }
3432
3433 /// Codes one block under every mode the search offers (or, when
3434 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
3435 /// pre-pass plus DC) and commits the one whose squared error and
3436 /// estimated rate come out cheapest.
3437 ///
3438 /// The prediction is built once per mode regardless -- the full RD trial
3439 /// needs it too -- so ranking modes by SAD on that same prediction before
3440 /// running the expensive part (forward transform, quantize, reconstruct,
3441 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
3442 /// only to sum.
3443 fn search_block(
3444 &mut self,
3445 at: At,
3446 search: &Search,
3447 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
3448 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
3449 let At {
3450 x, y, side, reach, ..
3451 } = at;
3452 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3453 let (above, left, corner) =
3454 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3455 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
3456 // the census reports it), so summing it under the default unpruned
3457 // search is `side * side` absolute differences per mode spent on a
3458 // number no one reads.
3459 let want_sad = search.top_k.is_some() || census_on();
3460 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
3461 .modes
3462 .iter()
3463 .map(|&mode| {
3464 let mut prediction = vec![0u8; side * side];
3465 intra_predict_u8(
3466 mode,
3467 0,
3468 above,
3469 left,
3470 corner,
3471 side,
3472 side,
3473 false,
3474 false,
3475 &mut prediction, fctx,
3476 );
3477 let sad = if want_sad {
3478 self.block_sad(x, y, side, &prediction)
3479 } else {
3480 0.0
3481 };
3482 (
3483 sad + search.lambda * mode_bits[usize::from(mode)],
3484 mode,
3485 prediction,
3486 )
3487 })
3488 .collect();
3489 if let Some(k) = search.top_k {
3490 if k < scored.len() {
3491 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
3492 let dc_entry = dc_pos.map(|i| scored.remove(i));
3493 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3494 scored.truncate(if dc_entry.is_some() {
3495 k.saturating_sub(1)
3496 } else {
3497 k
3498 });
3499 if let Some(dc_entry) = dc_entry {
3500 scored.push(dc_entry);
3501 }
3502 }
3503 }
3504 let ranking: Vec<(f64, u8)> = if census_on() {
3505 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
3506 } else {
3507 Vec::new()
3508 };
3509 census_add(0, 1);
3510 census_add(1, scored.len());
3511 let mut best: Option<(f64, u8, Trial)> = None;
3512 for (_, mode, prediction) in scored {
3513 let trial = self.code_from_prediction(
3514 x,
3515 y,
3516 side,
3517 &prediction,
3518 false,
3519 search.base_q_idx,
3520 search.deadzone,
3521 at.set,
3522 );
3523 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
3524 if best
3525 .as_ref()
3526 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
3527 {
3528 best = Some((cost, mode, trial));
3529 }
3530 }
3531 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
3532 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
3533 // directional modes each carry a -3..=3 delta, three degrees a step,
3534 // which the writer has always coded as ZERO because nothing searched
3535 // it. Refined on the winning mode only -- libaom's own ordering, and
3536 // six extra trials on the directional blocks instead of on every
3537 // block times every mode. The edges are the ones the base angle
3538 // already read (`enable_intra_edge_filter` is off in this encoder's
3539 // sequence header, so no delta changes which samples exist), and the
3540 // predictor is the decoder's, `angle_delta` argument and all.
3541 let mut angle_delta = 0i32;
3542 // Not on a screen frame: measured on the 5-row native gate, the
3543 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
3544 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
3545 // synthetic edges land on the base angles, so every delta there buys
3546 // a symbol and no prediction. Same `search.screen` gate palette and
3547 // intrabc already stand behind.
3548 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
3549 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
3550 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
3551 let mut prediction = vec![0u8; side * side];
3552 for delta in [-3i32, -2, -1, 1, 2, 3] {
3553 intra_predict_u8(
3554 mode,
3555 delta,
3556 above,
3557 left,
3558 corner,
3559 side,
3560 side,
3561 false,
3562 false,
3563 &mut prediction, fctx,
3564 );
3565 let candidate = self.code_from_prediction(
3566 x,
3567 y,
3568 side,
3569 &prediction,
3570 false,
3571 search.base_q_idx,
3572 search.deadzone,
3573 at.set,
3574 );
3575 let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3576 - zero_bits;
3577 let cost_d = candidate.sse
3578 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
3579 if cost_d < cost {
3580 cost = cost_d;
3581 angle_delta = delta;
3582 trial = candidate;
3583 }
3584 }
3585 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
3586 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3587 }
3588 // lane-txset: the block's own transform type, searched on the mode
3589 // and angle the trials above settled -- the same ordering the angle
3590 // refinement uses, and the same RD terms.
3591 let mut tx_type = TxType::DctDct;
3592 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
3593 let candidate = self.trial_typed(
3594 at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx,
3595 );
3596 let cost_t =
3597 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3598 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3599 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3600 // block's true one for the caller's own decision.
3601 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3602 cost = cost_t;
3603 tx_type = candidate_type;
3604 trial = candidate;
3605 }
3606 }
3607 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3608 if census_on() {
3609 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
3610 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3611 }
3612 self.commit(x, y, side, &trial);
3613 // A 64-point transform codes only its top-left 32x32 corner, which is
3614 // the grid `code_from_prediction` hands back (lane-i64).
3615 (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type)
3616 }
3617}
3618
3619/// Where one block sits in its plane, and how far past its own edges its
3620/// prediction may read.
3621#[derive(Clone, Copy)]
3622struct At {
3623 x: usize,
3624 y: usize,
3625 side: usize,
3626 reach: Reach,
3627 /// Which of the tile writer's coefficient tables this block's levels are
3628 /// coded with, and so which the search prices them through.
3629 set: TxbSet,
3630}
3631
3632/// Which of the samples past a block's own edges the decoder has decoded by
3633/// the time it predicts the block, and so which a directional mode may read.
3634///
3635/// The decoder derives these from its `BlockDecoded` flags, which are cleared
3636/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
3637/// that map, this reads the answer the same way libaom and rav1e do: for a
3638/// block whose transform covers it whole, whether the samples above its right
3639/// (or below its left) are decoded depends only on where the block sits inside
3640/// its 64x64 superblock, which is a pinned table per block size.
3641#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3642pub(crate) struct Reach {
3643 pub(crate) above_right: bool,
3644 pub(crate) below_left: bool,
3645}
3646
3647/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
3648/// libaom): for a block that is neither in the superblock's top row nor its
3649/// rightmost column, whether the block above and to its right is coded before
3650/// it. Indexed by the block's position in the superblock, in blocks of its own
3651/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
3652/// 128, not this crate's 64 superblock -- bit by bit from the low end.
3653const HAS_TOP_RIGHT: [&[u8]; 4] = [
3654 &[255, 85, 119, 85, 127, 85, 119, 85],
3655 &[95, 87],
3656 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
3657 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
3658 &[
3659 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
3660 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
3661 ],
3662
3663 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
3664 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
3665 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
3666 // with side 4 outside a TX4 split; without their own row they clamped
3667 // into the 8x8 table and read above-right samples the decoder has not
3668 // written yet (all-zero pixels in the bottom-right triangle of a
3669 // directional 4x4 leaf).
3670 &[
3671 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
3672 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
3673 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
3674 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
3675 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
3676 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
3677 119, 119, 119, 119, 85, 85, 85, 85,
3678 ],
3679];
3680
3681/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
3682/// left.
3683const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
3684 &[84, 16, 84, 0, 84, 16, 84, 0],
3685 &[4, 4],
3686 // has_bl_8x8 (libaom av1/common/reconintra.c)
3687 &[
3688 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
3689 84, 85, 16, 17, 84, 85, 0, 0,
3690 ],
3691
3692 // has_bl_4x4 (same source, same order).
3693 &[
3694 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
3695 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,
3696 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
3697 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,
3698 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
3699 85, 85, 0, 0, 0, 0,
3700 ],
3701];
3702
3703/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
3704/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
3705/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
3706/// rather than in raster order, so the bottom-left square's top-right
3707/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
3708/// libaom switches tables on the partition type (`get_has_tr_table`); the
3709/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
3710/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
3711/// lane-part32 r5 caught reading undecoded samples.
3712const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
3713 // has_tr_vert_16x16
3714 &[255, 0, 119, 0, 127, 0, 119, 0],
3715 // has_tr_vert_32x32
3716 &[15, 7],
3717 // has_tr_vert_8x8
3718 &[
3719 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
3720 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
3721 ],
3722];
3723
3724/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
3725const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
3726 // has_bl_vert_16x16
3727 &[254, 16, 254, 0, 254, 16, 254, 0],
3728 // has_bl_vert_32x32
3729 &[14, 14],
3730 // has_bl_vert_8x8
3731 &[
3732 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
3733 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
3734 ],
3735];
3736
3737thread_local! {
3738 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
3739 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
3740 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
3741 /// threading one bool through this crate's already twenty-argument
3742 /// `decode_block` would touch every call site instead of the two arms
3743 /// that need it.
3744 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3745}
3746
3747/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
3748pub(crate) struct VertAbGuard(bool);
3749
3750impl Drop for VertAbGuard {
3751 fn drop(&mut self) {
3752 VERT_AB_PARTITION.with(|c| c.set(self.0));
3753 }
3754}
3755
3756/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
3757/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
3758/// so no byte is retyped). Each is indexed by
3759/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
3760/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
3761/// superblock grid; on this crate's 64-pixel superblock the highest index a
3762/// shape can reach stays inside its own table, so no wrap is involved.
3763///
3764/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
3765/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
3766/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
3767/// 10 of the 21 reachable superblock positions for above-right and 7 for
3768/// below-left.
3769/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3770const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119];
3771/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3772const HAS_BL_4X8: [u8; 64] = [16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0];
3773/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3774const HAS_TR_8X4: [u8; 64] = [255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0];
3775/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3776const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0];
3777/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3778const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
3779/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3780const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
3781/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3782const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
3783/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3784const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
3785/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3786const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
3787/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3788const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
3789/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3790const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
3791/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3792const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
3793/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3794const HAS_TR_32X64: [u8; 1] = [127];
3795/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3796const HAS_BL_32X64: [u8; 1] = [0];
3797/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3798const HAS_TR_64X32: [u8; 1] = [19];
3799/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3800const HAS_BL_64X32: [u8; 1] = [34];
3801/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3802const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127];
3803/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3804const HAS_BL_4X16: [u8; 32] = [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0];
3805/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3806const HAS_TR_16X4: [u8; 32] = [255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0];
3807/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3808const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0];
3809/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3810const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
3811/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3812const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
3813/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3814const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
3815/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3816const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
3817/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3818const HAS_TR_16X64: [u8; 2] = [255, 127];
3819/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3820const HAS_BL_16X64: [u8; 2] = [0, 0];
3821/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3822const HAS_TR_64X16: [u8; 2] = [3, 1];
3823/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3824const HAS_BL_64X16: [u8; 2] = [42, 42];
3825
3826/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
3827fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
3828 match (bw, bh) {
3829 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
3830 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
3831 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
3832 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
3833 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
3834 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
3835 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
3836 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
3837 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
3838 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
3839 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
3840 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
3841 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
3842 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
3843 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
3844 }
3845}
3846
3847impl Reach {
3848 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3849 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
3850 /// own answer is `block` -- a different rule from the standalone-block
3851 /// tables, because a unit's neighbours are mostly its own block's
3852 /// already-reconstructed units:
3853 /// * top-right: available while the unit to the right is still inside
3854 /// the block (`col_off + tx < bw`); otherwise only the block's top row
3855 /// of units reaches past it, through the block-level answer
3856 /// (libaom's `row_off > 0` branch returns exactly
3857 /// `col_off + txw < plane_bw`).
3858 /// * bottom-left: a unit outside the block's left column has none
3859 /// (libaom returns 0 for `col_off > 0`); inside the block
3860 /// (`row_off + tx < bh`) they are the left unit's, already
3861 /// reconstructed; the bottom row falls back to the block-level answer.
3862 pub(crate) fn of_tu(
3863 bw: usize,
3864 bh: usize,
3865 col_off: usize,
3866 row_off: usize,
3867 // The unit's own width and height in pixels; equal for a square
3868 // transform, different for the rect unit a 1:4 strip's first split
3869 // produces (lane-rectsplitx r1).
3870 tx_w: usize,
3871 tx_h: usize,
3872 block: Self,
3873 ) -> Self {
3874 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
3875 // order, so both libaom predicates special-case it (lane-sb128c r10);
3876 // without this the last unit column of every chunk of a 128x64 block
3877 // predicts from a chunk libaom has not decoded yet.
3878 let wide = bw > 64;
3879 Self {
3880 above_right: if row_off > 0 {
3881 // `has_top_right`'s `row_off > 0` branch: the offset is taken
3882 // modulo the 64-wide chunk, except for the one unit whose
3883 // top-right corner is the centre of a 128x128 block.
3884 if wide {
3885 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
3886 } else {
3887 col_off + tx_w < bw
3888 }
3889 } else if col_off + tx_w < bw {
3890 true
3891 } else {
3892 block.above_right
3893 },
3894 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
3895 // `has_bottom_left`: at the left edge of a right-hand chunk
3896 // the bottom-left pixels are in the already-coded left chunk,
3897 // provided they stay inside it.
3898 (row_off % 64) + tx_h < bh.min(64)
3899 } else if col_off > 0 {
3900 false
3901 } else if row_off + tx_h < bh {
3902 true
3903 } else {
3904 block.below_left
3905 },
3906 }
3907 }
3908
3909 /// What a block of `side` samples at `(x, y)` may read past its own edges,
3910 /// in a frame of `width` by `height`.
3911 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
3912 Self {
3913 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
3914 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
3915 }
3916 }
3917
3918 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
3919 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
3920 /// block's own width for the row stride and by its own height for the
3921 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
3922 /// unlike the square [`Self::of`] which uses one `side` for everything.
3923 pub(crate) fn of_rect(
3924 bw: usize,
3925 bh: usize,
3926 x: usize,
3927 y: usize,
3928 width: usize,
3929 height: usize, fctx: &crate::decode::FrameCtx,
3930 ) -> Self {
3931 Self {
3932 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
3933 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
3934 }
3935 }
3936
3937 /// [`Self::of`] for one transform unit of a square block whose transform
3938 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
3939 /// non-zero `row_off`/`col_off`): interior units answer from the block's
3940 /// own geometry, and only a unit on the block's top row (resp. left
3941 /// column) reaches the table -- which is the BLOCK's table read at the
3942 /// BLOCK's position, never a table row for the transform's size. Letting
3943 /// the unit stand in for a block of its own size agrees with libaom for
3944 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
3945 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
3946 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
3947 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
3948 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
3949 /// the transform covering the whole block, luma): everything before the
3950 /// table lookup is that function's own early-exit ladder.
3951 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3952 let sb_mi: usize = reach_sb_px(fctx) / 4;
3953 let (mi_row, mi_col) = (y / 4, x / 4);
3954 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3955 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3956 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3957 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3958 // Top row of the superblock: the top-right pixels are in the (already
3959 // decoded) superblock above.
3960 if blk_row == 0 {
3961 return true;
3962 }
3963 // Rightmost column: they fall in the superblock to the right.
3964 if ((blk_col + 1) << bw_log2) >= sb_mi {
3965 return false;
3966 }
3967 let table = rect_reach_tables(bw, bh).0;
3968 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
3969 }
3970
3971 /// libaom `has_top_right`'s own index arithmetic:
3972 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
3973 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
3974 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
3975 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
3976 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
3977 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
3978 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
3979 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
3980 (blk_row << (5 - bw_log2)) + blk_col
3981 }
3982
3983 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
3984 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3985 let sb_mi: usize = reach_sb_px(fctx) / 4;
3986 let (mi_row, mi_col) = (y / 4, x / 4);
3987 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3988 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3989 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3990 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3991 // Leftmost column of the superblock: the bottom-left pixels are in
3992 // the left superblock iff they stay inside its height.
3993 if blk_col == 0 {
3994 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
3995 }
3996 // Bottom row (and not the leftmost column): they fall in the
3997 // superblock below, which is not decoded yet.
3998 if ((blk_row + 1) << bh_log2) >= sb_mi {
3999 return false;
4000 }
4001 let table = rect_reach_tables(bw, bh).1;
4002 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4003 }
4004
4005 /// Marks every [`Reach::of`] made until the returned guard drops as being
4006 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
4007 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
4008 /// unaffected: libaom's own comment says vertical rectangles keep their
4009 /// non-vert table, which is what [`Reach::of_rect`] already reads.
4010 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
4011 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
4012 /// can count the sub-block work that partition creates (lane-ab16).
4013 pub(crate) fn in_vert_ab() -> bool {
4014 VERT_AB_PARTITION.with(std::cell::Cell::get)
4015 }
4016
4017 pub(crate) fn vert_ab_partition() -> VertAbGuard {
4018 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
4019 }
4020
4021 /// Neither, which is all a mode that reads no further than its own edges
4022 /// needs.
4023 pub(crate) fn none() -> Self {
4024 Self {
4025 above_right: false,
4026 below_left: false,
4027 }
4028 }
4029
4030 /// `has_top_right` for a block whose transform covers it whole: the top
4031 /// row of a superblock reads into the superblock above, which is decoded;
4032 /// the rightmost column would read into the superblock to the right, which
4033 /// is not; and everything between is the table's to answer.
4034 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4035 let (row, col, per_side) = Self::position(side, x, y, fctx);
4036 if row == 0 {
4037 return true;
4038 }
4039 if col + 1 == per_side {
4040 return false;
4041 }
4042 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4043 // (the clamp corner-cut that used to live here is gone); sides
4044 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4045 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4046 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4047 // -- a reach over-estimate (extra above-right reference pixels),
4048 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4049 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4050 // NB: named `table_row`, not `row` -- `row` above is the block's
4051 // position inside the superblock and is what the bit index below
4052 // steps by (a merge that shadowed it desynced every block size).
4053 let table_row = Self::table(side);
4054 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
4055 HAS_TOP_RIGHT_VERT[table_row]
4056 } else {
4057 HAS_TOP_RIGHT[table_row]
4058 };
4059 Self::bit(
4060 table,
4061 (row * Self::table_stride(side) + col) % (table.len() * 8),
4062 )
4063 }
4064
4065 /// `has_bottom_left` for such a block: the leftmost column of a superblock
4066 /// reads into the superblock to its left, which is decoded only as far
4067 /// down as its own bottom; the bottom row would read into the superblock
4068 /// below, which is not decoded at all; and the table answers the rest.
4069 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4070 let (row, col, per_side) = Self::position(side, x, y, fctx);
4071 if col == 0 {
4072 return row * side + side < reach_sb_px(fctx);
4073 }
4074 if row + 1 == per_side {
4075 return false;
4076 }
4077 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4078 // (the clamp corner-cut that used to live here is gone); sides
4079 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4080 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4081 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4082 // -- a reach over-estimate (extra above-right reference pixels),
4083 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4084 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4085 // NB: named `table_row`, not `row` -- `row` above is the block's
4086 // position inside the superblock and is what the bit index below
4087 // steps by (a merge that shadowed it desynced every block size).
4088 let table_row = Self::table(side);
4089 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
4090 HAS_BOTTOM_LEFT_VERT[table_row]
4091 } else {
4092 HAS_BOTTOM_LEFT[table_row]
4093 };
4094 Self::bit(
4095 table,
4096 (row * Self::table_stride(side) + col) % (table.len() * 8),
4097 )
4098 }
4099
4100 /// Where a block sits inside its superblock, in blocks of its own size,
4101 /// and how many of them a superblock is across.
4102 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
4103 let sb = reach_sb_px(fctx);
4104 ((y % sb) / side, (x % sb) / side, sb / side)
4105 }
4106
4107 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
4108 /// these tables to its compile-time maximum superblock (128, spec
4109 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
4110 /// size an encode actually uses, so a block's row in the bit index steps
4111 /// by 128 / `side` even though this crate only ever codes a 64
4112 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
4113 /// here instead indexes the wrong bit for every block size but the one
4114 /// where 64 and 128 give the same stride.
4115 fn table_stride(side: usize) -> usize {
4116 128 / side
4117 }
4118
4119 /// Which of the three block sizes the encoder codes a table row is for.
4120 fn table(side: usize) -> usize {
4121 if side == BLOCK {
4122 1
4123 } else if side == 8 {
4124 2
4125 } else if side == 4 {
4126 3
4127 } else {
4128 0
4129 }
4130 }
4131
4132 /// One bit of a table, counting from the low end of its first byte.
4133 fn bit(table: &[u8], index: usize) -> bool {
4134 (table[index / 8] >> (index % 8)) & 1 != 0
4135 }
4136}
4137
4138/// What one symbol costs against a CDF, in bits.
4139/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
4140/// search, the frame header's `allow_warped_motion` and the sequence's
4141/// `enable_warped_motion`, all three together. ON by default since
4142/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
4143/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
4144/// bits -- back off for an A/B on one build.
4145pub(crate) fn warp_on() -> bool {
4146 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4147 crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
4148 });
4149 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
4150}
4151
4152/// The smallest LEAF an OBMC candidate is offered for, so the census can
4153/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
4154/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
4155/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
4156///
4157/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
4158/// (12 frames, four quantizers, the standing keep table):
4159///
4160/// | min side | film 1080p | film 2160p | screen |
4161/// |---|---|---|---|
4162/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
4163/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
4164/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
4165/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
4166///
4167/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
4168/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
4169/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
4170/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
4171/// that wins the local RD on five blocks in six and loses ladder bytes is
4172/// the `local-RD-on-references` class again, not a missing footprint.
4173///
4174/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
4175/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
4176/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
4177/// loss on the 1080p film became a 0.3-point win and the other two rows went
4178/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
4179/// of the "local win, ladder loss" it was charged with was the rate weight.
4180/// It still does not meet the keep rule (two down, one flat, both columns).
4181/// The tool stays OFF by default; the upgrade path is the price, not the size
4182/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
4183/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
4184/// 1080p film up, i.e. the same disagreement between the two gates).
4185///
4186/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
4187/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
4188/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
4189/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
4190/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
4191/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
4192/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
4193/// the margin's gain are the same bytes. It stays OFF.
4194///
4195/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
4196/// judgement above was taken when the gate's "film" rows were the `testsrc2`
4197/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
4198/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
4199/// the standing native keep table (`bd_rate_screen_native`):
4200///
4201/// | arm | film A | film B | screen | OBMC fire A/B |
4202/// |---|---|---|---|---|
4203/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
4204/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
4205/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
4206///
4207/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
4208/// only), where the anchors' non-skip area is the known gap:
4209///
4210/// | arm | film B long GOP | wall ours |
4211/// |---|---|---|
4212/// | off (control) | +89.8 / +9.1 | 477.5s |
4213/// | min side 8 | +89.6 / +9.0 | 514.1s |
4214///
4215/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
4216/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
4217/// only at min side 16, which is exactly where film B loses 0.7 on both
4218/// columns. Nothing here meets the keep rule (both films down on both
4219/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
4220/// costs +7.7% wall. OBMC stays OFF at every preset.
4221fn obmc_min_side() -> usize {
4222 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4223 *N.get_or_init(|| {
4224 std::env::var("EC_AV1_OBMC_MIN")
4225 .ok()
4226 .and_then(|v| v.parse().ok())
4227 .unwrap_or(8)
4228 })
4229}
4230
4231/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
4232/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
4233/// same frame-CDF price the coefficients of a non-screen frame are estimated
4234/// with, not the static default table.
4235/// The same price for whichever alphabet the writer will really use for this
4236/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
4237/// (`allow_warped_motion` and at least one warp sample), otherwise the
4238/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
4239/// search pay it, so the alphabet cancels out of a comparison and only its
4240/// per-value spread decides.
4241fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
4242 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
4243 return 0.0;
4244 };
4245 match warp_alphabet {
4246 true => crate::tile::motion_mode_symbol_bits(row, motion),
4247 false => crate::tile::obmc_symbol_bits(row, motion == 1),
4248 }
4249}
4250
4251/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
4252/// candidate, the header's `allow_warped_motion` and the sequence's
4253/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
4254/// native keep table, against the same build with the knob off:
4255///
4256/// | clip | warp on | off |
4257/// |---|---|---|
4258/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
4259/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
4260/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
4261///
4262/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
4263/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
4264/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
4265/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
4266/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
4267/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
4268/// this is a measured loss, not an inert knob. Same shape as the OBMC
4269/// candidate above it (`obmc_min_side`): a local RD win that does not convert
4270/// into ladder bytes.
4271///
4272/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
4273/// because a tool whose gain is local and whose cost is the rate it adds is
4274/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
4275///
4276/// | clip | warp on | off (both at lambda 0.05) |
4277/// |---|---|---|
4278/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
4279/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
4280/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
4281///
4282/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
4283/// column inside 0.1 everywhere -- which reads as a keep rather than the
4284/// 0.7/0.9 loss it was.
4285///
4286/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
4287/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
4288/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
4289/// ran the conformance shape the lambda lane deferred: every warp stream
4290/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
4291/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
4292/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
4293/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
4294/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
4295/// `allow_warped_motion` and `enable_warped_motion` back off together.
4296///
4297/// The WARPED_CAUSAL prediction of one square single-reference block: the
4298/// decoder's own warp-sample walk (`decode::find_samples` +
4299/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
4300/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
4301/// grid -- never a second implementation of any of the three. `None` when the
4302/// block would code no motion_mode symbol at all, when it has no warp sample
4303/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
4304/// or when the projection is not filter-representable (the decoder would then
4305/// predict translationally, so the mode is pure cost).
4306#[allow(clippy::too_many_arguments)]
4307fn warp_prediction(
4308 grid: &MiGrid,
4309 (mi_row, mi_col): (usize, usize),
4310 (mi_rows, mi_cols): (usize, usize),
4311 (x, y): (usize, usize),
4312 side: usize,
4313 mv: (i32, i32),
4314 ref_frame: i8,
4315 ref_planes: [(&[u16], usize, usize, usize); 3],
4316 fctx: &crate::decode::FrameCtx,
4317) -> Option<[Vec<u8>; 3]> {
4318 let n4 = side / 4;
4319 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
4320 return None;
4321 }
4322 let mut samples = crate::decode::find_samples(
4323 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
4324 );
4325 if samples.is_empty() {
4326 return None;
4327 }
4328 if samples.len() > 1 {
4329 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
4330 }
4331 let params = crate::warp::find_projection(
4332 &samples,
4333 side as i32,
4334 side as i32,
4335 mv.1,
4336 mv.0,
4337 mi_row as i32,
4338 mi_col as i32,
4339 )?;
4340 let mut pred = [
4341 vec![0u16; side * side],
4342 vec![0u16; side * side / 4],
4343 vec![0u16; side * side / 4],
4344 ];
4345 // The translational prediction first, exactly as the decoder builds it,
4346 // then the affine one over the planes whose OWN block is at least 8x8
4347 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
4348 // 4x4 chroma stays translational).
4349 for (i, r) in ref_planes.into_iter().enumerate() {
4350 let luma_plane = i == 0;
4351 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
4352 let s = if luma_plane { side } else { side / 2 };
4353 mc::predict(
4354 r.0,
4355 r.1,
4356 r.2,
4357 r.3,
4358 mv_to_q4(px, mv.1, luma_plane),
4359 mv_to_q4(py, mv.0, luma_plane),
4360 s,
4361 s,
4362 &mut pred[i],
4363 fctx,
4364 );
4365 if crate::decode::warp_plane_allowed(s, s) {
4366 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
4367 crate::warp::warp_affine(
4368 &params,
4369 r.0,
4370 r.2 as i32,
4371 r.3 as i32,
4372 r.1 as i32,
4373 &mut pred[i],
4374 px as i32,
4375 py as i32,
4376 cside,
4377 cside,
4378 cside,
4379 sub,
4380 sub,
4381 fctx,
4382 );
4383 }
4384 }
4385 let [py_buf, pu_buf, pv_buf] = pred;
4386 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4387 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4388}
4389
4390/// What tile.rs' `write_compound_ref_frames` pays for the pair
4391/// `(ref0, ref1)`, symbol for symbol, each at the context its own
4392/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
4393/// derives from the block's above/left neighbours -- plus the `comp_mode`
4394/// symbol itself at `reference_mode_ctx`.
4395///
4396/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
4397/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
4398/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
4399/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4400pub(crate) fn compound_ref_bits(
4401 (ref0, ref1): (i8, i8),
4402 stack: &crate::mvstack::MvStack,
4403) -> f64 {
4404 use crate::mvstack::{
4405 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4406 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
4407 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
4408 uni_comp_ref_p1_ctx,
4409 };
4410 let (a, a1) = stack.above_refs;
4411 let (l, l1) = stack.left_refs;
4412 let unidir = is_uni_comp_ref(ref0, ref1);
4413 let comp_mode = symbol_bits(
4414 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4415 1,
4416 );
4417 let ref_type = symbol_bits(
4418 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
4419 usize::from(!unidir),
4420 );
4421 if unidir {
4422 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
4423 let p0 = symbol_bits(
4424 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4425 usize::from(both_backward),
4426 );
4427 if both_backward {
4428 return comp_mode + ref_type + p0;
4429 }
4430 let past_last2 = ref1 != LAST2_FRAME;
4431 let p1 = symbol_bits(
4432 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
4433 usize::from(past_last2),
4434 );
4435 let p2 = if past_last2 {
4436 symbol_bits(
4437 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4438 usize::from(ref1 == GOLDEN_FRAME),
4439 )
4440 } else {
4441 0.0
4442 };
4443 return comp_mode + ref_type + p0 + p1 + p2;
4444 }
4445 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
4446 let fwd = symbol_bits(
4447 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
4448 usize::from(far),
4449 ) + if far {
4450 symbol_bits(
4451 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4452 usize::from(ref0 == GOLDEN_FRAME),
4453 )
4454 } else {
4455 symbol_bits(
4456 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
4457 usize::from(ref0 == LAST2_FRAME),
4458 )
4459 };
4460 let is_altref = ref1 == ALTREF_FRAME;
4461 let bwd = symbol_bits(
4462 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
4463 usize::from(is_altref),
4464 ) + if is_altref {
4465 0.0
4466 } else {
4467 symbol_bits(
4468 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
4469 usize::from(ref1 == ALTREF2_FRAME),
4470 )
4471 };
4472 comp_mode + ref_type + fwd + bwd
4473}
4474
4475/// What the `skip` symbol costs at the context tile.rs really codes it with
4476/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
4477/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
4478/// exactly the difference between this symbol's two values, so the row it is
4479/// read from moves that decision (class pricer-context-zero, lane-ctx).
4480pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
4481 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
4482 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
4483}
4484
4485/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
4486/// neighbours' intra/inter state, with an out-of-tile side contributing
4487/// nothing, off the same two cells (lane-ctx).
4488pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
4489 let ctx = crate::tile::intra_inter_ctx(
4490 stack.above_nbr.is_some(),
4491 stack.left_nbr.is_some(),
4492 stack.above_nbr.is_some_and(|n| n.is_inter),
4493 stack.left_nbr.is_some_and(|n| n.is_inter),
4494 );
4495 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
4496}
4497
4498/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
4499/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
4500/// context -- zero on a frame that carries no `reference_select` bit, where
4501/// the writer codes no symbol at all.
4502fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
4503 if !reference_select() {
4504 return 0.0;
4505 }
4506 symbol_bits(
4507 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4508 0,
4509 )
4510}
4511
4512/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
4513/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
4514/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
4515/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
4516/// LAST is p1=0,p3=0,p4=0,
4517/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
4518/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
4519/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
4520/// symbols off the wrong CDFs -- which is what made the search believe an
4521/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
4522/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
4523/// paid nothing at all, so compound was overcharged by the whole symbol.
4524pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
4525 use crate::mvstack::{
4526 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4527 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4528 single_ref_p5_ctx, single_ref_p6_ctx,
4529 };
4530 let (a, a1) = stack.above_refs;
4531 let (l, l1) = stack.left_refs;
4532 let comp_mode = comp_mode_single_bits(stack);
4533 let backward = ref_frame >= BWDREF_FRAME;
4534 let p1 = symbol_bits(
4535 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4536 usize::from(backward),
4537 );
4538 if backward {
4539 let is_altref = ref_frame == ALTREF_FRAME;
4540 let p2 = symbol_bits(
4541 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
4542 usize::from(is_altref),
4543 );
4544 return comp_mode
4545 + p1
4546 + p2
4547 + if is_altref {
4548 0.0
4549 } else {
4550 symbol_bits(
4551 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
4552 usize::from(ref_frame == ALTREF2_FRAME),
4553 )
4554 };
4555 }
4556 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4557 comp_mode + p1 + symbol_bits(
4558 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4559 usize::from(far),
4560 ) + if far {
4561 symbol_bits(
4562 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4563 usize::from(ref_frame == GOLDEN_FRAME),
4564 )
4565 } else {
4566 symbol_bits(
4567 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4568 usize::from(ref_frame == LAST2_FRAME),
4569 )
4570 }
4571}
4572
4573pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
4574 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
4575 let width = cdf[symbol] - low;
4576 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
4577 // 32769 prices a symbol can carry; the `log2` behind each is computed
4578 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
4579 // profile -- this function is called for every symbol of every candidate
4580 // the RD search prices). Each entry is exactly the expression this used
4581 // to evaluate, so every price is bit-identical.
4582 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
4583 PRICES.get_or_init(|| {
4584 (0..=32768u32)
4585 .map(|w| -(f64::from(w) / 32768.0).log2())
4586 .collect()
4587 })[usize::from(width)]
4588}
4589
4590/// What the tile writer spends to say a block is coded in each of the thirteen
4591/// modes, given the modes of the blocks above it and to its left: the luma mode
4592/// symbol against the CDF those two neighbours pick, the angle delta a
4593/// directional mode carries, and the chroma mode symbol, whose CDF the luma
4594/// mode itself indexes.
4595///
4596/// Without this the search is blind to what a mode costs to name, which is not
4597/// a rounding error: a directional mode on a picture that does not run that way
4598/// is a rate loss the squared error never sees.
4599/// Codes one square of the picture as a single block: searches the luma mode,
4600/// codes both chroma planes DC, and hands back the block and what it cost --
4601/// squared error plus lambda times the bits its symbols spend.
4602/// How many halvings of a `side`-square block's transform the `tx_depth`
4603/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
4604/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
4605fn max_tx_depth(side: usize) -> usize {
4606 match side {
4607 8 => 1,
4608 16 | 32 => 2,
4609 _ => 0,
4610 }
4611}
4612
4613/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
4614/// Priced at context row 0 -- the writer picks the real row from its
4615/// neighbours' transform sizes, which the search has no view of; the term is
4616/// the same for every depth of one block either way, so it only shifts the
4617/// depth-0-versus-split margin, never the ordering between two splits.
4618fn tx_depth_bits(side: usize, depth: usize) -> f64 {
4619 match side {
4620 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
4621 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
4622 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
4623 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
4624 }
4625}
4626
4627/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4628/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4629/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4630/// (the mode search's own weight); below 1 the split trial is charged less
4631/// for its bits and fires more often.
4632///
4633/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4634/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4635/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4636/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4637/// so what is mis-calibrated is the weight the split's rate is judged under,
4638/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4639pub(crate) fn split_lambda_mult() -> f64 {
4640 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4641 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4642 .ok()
4643 .and_then(|v| v.parse().ok())
4644 .unwrap_or(SPLIT_LAMBDA)
4645 });
4646 *M
4647}
4648
4649/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4650/// the sweep that chose it.
4651const SPLIT_LAMBDA: f64 = 1.0;
4652
4653/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4654/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
4655/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
4656/// trials offered, trials the split won, then the (rate, distortion) of the
4657/// split and flat arms summed apart for the split-won and flat-won trials --
4658/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
4659static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
4660 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
4661
4662/// Whether [`SPLIT_CENSUS`] is armed, read once.
4663pub(crate) fn split_census_on() -> bool {
4664 static ON: std::sync::LazyLock<bool> =
4665 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
4666 *ON
4667}
4668
4669/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
4670/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
4671fn split_census_base(site: usize, key: bool, side: usize) -> usize {
4672 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
4673 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
4674}
4675
4676/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
4677/// `(rate in bits, distortion as squared error)`.
4678fn split_census(
4679 site: usize,
4680 key: bool,
4681 side: usize,
4682 split_won: bool,
4683 split: (f64, f64),
4684 flat: (f64, f64),
4685) {
4686 use std::sync::atomic::Ordering::Relaxed;
4687 let base = split_census_base(site, key, side);
4688 let add = |i: usize, v: u64| {
4689 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
4690 };
4691 add(0, 1);
4692 let off = if split_won {
4693 add(1, 1);
4694 2
4695 } else {
4696 6
4697 };
4698 let (win, lose) = if split_won { (split, flat) } else { (flat, split) };
4699 add(off, (win.0 * 64.0).max(0.0) as u64);
4700 add(off + 1, win.1.max(0.0) as u64);
4701 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
4702 add(off + 3, lose.1.max(0.0) as u64);
4703}
4704
4705/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
4706/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
4707/// last table a run prints is the whole encode's total (there is no flush
4708/// hook the encoder API guarantees to reach).
4709pub(crate) fn dump_split_census() {
4710 use std::sync::atomic::Ordering::Relaxed;
4711 eprintln!(
4712 "SPLITCENSUS site frame side offered split share% \
4713 win_rate win_dist lose_rate lose_dist"
4714 );
4715 for site in 0..2 {
4716 for key in [true, false] {
4717 for side_idx in 0..4 {
4718 let base = split_census_base(site, key, 8 << side_idx);
4719 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
4720 if v[0] == 0 {
4721 continue;
4722 }
4723 let (n, s) = (v[0] as f64, v[1] as f64);
4724 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
4725 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
4726 // all `n` trials, not a mean of two means.
4727 eprintln!(
4728 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
4729 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
4730 if site == 0 { "intra" } else { "inter" },
4731 if key { "key " } else { "inter" },
4732 8 << side_idx,
4733 v[0],
4734 v[1],
4735 100.0 * s / n,
4736 (v[2] + v[6]) as f64 / n / 64.0,
4737 (v[3] + v[7]) as f64 / n,
4738 (v[4] + v[8]) as f64 / n / 64.0,
4739 (v[5] + v[9]) as f64 / n,
4740 );
4741 }
4742 }
4743 }
4744}
4745
4746/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
4747/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
4748/// its mode/reference syntax and not the search's own cost function
4749/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
4750/// control; below 1 a coded vector is charged less and `NEWMV` wins more
4751/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
4752pub(crate) fn mv_lambda_mult() -> f64 {
4753 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4754 crate::envflags::var("EC_AV1_MV_LAMBDA")
4755 .ok()
4756 .and_then(|v| v.parse().ok())
4757 .unwrap_or(MV_LAMBDA)
4758 });
4759 *M
4760}
4761
4762/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
4763const MV_LAMBDA: f64 = 1.0;
4764
4765/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
4766/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
4767/// which the RD cost multiplies by lambda). Zero at the default weight.
4768fn mv_rate_surcharge(mv_bits: f64) -> f64 {
4769 (mv_lambda_mult() - 1.0) * mv_bits
4770}
4771
4772/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
4773/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
4774/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
4775/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
4776/// cost it won by, 4 the summed cost it lost by, 5 the summed
4777/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
4778/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
4779/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
4780/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
4781/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
4782static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
4783 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
4784
4785/// Whether [`NEWMV_CENSUS`] is armed, read once.
4786pub(crate) fn newmv_census_on() -> bool {
4787 static ON: std::sync::LazyLock<bool> =
4788 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
4789 *ON
4790}
4791
4792/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
4793fn newmv_census_global(i: usize) {
4794 if newmv_census_on() {
4795 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4796 }
4797}
4798
4799/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
4800/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
4801/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
4802/// candidate's own; both `f64::INFINITY` is a block that offered neither.
4803fn newmv_census_block(
4804 side: usize,
4805 offered: bool,
4806 new_cost: f64,
4807 other_cost: f64,
4808 mv: (i32, i32),
4809 nearest: (i32, i32),
4810 mv_bits: f64,
4811) {
4812 if !newmv_census_on() {
4813 return;
4814 }
4815 use std::sync::atomic::Ordering::Relaxed;
4816 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
4817 let add = |i: usize, v: u64| {
4818 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
4819 };
4820 add(0, 1);
4821 if !offered {
4822 return;
4823 }
4824 add(1, 1);
4825 if new_cost < other_cost {
4826 add(2, 1);
4827 add(3, (other_cost - new_cost).max(0.0) as u64);
4828 } else {
4829 add(4, (new_cost - other_cost).max(0.0) as u64);
4830 }
4831 add(5, ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64);
4832 if mv == nearest {
4833 add(6, 1);
4834 }
4835 add(7, (mv_bits * 64.0).max(0.0) as u64);
4836}
4837
4838/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
4839/// same guard [`dump_split_census`] rides (cumulative, so the last table a
4840/// run prints is the whole encode's).
4841pub(crate) fn dump_newmv_census() {
4842 use std::sync::atomic::Ordering::Relaxed;
4843 eprintln!(
4844 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
4845 mv_dist_q3 mv==nearest% mv_bits"
4846 );
4847 for side_idx in 0..4 {
4848 let base = side_idx * 8;
4849 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
4850 if v[0] == 0 {
4851 continue;
4852 }
4853 let off = v[1].max(1) as f64;
4854 eprintln!(
4855 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
4856 8 << side_idx,
4857 v[0],
4858 v[1],
4859 v[2],
4860 100.0 * v[2] as f64 / off,
4861 v[3] as f64 / v[2].max(1) as f64,
4862 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
4863 v[5] as f64 / off,
4864 100.0 * v[6] as f64 / off,
4865 v[7] as f64 / off / 64.0,
4866 );
4867 }
4868 // lane-hpmv: how many mv components this encode coded an eighth-pel bit
4869 // for, and how many of those named a vector no non-hp frame can code.
4870 let (hp_all, hp_eighth) = crate::tile::hp_symbols();
4871 eprintln!(
4872 "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)",
4873 100.0 * hp_eighth as f64 / hp_all.max(1) as f64,
4874 );
4875 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
4876 eprintln!(
4877 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
4878 leaf second reference {}/{} ({:.1}%)",
4879 g[1],
4880 g[0],
4881 100.0 * g[1] as f64 / g[0].max(1) as f64,
4882 g[3],
4883 g[2],
4884 100.0 * g[3] as f64 / g[2].max(1) as f64,
4885 );
4886 let [calls, evals, _subpel, rounds, near_pred, unmoved, widest, widest_moves] =
4887 crate::motion::take_census();
4888 let per = |n: u64| n as f64 / calls.max(1) as f64;
4889 eprintln!(
4890 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
4891 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
4892 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
4893 per(evals),
4894 per(rounds),
4895 100.0 * near_pred as f64 / calls.max(1) as f64,
4896 100.0 * unmoved as f64 / calls.max(1) as f64,
4897 100.0 * widest as f64 / calls.max(1) as f64,
4898 per(widest_moves),
4899 );
4900}
4901
4902/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
4903/// the intra witness's fire count stays its own.
4904pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4905 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4906
4907/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
4908/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
4909/// `0` compares types on reconstruction error alone, which is what separates
4910/// a rate-term calibration (class `rd-rate-term-calibration`) from a
4911/// distortion the trial mis-measures.
4912pub(crate) fn tx_type_lambda_mult() -> f64 {
4913 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4914 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
4915 .ok()
4916 .and_then(|v| v.parse().ok())
4917 .unwrap_or(1.0)
4918 });
4919 *M
4920}
4921
4922/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
4923/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
4924/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
4925/// question needs: at weight 1 the five-type intra search spends 1.2% more
4926/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
4927/// of the type it picks.
4928pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
4929 if tx_type == TxType::DctDct {
4930 0.0
4931 } else {
4932 lambda * (tx_type_lambda_mult() - 1.0) * bits
4933 }
4934}
4935
4936/// lane-txrd instrument: over the FLAT inter luma decision, the summed
4937/// reconstruction error and priced bits of the type the search chose against
4938/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
4939/// integer counter. `EC_AV1_TXRD_CENSUS`.
4940pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
4941 std::sync::atomic::AtomicU64::new(0),
4942 std::sync::atomic::AtomicU64::new(0),
4943 std::sync::atomic::AtomicU64::new(0),
4944 std::sync::atomic::AtomicU64::new(0),
4945 std::sync::atomic::AtomicU64::new(0),
4946 std::sync::atomic::AtomicU64::new(0),
4947 std::sync::atomic::AtomicU64::new(0),
4948];
4949
4950/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
4951/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
4952#[cfg(test)]
4953pub(crate) fn take_txrd_stats() -> [u64; 7] {
4954 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4955}
4956
4957/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
4958#[cfg(test)]
4959pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
4960 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4961}
4962
4963/// How many luma transform units resolved to each [`TxType`], indexed by the
4964/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
4965/// and the instrument that says which types the search actually reaches.
4966pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4967 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4968
4969/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
4970/// counts to its own encode.
4971#[cfg(test)]
4972pub(crate) fn take_tx_type_hits() -> [usize; 16] {
4973 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4974}
4975
4976/// How many blocks resolved to each `tx_depth`, the fire count that says
4977/// whether the depth search below reaches its candidates at all.
4978static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
4979 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
4980
4981/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
4982/// to its own encode.
4983#[cfg(test)]
4984pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
4985 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
4986}
4987
4988/// How many inter blocks resolved to each var-tx depth (0 = one transform
4989/// over the whole block, 1 = its four halves), the fire count a gate prints
4990/// to see the split search reach its candidates at all. Indexed
4991/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
4992/// says which of the four block classes the split reaches -- the 32x32 root
4993/// and the compound blocks are this lane's two new ones.
4994static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
4995 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
4996
4997/// Whether a 32x32 inter winner searches its own var-tx depth (the four
4998/// 16x16 units against the flat transform) instead of coding depth 0 blind.
4999/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
5000///
5001/// Rejected three times on the bars rows of the native gate (flat to +0.3).
5002/// lane-av1resweep re-judged it on the two REAL film crops at
5003/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
5004/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
5005///
5006/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
5007/// |---|---|---|---|
5008/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
5009/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
5010/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
5011/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
5012/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
5013///
5014/// The bars rows are ~90% zero-intra-cost cells, so the split never had
5015/// residual to reach there -- the tool was being judged on content that
5016/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
5017fn tx32_depth_search() -> bool {
5018 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5019 crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5020 });
5021 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
5022}
5023
5024/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
5025/// trial units have to be predicted from BOTH references
5026/// ([`mc_trial_compound`]) or the split would re-predict them by single-
5027/// reference translation, which is not what the decoder reconstructs.
5028/// ON by default (the table on [`tx32_depth_search`]: on real film it is
5029/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
5030/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
5031/// `EC_AV1_COMP_VARTX`.
5032fn compound_var_tx() -> bool {
5033 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5034 crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5035 });
5036 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
5037}
5038
5039/// How many 32x32-and-below inter blocks each reference frame won, indexed by
5040/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
5041/// fire count a gate prints to see an extra reference reach a block at all
5042/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
5043/// chosen is a pyramid that costs bytes and buys nothing).
5044static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
5045 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5046
5047/// Reads [`REF_FRAME_HITS`] and zeroes it.
5048#[cfg(test)]
5049pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
5050 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
5051}
5052
5053/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
5054#[cfg(test)]
5055pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
5056 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5057}
5058
5059/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
5060/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
5061/// is one flag, depth 1 is a split root plus one unsplit flag per child
5062/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
5063/// or a 4x4 sub-size).
5064fn txfm_split_bits(side: usize, depth: usize) -> f64 {
5065 let max_tx = side.min(64);
5066 let ctx = |tx: usize| {
5067 crate::decode::txfm_partition_ctx_rect(
5068 crate::decode::TXFM_CTX_INIT,
5069 crate::decode::TXFM_CTX_INIT,
5070 side,
5071 tx,
5072 tx,
5073 )
5074 };
5075 if depth == 0 {
5076 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
5077 }
5078 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
5079 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
5080}
5081
5082/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
5083/// type is never coded -- the decoder takes the LUMA type of the block's
5084/// chroma-reference position and reduces it to the set the chroma size allows
5085/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
5086/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
5087/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
5088/// basis they were never produced for: on the bars gate row the luma of the
5089/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
5090/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
5091/// collapse two lanes attributed to the type PRICE (class
5092/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
5093/// field the encoder never mirrored).
5094///
5095/// Re-codes the two chroma planes of a committed inter block at the type the
5096/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
5097/// the trials the caller already holds are right.
5098#[allow(clippy::too_many_arguments)]
5099fn recode_inter_chroma(
5100 chroma: &[Plane; 2],
5101 (x, y): (usize, usize),
5102 side: usize,
5103 mv: (i32, i32),
5104 refs: [(&[u16], usize, usize, usize); 2],
5105 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
5106 search: &Search,
5107 set: TxbSet,
5108 luma_tx_type: TxType,
5109 fctx: &crate::decode::FrameCtx,
5110) -> Option<[Trial; 2]> {
5111 let c = side / 2;
5112 let tx = crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
5113 if tx == TxType::DctDct {
5114 return None;
5115 }
5116 Some([0usize, 1].map(|p| match second {
5117 Some((mv1, r1)) => mc_trial_compound_typed(
5118 &chroma[p], x / 2, y / 2, c, (mv, mv1), false, refs[p], r1[p], search.base_q_idx,
5119 search.deadzone, set, tx, fctx,
5120 ),
5121 None => mc_trial_typed(
5122 &chroma[p], x / 2, y / 2, c, mv, false, refs[p].0, refs[p].1, refs[p].2, refs[p].3,
5123 false, search.base_q_idx, search.deadzone, set, tx, fctx,
5124 ),
5125 }))
5126}
5127
5128/// The inter block's own var-tx decision, once its motion vector is settled:
5129/// its residual as ONE transform over the whole block, or as the four
5130/// transforms of half the side the tree's first halving names. The prediction
5131/// is the same motion compensation either way, so the split trial
5132/// re-transforms the identical residual in four pieces -- it wins where four
5133/// small transforms carry a locally varying residual cheaper than one big
5134/// one. Commits the winner into `luma` and hands back its block-coordinate
5135/// levels, the depth the writer codes and the cost the winner adds to (or
5136/// takes off) the caller's already-computed flat cost.
5137///
5138/// Only for a block wholly inside the frame: past the true edge the reader's
5139/// var-tx recursion skips the units that fall outside
5140/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
5141/// leave the residual units this writes unpaired.
5142#[allow(clippy::too_many_arguments)]
5143fn commit_inter_luma(
5144 luma: &mut Plane,
5145 (x, y): (usize, usize),
5146 side: usize,
5147 mv: (i32, i32),
5148 reference: (&[u16], usize, usize, usize),
5149 search: &Search,
5150 flat: &Trial,
5151 skip: bool,
5152 // A COMPOUND winner's second half: the vector and reference planes the
5153 // trial units are blended from ([`mc_trial_compound`], the decoder's own
5154 // `comp_group_idx == 0` average). `None` is the single-reference block.
5155 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
5156 fctx: &crate::decode::FrameCtx,
5157) -> (Vec<i32>, u8, f64, Vec<TxType>) {
5158 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
5159 // type out of the two-type inter set the writer already codes a symbol
5160 // for, priced the same way the intra search is (sse + lambda * bits, the
5161 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
5162 // block codes no residual and the 64-point transform names no type.
5163 let mut flat_typed: Option<Trial> = None;
5164 let mut flat_type = TxType::DctDct;
5165 if !skip {
5166 // lane-intertx: on a `reduced_tx_set = 0` frame the search names the
5167 // Set1 alphabet the writer codes into ([`luma_set_for`], the shape
5168 // the intra search already takes), which is what makes the wider
5169 // seven-type candidate list below reachable -- and prices every
5170 // candidate, `IDTX` included, in the alphabet its symbol is really
5171 // coded into.
5172 if let Some(fset) =
5173 inter_luma_set(side).map(|set| luma_set_for(set, search.screen))
5174 {
5175 let lambda = search.lambda * tx_type_lambda_mult();
5176 let cost = |t: &Trial| t.sse + lambda * t.bits;
5177 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
5178 if tx_type == TxType::DctDct {
5179 continue;
5180 }
5181 let candidate = match second {
5182 Some((mv1, ref1)) => mc_trial_compound_typed(
5183 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5184 search.deadzone, fset, tx_type, fctx,
5185 ),
5186 None => mc_trial_typed(
5187 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5188 reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type,
5189 fctx,
5190 ),
5191 };
5192 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
5193 flat_type = tx_type;
5194 flat_typed = Some(candidate);
5195 }
5196 }
5197 }
5198 }
5199 // Counted at the return points, so the census names the types the block
5200 // really CODES -- a split unit's winner that the flat cost then beats was
5201 // never written (class `counter from refused stream`).
5202 let count = |types: &[TxType]| {
5203 for &t in types {
5204 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5205 }
5206 };
5207 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
5208 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
5209 use std::sync::atomic::Ordering::Relaxed;
5210 TXRD_STATS[0].fetch_add(1, Relaxed);
5211 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
5212 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
5213 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
5214 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
5215 // Is the `DCT_DCT` baseline the search compares against the trial
5216 // THIS function would build for the same block? A stale or
5217 // differently-predicted baseline is what would let a candidate win on
5218 // both terms at once (class `local-rd-on-references` vs a real
5219 // pricing defect); re-predicting it here is the only way to tell.
5220 if let Some(fset) = inter_luma_set(side) {
5221 let here = match second {
5222 Some((mv1, ref1)) => mc_trial_compound_typed(
5223 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5224 search.deadzone, fset, TxType::DctDct, fctx,
5225 ),
5226 None => mc_trial_typed(
5227 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5228 reference.3, false, search.base_q_idx, search.deadzone, fset,
5229 TxType::DctDct, fctx,
5230 ),
5231 };
5232 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
5233 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
5234 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
5235 let n = TXRD_STATS[0].load(Relaxed);
5236 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
5237 eprintln!(
5238 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
5239 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
5240 sse={:.0} bits={:.1}",
5241 second.is_some(), flat.sse, flat.bits, here.sse, here.bits,
5242 flat_ref.sse, flat_ref.bits,
5243 );
5244 }
5245 }
5246 }
5247 // What the caller's already-counted `flat` cost has to be corrected by
5248 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
5249 let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits)
5250 - (flat.sse + search.lambda * flat.bits);
5251 let eligible = tx_select()
5252 && tx_select_inter()
5253 && !skip
5254 && side >= 16
5255 && (second.is_none() || compound_var_tx())
5256 && (side != BLOCK || tx32_depth_search())
5257 && x + side <= luma.true_width
5258 && y + side <= luma.true_height;
5259 if !eligible {
5260 luma.commit(x, y, side, flat_ref);
5261 count(&[flat_type]);
5262 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
5263 }
5264 let tx = side / 2;
5265 let set = luma_set_for(
5266 if tx >= 32 {
5267 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
5268 TxbSet::Luma32Inter
5269 } else if tx >= 16 {
5270 TxbSet::Luma16Inter
5271 } else {
5272 TxbSet::Luma8Inter
5273 },
5274 search.screen,
5275 );
5276 let mut levels = vec![0i32; side * side];
5277 let (mut sse, mut bits) = (0.0, 0.0);
5278 let mut units = Vec::with_capacity(4);
5279 // The split units are smaller than their block, so their `txb_skip`
5280 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
5281 // each unit's own commit publishes what the next one reads, coding order.
5282 luma.ctx.tu_split = true;
5283 // One type per unit in the writer's own raster order (tile.rs
5284 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
5285 let mut split_types = vec![TxType::DctDct; 4];
5286 for tu_row in 0..2 {
5287 for tu_col in 0..2 {
5288 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
5289 let unit = |tx_type: TxType| match second {
5290 Some((mv1, ref1)) => mc_trial_compound_typed(
5291 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
5292 search.base_q_idx, search.deadzone, set, tx_type, fctx,
5293 ),
5294 None => mc_trial_typed(
5295 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
5296 reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx,
5297 ),
5298 };
5299 let mut best: Option<(f64, TxType, Trial)> = None;
5300 for &tx_type in inter_tx_type_candidates(set, search.screen) {
5301 let candidate = unit(tx_type);
5302 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
5303 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
5304 best = Some((cost, tx_type, candidate));
5305 }
5306 }
5307 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
5308 split_types[tu_row * 2 + tu_col] = tx_type;
5309 sse += trial.sse;
5310 bits += trial.bits;
5311 for row in 0..tx {
5312 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
5313 .copy_from_slice(&trial.levels[row * tx..][..tx]);
5314 }
5315 units.push((tu_x, tu_y, trial));
5316 }
5317 }
5318 luma.ctx.tu_split = false;
5319 let split_rate = bits + txfm_split_bits(side, 1);
5320 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
5321 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
5322 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
5323 if split_census_on() {
5324 split_census(1, false, side, split_cost < flat_cost, (split_rate, sse), (flat_rate, flat_ref.sse));
5325 }
5326 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
5327 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
5328 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
5329 // in the leaf row (class `gate-blind-to-feature`).
5330 let counted = side <= BLOCK;
5331 if split_cost < flat_cost {
5332 for (tu_x, tu_y, trial) in &units {
5333 luma.commit(*tu_x, *tu_y, tx, trial);
5334 }
5335 if counted {
5336 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5337 }
5338 count(&split_types);
5339 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
5340 }
5341 if counted {
5342 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5343 }
5344 luma.commit(x, y, side, flat_ref);
5345 count(&[flat_type]);
5346 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
5347}
5348
5349/// The largest distinct-colour count a block may hold and still be offered a
5350/// palette candidate at all: past it the k-means quantisation costs more
5351/// error than the map saves rate, and every trial is wasted wall.
5352///
5353/// Swept on the gate's own screen capture (lane-av1pal2, the
5354/// `unswept-decision-constants` class): 32 (the value this lane inherited)
5355/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
5356/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
5357/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
5358/// binds on nothing this content holds. 128 ships: best BD against both
5359/// references and no wall cost at all (6.1s, the same as at 32, because the
5360/// blocks it newly admits are ones the RD then keeps).
5361/// `EC_AV1_PAL_MAXCOLORS`.
5362fn palette_max_colors() -> usize {
5363 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5364 *N.get_or_init(|| {
5365 std::env::var("EC_AV1_PAL_MAXCOLORS")
5366 .ok()
5367 .and_then(|v| v.parse().ok())
5368 .unwrap_or(128)
5369 })
5370}
5371
5372/// The palettes worth trying for one block's luma, in the shape libaom's
5373/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
5374/// distinct colours takes them ALL (the prediction is then exact and the
5375/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
5376/// one-dimensional Lloyd iteration seeded evenly across its range -- both
5377/// offered, because which wins is an RD question the caller answers.
5378/// `block` is `side*side` source samples, row-major.
5379fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
5380 let mut histogram = [0u32; 256];
5381 for &v in block {
5382 histogram[usize::from(v)] += 1;
5383 }
5384 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
5385 if present.len() < 2 {
5386 return Vec::new();
5387 }
5388 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
5389 let mut base = [0u16; 8];
5390 base[..colors.len()].copy_from_slice(colors);
5391 let map = block
5392 .iter()
5393 .map(|&v| {
5394 colors
5395 .iter()
5396 .enumerate()
5397 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
5398 .map(|(i, _)| i as u8)
5399 .expect("a palette holds at least two colours")
5400 })
5401 .collect();
5402 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
5403 };
5404 if present.len() <= 8 {
5405 return vec![exact(&present)];
5406 }
5407 if present.len() > palette_max_colors() {
5408 return Vec::new();
5409 }
5410 let (lo, hi) = (
5411 i32::from(present[0]),
5412 i32::from(present[present.len() - 1]),
5413 );
5414 let mut out = Vec::with_capacity(2);
5415 for n in [8usize, 4] {
5416 // Even seeding across the block's own range, then four Lloyd passes
5417 // over the histogram (256 bins, not `side*side` pixels).
5418 let mut centres: Vec<f64> = (0..n)
5419 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
5420 .collect();
5421 for _ in 0..4 {
5422 let mut sums = vec![0f64; n];
5423 let mut counts = vec![0u32; n];
5424 for (v, &count) in histogram.iter().enumerate() {
5425 if count == 0 {
5426 continue;
5427 }
5428 let k = (0..n)
5429 .min_by(|&a, &b| {
5430 (centres[a] - v as f64)
5431 .abs()
5432 .total_cmp(&(centres[b] - v as f64).abs())
5433 })
5434 .expect("n >= 2");
5435 sums[k] += (v as u32 * count) as f64;
5436 counts[k] += count;
5437 }
5438 for k in 0..n {
5439 if counts[k] > 0 {
5440 centres[k] = sums[k] / f64::from(counts[k]);
5441 }
5442 }
5443 }
5444 let mut colors: Vec<u16> = centres
5445 .iter()
5446 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
5447 .collect();
5448 colors.sort_unstable();
5449 colors.dedup();
5450 if colors.len() >= 2 {
5451 out.push(exact(&colors));
5452 }
5453 }
5454 out
5455}
5456
5457#[allow(clippy::too_many_arguments)]
5458// ---------------------------------------------------------------------------
5459// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
5460// validity). A key frame that detected screen content and finds enough exact
5461// repeats in its own source sets `allow_intrabc`, which the spec forces every
5462// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
5463// its place when the copied blocks pay back the deblock/CDEF/LR the frame
5464// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
5465// ---------------------------------------------------------------------------
5466
5467/// Whether intra block copy is offered at all. **Off by default** --
5468/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
5469/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
5470/// but on the gate's real screen capture it MEASURED WORSE: setting
5471/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
5472/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
5473/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
5474/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
5475/// that detected no screen content.
5476fn intrabc_enabled() -> bool {
5477 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
5478 return forced;
5479 }
5480 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5481 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
5482}
5483
5484thread_local! {
5485 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
5486 /// probe runs both arms in one process, and the suite is one process, so
5487 /// an environment variable cannot separate them (same reason
5488 /// [`SCREEN_FORCE`] exists).
5489 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
5490}
5491
5492#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5493pub(crate) fn force_intrabc(value: Option<bool>) {
5494 INTRABC_FORCE.with(|c| c.set(value));
5495}
5496
5497/// How many of a screen frame's 16x16 blocks must have an exact repeat
5498/// somewhere else in the source before `allow_intrabc` is worth the in-loop
5499/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
5500/// constant class: `probe_intrabc_threshold` measures the arm at several
5501/// values.
5502fn intrabc_pct() -> usize {
5503 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5504 *N.get_or_init(|| {
5505 std::env::var("EC_AV1_INTRABC_PCT")
5506 .ok()
5507 .and_then(|v| v.parse().ok())
5508 .unwrap_or(10)
5509 })
5510}
5511
5512/// The pixel grid intrabc source positions are hashed on
5513/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
5514/// which keeps the block-hash table (and so the search) linear in the frame
5515/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
5516/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
5517/// bilinear interpolation decode.rs applies but this encoder does not.
5518fn intrabc_step() -> usize {
5519 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5520 *N.get_or_init(|| {
5521 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
5522 .ok()
5523 .and_then(|v| v.parse().ok())
5524 .unwrap_or(4);
5525 if n % 2 == 0 { n.max(2) } else { 4 }
5526 })
5527}
5528
5529/// The side of the luma square the block-hash table is keyed on.
5530const IBC_HASH: usize = 16;
5531
5532/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
5533/// the current one the source's bottom-right corner must already be. Under
5534/// 128 superblocks the same 256 pixels are two superblocks, which
5535/// [`Ibc::dv_valid`] derives from the size itself.
5536const INTRABC_DELAY_SB64: i32 = 4;
5537
5538/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
5539fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
5540 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
5541 for row in 0..IBC_HASH {
5542 let base = (y + row) * width + x;
5543 for &v in &plane[base..base + IBC_HASH] {
5544 h ^= u64::from(v);
5545 h = h.wrapping_mul(0x100_0000_01b3);
5546 }
5547 }
5548 h
5549}
5550
5551/// Every `intrabc_step()`-aligned position of `plane` inside
5552/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
5553fn ibc_index(
5554 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
5555 plane: &[u8],
5556 width: usize,
5557 (x0, y0): (usize, usize),
5558 (x1, y1): (usize, usize),
5559) {
5560 let step = intrabc_step();
5561 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
5562 return;
5563 }
5564 let mut y = y0.next_multiple_of(step);
5565 while y + IBC_HASH <= y1 {
5566 let mut x = x0.next_multiple_of(step);
5567 while x + IBC_HASH <= x1 {
5568 table
5569 .entry(ibc_hash(plane, width, x, y))
5570 .or_default()
5571 .push((x as u32, y as u32));
5572 x += step;
5573 }
5574 y += step;
5575 }
5576}
5577
5578/// Whether `screen`-detected source `y` repeats itself enough to be worth
5579/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
5580/// content appears at some other position, against [`intrabc_pct`]. Returns
5581/// the share as well, for the gate's own print.
5582fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
5583 if true_width < 4 * 64 || true_height < 2 * 64 {
5584 return (false, 0.0);
5585 }
5586 let mut table = std::collections::HashMap::new();
5587 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
5588 let (mut total, mut matched) = (0usize, 0usize);
5589 let mut by = 0;
5590 while by + IBC_HASH <= true_height {
5591 let mut bx = 0;
5592 while bx + IBC_HASH <= true_width {
5593 total += 1;
5594 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
5595 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
5596 matched += 1;
5597 }
5598 }
5599 bx += IBC_HASH;
5600 }
5601 by += IBC_HASH;
5602 }
5603 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
5604 (share * 100.0 >= intrabc_pct() as f64, share)
5605}
5606
5607/// One tile's intrabc search state: a block-hash table over the part of the
5608/// tile's own reconstruction that is already final (whole superblock rows --
5609/// the in-loop filters are off on this frame, so a coded superblock row never
5610/// changes again), plus the last DV chosen, which the RD price uses as its
5611/// predictor estimate.
5612struct Ibc {
5613 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
5614 /// source repeats exactly where a lossily coded reconstruction only
5615 /// nearly does, so an exact-match table over the reconstruction finds
5616 /// almost nothing. The candidate is then SCORED against the
5617 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
5618 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
5619 /// The tile's own luma rect, in samples.
5620 tile: (usize, usize, usize, usize),
5621 /// The DV the previous intrabc block of this tile took -- the *estimate*
5622 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
5623 /// against. The writer computes the true predictor off its own mi grid
5624 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
5625 /// a slightly mispriced candidate, never a wrong bitstream.
5626 last_dv: Option<(i32, i32)>,
5627 /// How many blocks took intrabc, and how many hash lookups found at least
5628 /// one valid candidate -- the gate's own fire counts.
5629 hits: usize,
5630 lookups: usize,
5631 found: usize,
5632}
5633
5634impl Ibc {
5635 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
5636 let mut table = std::collections::HashMap::new();
5637 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
5638 Self {
5639 table,
5640 tile,
5641 last_dv: None,
5642 hits: 0,
5643 lookups: 0,
5644 found: 0,
5645 }
5646 }
5647
5648 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
5649 /// (1/8 pel), with this lane's own extra restriction on top: the source
5650 /// must lie entirely in a COMPLETED superblock row, which is exactly the
5651 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
5652 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
5653 /// wavefront's own diagonal) are legal and not searched; the upgrade path
5654 /// is to index the current row's finished superblocks too.
5655 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
5656 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
5657 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
5658 return false;
5659 }
5660 let (tx0, ty0, tx1, ty1) = (
5661 self.tile.0 as i32,
5662 self.tile.1 as i32,
5663 self.tile.2 as i32,
5664 self.tile.3 as i32,
5665 );
5666 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
5667 let (w, h) = (w as i32, h as i32);
5668 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
5669 return false;
5670 }
5671 // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
5672 // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
5673 // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
5674 // Counting 64s under a 128 superblock let the search take a source
5675 // from a 64 row the 128 visit order had not reconstructed yet.
5676 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
5677 let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 };
5678 let active_sb_row = (y as i32 - ty0) >> sb_log2;
5679 let active_sb_col = (x as i32 - tx0) >> sb_log2;
5680 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
5681 let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
5682 // This lane's own restriction (see the doc comment).
5683 if src_sb_row >= active_sb_row {
5684 return false;
5685 }
5686 let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
5687 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
5688 return false;
5689 }
5690 // libaom's wavefront: only the top-left cone of the frame is legal.
5691 let wf = (1 + delay) * (active_sb_row - src_sb_row);
5692 src_sb_col < active_sb_col - delay + wf
5693 }
5694}
5695
5696/// How many block searches ran, how many found at least one VALID candidate,
5697/// and how many won on rate-distortion -- the hash hit rate a gate prints
5698/// (class `gate-blind-to-feature`: "the search ran" and "the search found
5699/// something" and "the block took it" are three different claims).
5700static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
5701 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
5702
5703impl Drop for Ibc {
5704 fn drop(&mut self) {
5705 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
5706 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
5707 }
5708 }
5709}
5710
5711/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
5712/// its own encode.
5713#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5714pub(crate) fn take_intrabc_search() -> [usize; 3] {
5715 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5716}
5717
5718/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
5719/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
5720/// infers rather than codes.
5721fn dv_component_bits(diff: i32) -> f64 {
5722 let z = diff.unsigned_abs() as i32 - 1;
5723 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
5724 let class = mv_class_of(z);
5725 bits += symbol_bits(&cdf::MV_CLASS, class);
5726 let local = z - mv_class_base(class);
5727 if class == 0 {
5728 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
5729 } else {
5730 let d = local >> 3;
5731 for i in 0..class {
5732 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
5733 }
5734 }
5735 bits
5736}
5737
5738/// What one block vector costs against `pred`, plus the `skip` and
5739/// `use_intrabc` flags the block carries and the ordinary intra block does
5740/// not pay in this currency.
5741fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
5742 let diff = (dv.0 - pred.0, dv.1 - pred.1);
5743 let joint = match (diff.0 != 0, diff.1 != 0) {
5744 (false, false) => 0,
5745 (false, true) => 1,
5746 (true, false) => 2,
5747 (true, true) => 3,
5748 };
5749 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
5750 if diff.0 != 0 {
5751 bits += dv_component_bits(diff.0);
5752 }
5753 if diff.1 != 0 {
5754 bits += dv_component_bits(diff.1);
5755 }
5756 bits
5757}
5758
5759/// The squared error of copying the `side`-square block at `(sx, sy)` of each
5760/// plane's reconstruction onto the source block at `(x, y)`, luma and both
5761/// chroma planes together -- what an intrabc block's whole (residual-free)
5762/// distortion is.
5763fn ibc_sse(
5764 luma: &Plane,
5765 chroma: &[Plane; 2],
5766 (x, y): (usize, usize),
5767 (sx, sy): (usize, usize),
5768 side: usize,
5769) -> f64 {
5770 // Inside the true frame only, for the reason [`Plane::block_sse`] is
5771 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
5772 // how well it copies the padding.
5773 let mut sse = 0.0f64;
5774 let clip = |whole: usize, inside: usize| match edge_sse() {
5775 true => whole.min(inside),
5776 false => whole,
5777 };
5778 let rows = clip(side, luma.true_height.saturating_sub(y));
5779 let cols = clip(side, luma.true_width.saturating_sub(x));
5780 for row in 0..rows {
5781 let src = &luma.source[(y + row) * luma.width + x..][..cols];
5782 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
5783 for (&s, &r) in src.iter().zip(rec) {
5784 let d = f64::from(i32::from(s) - i32::from(r));
5785 sse += d * d;
5786 }
5787 }
5788 let half = side / 2;
5789 for plane in chroma {
5790 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
5791 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
5792 for row in 0..rows {
5793 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
5794 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
5795 for (&s, &r) in src.iter().zip(rec) {
5796 let d = f64::from(i32::from(s) - i32::from(r));
5797 sse += d * d;
5798 }
5799 }
5800 }
5801 sse
5802}
5803
5804/// Copies the `side`-square block at `(sx, sy)` of each plane's
5805/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
5806/// since it carries no residual (`skip`). Full-pel in both planes by
5807/// construction ([`intrabc_step`] keeps every DV even), which is what makes
5808/// this a plain copy where decode.rs runs the bilinear kernel over the same
5809/// samples.
5810fn ibc_commit(
5811 luma: &mut Plane,
5812 chroma: &mut [Plane; 2],
5813 (x, y): (usize, usize),
5814 (sx, sy): (usize, usize),
5815 side: usize,
5816) {
5817 for row in 0..side {
5818 let from = (sy + row) * luma.width + sx;
5819 let to = (y + row) * luma.width + x;
5820 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
5821 luma.reconstruction[to..to + side].copy_from_slice(&copied);
5822 }
5823 let half = side / 2;
5824 for plane in chroma {
5825 for row in 0..half {
5826 let from = (sy / 2 + row) * plane.width + sx / 2;
5827 let to = (y / 2 + row) * plane.width + x / 2;
5828 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
5829 plane.reconstruction[to..to + half].copy_from_slice(&copied);
5830 }
5831 plane.commit_ctx_zero(x / 2, y / 2, half);
5832 }
5833 luma.commit_ctx_zero(x, y, side);
5834}
5835
5836/// Searches this block's own DV: every hash-table position whose 16x16 luma
5837/// square equals the block's source square, plus the previous block's DV as a
5838/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
5839/// the winning `(dv, cost)`, or `None` when nothing valid was found.
5840fn ibc_search(
5841 ibc: &mut Ibc,
5842 luma: &Plane,
5843 chroma: &[Plane; 2],
5844 (x, y): (usize, usize),
5845 side: usize,
5846 lambda: f64,
5847) -> Option<((i32, i32), f64, (usize, usize))> {
5848 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
5849 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
5850 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
5851 let dv = (
5852 (sy as i32 - y as i32) * 8,
5853 (sx as i32 - x as i32) * 8,
5854 );
5855 if !ibc.dv_valid(x, y, side, side, dv) {
5856 return;
5857 }
5858 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
5859 if best.as_ref().is_none_or(|b| cost < b.1) {
5860 *best = Some((dv, cost, (sx, sy)));
5861 }
5862 };
5863 ibc.lookups += 1;
5864 let key = ibc_hash(luma.source, luma.width, x, y);
5865 // The table is filled in raster order, so the entries BEFORE this block's
5866 // own position are exactly the already-coded ones -- and the nearest of
5867 // them costs the fewest DV bits. Walking backwards from the block's own
5868 // slot is what makes the search look up-and-left; taking the newest
5869 // entries outright only ever finds candidates below and to the right,
5870 // every one of which `dv_valid` rejects.
5871 let hits: Vec<(u32, u32)> = ibc
5872 .table
5873 .get(&key)
5874 .map(|h| {
5875 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
5876 h[..end].iter().rev().take(32).copied().collect()
5877 })
5878 .unwrap_or_default();
5879 for (hx, hy) in hits {
5880 consider(&*ibc, hx as usize, hy as usize, &mut best);
5881 }
5882 if let Some(dv) = ibc.last_dv {
5883 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
5884 if sx >= 0 && sy >= 0 {
5885 consider(&*ibc, sx as usize, sy as usize, &mut best);
5886 }
5887 }
5888 if best.is_some() {
5889 ibc.found += 1;
5890 }
5891 best
5892}
5893
5894fn code_square(
5895 luma: &mut Plane,
5896 chroma: &mut [Plane; 2],
5897 (x, y): (usize, usize),
5898 side: usize,
5899 search: &Search,
5900 mode_bits: &[f64; 13],
5901 // The frame header's `tx_mode == TxMode::Select`: the block then searches
5902 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
5903 // transform over its whole side.
5904 tx_select: bool,
5905 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
5906 // header did not set `allow_intrabc`.
5907 ibc: Option<&mut Ibc>,
5908 // Whether this is a KEY frame's block, read only by the split census
5909 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
5910 // which is this lane's whole finding.
5911 census_key: bool,
5912 fctx: &crate::decode::FrameCtx,
5913) -> (BlockCoeffs, f64) {
5914 let (luma_set, chroma_set) = if side == SUPERBLOCK {
5915 // A whole superblock coded as ONE intra block (lane-i64): one
5916 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
5917 // `code_from_prediction` hands back, and one TX_32X32 per chroma
5918 // plane -- the same three sets the key frame writer's
5919 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
5920 // uses (`search_skip_64`).
5921 (TxbSet::Luma64, TxbSet::Chroma32)
5922 } else if side == BLOCK {
5923 (TxbSet::Luma32, TxbSet::Chroma16)
5924 } else if side == 8 {
5925 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
5926 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
5927 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
5928 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
5929 // (this branch is still unreached), so leaving `Chroma8` here would
5930 // silently wire the wrong table the moment one does; `Chroma4` is
5931 // what a real caller needs.
5932 (TxbSet::Luma8, TxbSet::Chroma4)
5933 } else {
5934 (TxbSet::Luma16, TxbSet::Chroma8)
5935 };
5936 let at = At {
5937 x,
5938 y,
5939 side,
5940 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
5941 set: luma_set_for(luma_set, search.screen),
5942 };
5943 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
5944 luma.search_block(at, search, mode_bits, fctx);
5945 let mut luma_tx_types = vec![tx_type];
5946 // The depth search runs on the mode the whole-block transform picked --
5947 // libaom's own ordering, and the reason it costs one extra pass per depth
5948 // rather than one per (mode, depth) pair.
5949 let mut tx_depth = 0u8;
5950 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
5951 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
5952 // pays that zero exactly as a 32x32's depth search makes it pay
5953 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
5954 // below hands the root a symbol for free.
5955 if tx_select && side == SUPERBLOCK {
5956 cost += search.lambda * tx_depth_bits(side, 0);
5957 }
5958 if tx_select && max_tx_depth(side) > 0 {
5959 let mut best = (
5960 cost + search.lambda * tx_depth_bits(side, 0),
5961 0usize,
5962 luma.snapshot(x, y, side),
5963 luma_coeffs,
5964 );
5965 let mut best_types = std::mem::take(&mut luma_tx_types);
5966 // The census wants the flat arm's own (rate, distortion), which
5967 // `search_block` only hands back folded into one cost -- so under the
5968 // env flag alone it is re-coded at depth 0 and the plane restored.
5969 let census_flat = split_census_on().then(|| {
5970 let kept = luma.snapshot(x, y, side);
5971 let (_, sse, bits, _) =
5972 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
5973 luma.restore(x, y, side, &kept);
5974 (bits + tx_depth_bits(side, 0), sse)
5975 });
5976 let mut census_split: Option<(f64, f64)> = None;
5977 for depth in 1..=max_tx_depth(side) {
5978 let (levels, sse, bits, types) =
5979 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
5980 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
5981 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
5982 if census_flat.is_some() {
5983 let c = (bits + tx_depth_bits(side, depth), sse);
5984 if census_split.is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
5985 {
5986 census_split = Some(c);
5987 }
5988 }
5989 if cost_d < best.0 {
5990 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
5991 best_types = types;
5992 }
5993 }
5994 if let (Some(flat), Some(split)) = (census_flat, census_split) {
5995 split_census(0, census_key, side, best.1 > 0, split, flat);
5996 }
5997 luma_tx_types = best_types;
5998 luma.restore(x, y, side, &best.2);
5999 cost = best.0;
6000 tx_depth = best.1 as u8;
6001 luma_coeffs = best.3;
6002 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6003 }
6004 // The palette candidate is priced against the mode the luma search (and
6005 // its transform-depth search) already settled on, so a block only takes
6006 // one when it beats the best ordinary intra coding of the same pixels.
6007 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
6008 // prediction is the colour map, not the DC of its neighbours.
6009 let mut mode = mode;
6010 let mut angle_delta = angle_delta;
6011 let mut palette = None;
6012 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6013 let source: Vec<u8> = (y..y + side)
6014 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
6015 .collect();
6016 let kept = luma.snapshot(x, y, side);
6017 // spec 5.11.50: a block cut by the frame's right/bottom edge codes
6018 // its map over the ON-SCREEN corner only and the decoder replicates
6019 // that outward, so the searched map is folded the same way here --
6020 // the prediction priced, the reconstruction committed and the symbols
6021 // `write_color_index_map` writes are then one and the same map
6022 // (lane-palw).
6023 let on = (
6024 side.min(luma.true_width.saturating_sub(x)),
6025 side.min(luma.true_height.saturating_sub(y)),
6026 );
6027 for mut pal in palette_candidates(&source) {
6028 let n = usize::from(pal.size);
6029 crate::decode::palette_replicate(&mut pal.map, side, side, on);
6030 let prediction: Vec<u8> = pal
6031 .map
6032 .iter()
6033 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
6034 .collect();
6035 let trial = luma.code_from_prediction(
6036 x,
6037 y,
6038 side,
6039 &prediction,
6040 false,
6041 search.base_q_idx,
6042 search.deadzone,
6043 luma_set,
6044 );
6045 let cost_p = trial.sse
6046 + search.lambda
6047 * (trial.bits
6048 + mode_bits[DC_PRED as usize]
6049 + crate::tile::palette_bits(&pal, side, on)
6050 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
6051 if cost_p < cost {
6052 cost = cost_p;
6053 mode = DC_PRED as u8;
6054 angle_delta = 0;
6055 tx_depth = 0;
6056 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
6057 luma.commit(x, y, side, &trial);
6058 palette = Some(pal);
6059 }
6060 }
6061 if palette.is_none() {
6062 luma.restore(x, y, side, &kept);
6063 }
6064 }
6065
6066 // The five recursive filter-intra modes (spec 5.11.14), priced against
6067 // whatever the mode, transform-depth and palette searches settled on --
6068 // the same "one candidate loop after the incumbent is known" shape the
6069 // palette above uses. A block that takes one is `DC_PRED` with no palette
6070 // by construction (`av1_filter_intra_allowed`), and its luma transform
6071 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
6072 //
6073 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
6074 // depth the ordinary intra search runs, each unit predicting recursively
6075 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
6076 // arm), so a block whose ordinary winner wanted a split transform is
6077 // compared against a filter arm that may split too.
6078 //
6079 // Measured (native BD table, lane-fitu): searching the depths on EVERY
6080 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
6081 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
6082 // locally cheaper reconstruction that the film rows go on to predict from
6083 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
6084 // content is where it pays, and a non-screen frame keeps the depth-0-only
6085 // arm, byte for byte.
6086 let mut filter_intra: Option<u8> = None;
6087 if filter_intra_on()
6088 && palette.is_none()
6089 && let Some(class) = crate::decode::filter_intra_size_class(side)
6090 {
6091 let row = &cdf::FILTER_INTRA[class];
6092 // With the sequence bit on, EVERY `DC_PRED` block without a luma
6093 // palette carries the flag, so the incumbent pays its zero before the
6094 // comparison -- otherwise the candidate is charged a bit the block
6095 // spends either way (class `price-the-narrowing-not-the-table`).
6096 if mode == DC_PRED {
6097 cost += search.lambda * symbol_bits(row, 0);
6098 }
6099 let one_bits = symbol_bits(row, 1);
6100 let kept = luma.snapshot(x, y, side);
6101 let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 };
6102 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
6103 for fi in 0..5u8 {
6104 for depth in 0..=max_depth {
6105 // A filter-intra block's units are coded through
6106 // `code_from_prediction`, which is `DCT_DCT` throughout, so
6107 // this arm keeps the empty (all-`DCT_DCT`) type list.
6108 let (levels, sse, bits, _) =
6109 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
6110 let cost_f = sse
6111 + search.lambda
6112 * (bits
6113 + mode_bits[DC_PRED as usize]
6114 + one_bits
6115 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
6116 + if tx_select { tx_depth_bits(side, depth) } else { 0.0 });
6117 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
6118 best = Some((
6119 cost_f,
6120 fi,
6121 depth,
6122 luma.snapshot(x, y, side),
6123 coeffs(&levels, side),
6124 ));
6125 }
6126 }
6127 }
6128 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
6129 cost = cost_f;
6130 mode = DC_PRED;
6131 angle_delta = 0;
6132 tx_depth = depth as u8;
6133 luma_coeffs = levels;
6134 luma.restore(x, y, side, &snapshot);
6135 filter_intra = Some(fi);
6136 } else {
6137 luma.restore(x, y, side, &kept);
6138 }
6139 }
6140
6141 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
6142 // planes; what it costs still counts towards the partition decision.
6143 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
6144 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
6145 cost += chroma_cost;
6146
6147 // The intrabc arm is priced against the WHOLE block -- luma and both
6148 // chroma planes, residual-free -- so it is compared after the chroma
6149 // search has added its own cost, not against the luma decision alone.
6150 if let Some(ibc) = ibc {
6151 if let Some((dv, cost_ibc, src)) =
6152 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
6153 {
6154 if cost_ibc < cost {
6155 ibc_commit(luma, chroma, (x, y), src, side);
6156 ibc.last_dv = Some(dv);
6157 ibc.hits += 1;
6158 return (
6159 BlockCoeffs {
6160 skip: true,
6161 dv: Some(dv),
6162 ..BlockCoeffs::default()
6163 },
6164 cost_ibc,
6165 );
6166 }
6167 }
6168 }
6169 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
6170 // (its levels came from `code_from_prediction`), so the searched types
6171 // belong to a block this one no longer is.
6172 if palette.is_some() || filter_intra.is_some() {
6173 luma_tx_types = Vec::new();
6174 }
6175 (
6176 BlockCoeffs {
6177 u,
6178 v,
6179 luma: luma_coeffs,
6180 mode,
6181 uv_mode,
6182 tx_depth,
6183 palette,
6184 palette_uv,
6185 filter_intra,
6186 cfl_alphas,
6187 angle_delta_y: angle_delta as i8,
6188 luma_tx_types,
6189 ..BlockCoeffs::default()
6190 },
6191 cost,
6192 )
6193}
6194
6195/// The chroma modes the search offers, and the only ones it may offer: each
6196/// predicts from the row directly above and the column directly to the left
6197/// and nothing further, so none of them needs the above-right/below-left
6198/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
6199/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
6200/// reconstruction and its own alpha syntax; both are left out here.
6201const CHROMA_MODES: [u8; 7] = [
6202 DC_PRED,
6203 V_PRED,
6204 H_PRED,
6205 SMOOTH_PRED,
6206 SMOOTH_V_PRED,
6207 SMOOTH_H_PRED,
6208 PAETH_PRED,
6209];
6210
6211/// The thirteen intra mode names, for the chroma fire count's print.
6212#[cfg(test)]
6213const UV_MODE_NAMES: [&str; 14] = [
6214 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
6215 "SMOOTH_H", "PAETH", "CFL",
6216];
6217
6218/// How many blocks each chroma mode has won, indexed by the mode itself --
6219/// the fire count that says whether the search below reaches its candidates
6220/// at all (the `gate-blind-to-feature` class), printed once per gate run.
6221static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
6222 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
6223
6224/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
6225/// won, summed over both chroma planes -- the alpha histogram the gate prints
6226/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
6227/// magnitude only is a search that never left its first candidate).
6228static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
6229 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
6230
6231/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
6232/// zero on a CfL block", `1..=16` the magnitudes.
6233#[cfg(test)]
6234pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
6235 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6236}
6237
6238/// How many directional luma blocks won at each `angle_delta_y`, indexed
6239/// `delta + 3` -- the histogram that says whether the refinement below ever
6240/// leaves zero (`gate-blind-to-feature`).
6241static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
6242 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
6243
6244/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
6245#[cfg(test)]
6246pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
6247 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
6248}
6249
6250/// Whether the luma search refines a directional winner's `angle_delta_y`
6251/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
6252fn angle_delta_on() -> bool {
6253 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6254 crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")
6255 });
6256 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
6257}
6258
6259/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
6260/// switches it off, which is how the lane measured its own on/off pair).
6261fn cfl_on() -> bool {
6262 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6263 crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0")
6264 });
6265 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
6266}
6267
6268/// Whether the intra search offers the five recursive filter-intra modes at
6269/// all, and with them whether the sequence header sets `enable_filter_intra`
6270/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
6271/// its own on/off pair -- and how every byte pin written before it still
6272/// reproduces). It is also a speed lever: on at preset 0, off above it.
6273// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
6274// it off for the whole process (a sequence-header field, so it cannot change
6275// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
6276// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
6277// this workspace.
6278
6279/// Whether a sequence codes 128x128 superblocks when the environment says
6280/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
6281/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
6282/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
6283/// 128x128 block in it every row of the native BD gate is down or flat on
6284/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
6285///
6286/// | row | 64 superblocks | 128 + the 128 root |
6287/// |---|---|---|
6288/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
6289/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
6290/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
6291/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
6292/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
6293///
6294/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
6295/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
6296///
6297/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
6298/// off (the delta_q unit at the 128 superblock, the superblock size travelling
6299/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
6300/// predictor and wavefront, and seven test harnesses that handed the encoder a
6301/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
6302pub(crate) const SB128_DEFAULT: bool = true;
6303
6304/// Whether this process's sequences code 128x128 superblocks. An ENCODER
6305/// knob (like `speed::SPEED`), never read by a decode: read through a
6306/// process-global (not a thread-local) because the tile writers run on
6307/// worker threads; `2` is "the environment has not been read yet".
6308static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
6309
6310/// Whether this process's sequences code 128x128 superblocks.
6311pub(crate) fn sb128_on() -> bool {
6312 use std::sync::atomic::Ordering::Relaxed;
6313 match ENC_SB128.load(Relaxed) {
6314 2 => {
6315 let on = crate::envflags::var("EC_AV1_SB128")
6316 .ok()
6317 .map_or(SB128_DEFAULT, |v| v != "0");
6318 ENC_SB128.store(u8::from(on), Relaxed);
6319 on
6320 }
6321 v => v == 1,
6322 }
6323}
6324
6325/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
6326/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
6327/// exactly like the speed-preset gates.
6328#[cfg(test)]
6329pub(crate) fn force_sb128(on: bool) {
6330 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
6331}
6332
6333/// The luma loop-restoration unit size this sequence codes: a 128 superblock
6334/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
6335/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
6336/// 128), which is the one filter parameter the superblock size moves.
6337pub(crate) fn lr_unit() -> u32 {
6338 if sb128_on() { 128 } else { 64 }
6339}
6340
6341pub(crate) fn filter_intra_on() -> bool {
6342 #[cfg(test)]
6343 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
6344 return forced;
6345 }
6346 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6347 crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0")
6348 });
6349 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
6350}
6351
6352/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
6353/// to its own encode.
6354#[cfg(test)]
6355pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
6356 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6357}
6358
6359/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
6360/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
6361/// Returns each plane's levels, the mode, and what the pair cost (squared
6362/// error plus lambda times bits, the same currency the luma search speaks).
6363///
6364/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
6365/// which is what the luma mode decision was taken against, so what a
6366/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
6367/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
6368/// writer then has to code.
6369#[allow(clippy::too_many_arguments)]
6370/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
6371/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
6372/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
6373/// trials all seven, as before this lever.
6374///
6375/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
6376/// the search's largest trial population by far -- seven modes times two
6377/// planes for every intra block, against 3.7 luma trials -- and the RD
6378/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
6379/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
6380fn chroma_top_k() -> Option<usize> {
6381 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
6382 crate::envflags::var("EC_AV1_CHROMA_K")
6383 .ok()
6384 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
6385 });
6386 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
6387}
6388
6389/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
6390/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
6391/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
6392/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
6393/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
6394/// BD swings by about a point in either direction as near-tie chroma modes
6395/// flip, which is the measurement's own sensitivity, not a trend: nothing
6396/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
6397/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
6398/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
6399/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
6400pub(crate) const CHROMA_TOP_K: Option<usize> = None;
6401
6402fn search_chroma(
6403 chroma: &mut [Plane; 2],
6404 // The luma plane's RECONSTRUCTION under this block, already committed by
6405 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
6406 luma: &Plane,
6407 (x, y): (usize, usize),
6408 side: usize,
6409 set: TxbSet,
6410 search: &Search,
6411 luma_mode: u8,
6412 fctx: &crate::decode::FrameCtx,
6413) -> (
6414 [Vec<Coeff>; 2],
6415 u8,
6416 f64,
6417 Option<crate::tile::PaletteUv>,
6418 Option<(i32, i32)>,
6419) {
6420 let at = At {
6421 x: x / 2,
6422 y: y / 2,
6423 side: side / 2,
6424 reach: Reach::none(),
6425 set,
6426 };
6427 // The census's cheap proxy for a chroma mode: the SAD of its prediction
6428 // summed over both planes, ranked by the same rule the luma histogram
6429 // uses. Only built under `EC_AV1_CENSUS`.
6430 // The SAD of each mode's prediction, summed over both planes -- the
6431 // census's ranking rule, and what [`chroma_top_k`] prunes by.
6432 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
6433 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6434 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6435 u.iter()
6436 .zip(v.iter())
6437 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
6438 .collect()
6439 };
6440 let modes: Vec<u8> = match chroma_top_k() {
6441 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
6442 _ => CHROMA_MODES.to_vec(),
6443 };
6444 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
6445 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
6446 let ranking: Vec<(f64, u8)> = if census_on() {
6447 sad_scores(chroma)
6448 } else {
6449 Vec::new()
6450 };
6451 census_add(2, 1);
6452 census_add(3, modes.len());
6453 let mut best: Option<(f64, u8, Trial, Trial)> = None;
6454 for mode in modes {
6455 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
6456 if (V_PRED..=D67_PRED).contains(&mode) {
6457 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
6458 }
6459 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
6460 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
6461 // chroma of a 64x64 block is `DCT_DCT` whatever
6462 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
6463 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
6464 // points.
6465 let tx_type = if at.side >= 32 {
6466 TxType::DctDct
6467 } else {
6468 crate::decode::default_intra_tx_type(mode)
6469 };
6470 let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6471 let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6472 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
6473 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
6474 best = Some((cost, mode, u, v));
6475 }
6476 }
6477 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
6478 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
6479 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
6480 // what keeps `u_colors` ascending and distinct the way
6481 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
6482 // each cluster's own mean, since the colour-index map is SHARED by the
6483 // two planes. Priced against the best ordinary chroma mode above, so a
6484 // block only takes one when it beats it; a palette block's chroma mode is
6485 // `UV_DC_PRED` by construction.
6486 let mut palette_uv = None;
6487 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6488 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
6489 let plane_source = |p: &Plane| -> Vec<u8> {
6490 (at.y..at.y + at.side)
6491 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
6492 .collect()
6493 };
6494 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
6495 // The luma on-screen extent carried into this plane exactly as the
6496 // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
6497 let on_uv = crate::decode::palette_onscreen_uv(
6498 (side, side),
6499 (
6500 side.min(luma.true_width.saturating_sub(x)),
6501 side.min(luma.true_height.saturating_sub(y)),
6502 ),
6503 (at.side, at.side),
6504 // The encoder writes 4:2:0 only (`palette_uv_side` above).
6505 (1, 1),
6506 );
6507 for mut pal in palette_candidates(&u_source) {
6508 let n = usize::from(pal.size);
6509 crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
6510 // V's base colour per cluster: the mean of the samples the shared
6511 // map assigns to it (an empty cluster cannot happen -- every
6512 // colour `palette_candidates` returns is some pixel's nearest).
6513 let mut sums = [0u32; 8];
6514 let mut counts = [0u32; 8];
6515 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
6516 let k = usize::from(i).min(n - 1);
6517 sums[k] += u32::from(sample);
6518 counts[k] += 1;
6519 }
6520 let mut v_colors = [0u16; 8];
6521 for k in 0..n {
6522 v_colors[k] = if counts[k] > 0 {
6523 ((sums[k] + counts[k] / 2) / counts[k]) as u16
6524 } else {
6525 0
6526 };
6527 }
6528 let candidate = crate::tile::PaletteUv {
6529 size: pal.size,
6530 u_colors: pal.colors,
6531 v_colors,
6532 map: pal.map,
6533 };
6534 let predict = |colors: &[u16; 8]| -> Vec<u8> {
6535 candidate
6536 .map
6537 .iter()
6538 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
6539 .collect()
6540 };
6541 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
6542 let u_trial = chroma[0].code_from_prediction(
6543 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
6544 );
6545 let v_trial = chroma[1].code_from_prediction(
6546 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
6547 );
6548 let cost_p = u_trial.sse
6549 + v_trial.sse
6550 + search.lambda
6551 * (u_trial.bits
6552 + v_trial.bits
6553 + crate::tile::palette_uv_bits(&candidate, side, on_uv));
6554 if cost_p < cost {
6555 cost = cost_p;
6556 mode = DC_PRED;
6557 u = u_trial;
6558 v = v_trial;
6559 palette_uv = Some(candidate);
6560 }
6561 }
6562 }
6563 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
6564 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
6565 // nudges every sample by `alpha_q3` times the block's subsampled,
6566 // average-subtracted luma reconstruction. Offered only where
6567 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
6568 // and priced against the best ordinary chroma mode above, palette
6569 // included, so a block only takes it when it beats both.
6570 let mut cfl_alphas = None;
6571 if side <= 32 && cfl_on() {
6572 // The AC signal, through the decoder's own
6573 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
6574 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
6575 i32::from(luma.reconstruction[ly * luma.width + lx])
6576 });
6577 let dc_prediction = |plane: &Plane| -> Vec<u8> {
6578 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
6579 let (above, left, corner) =
6580 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
6581 let mut prediction = vec![0u8; at.side * at.side];
6582 intra_predict_u8(
6583 DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
6584 fctx,
6585 );
6586 prediction
6587 };
6588 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
6589 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
6590 // add the residual -- which is what [`Plane::code_from_prediction`]
6591 // does with what this returns.
6592 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
6593 base.iter()
6594 .zip(ac.iter())
6595 .map(|(&b, &a)| {
6596 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
6597 })
6598 .collect()
6599 };
6600 // The least-squares alpha, then its two neighbours: minimising
6601 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
6602 // dot-product ratio, and the quantised optimum is one of the two
6603 // integers around it (the clamp and the Q6 rounding are what the SSE
6604 // check below re-decides). libaom sweeps all sixteen magnitudes under
6605 // full RD; three predictions per plane buy nearly the same alpha for a
6606 // thirtieth of the search.
6607 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
6608 let (mut num, mut den) = (0.0f64, 0.0f64);
6609 for row in 0..at.side {
6610 for col in 0..at.side {
6611 let i = row * at.side + col;
6612 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
6613 - f64::from(base[i]);
6614 num += d * f64::from(ac[i]);
6615 den += f64::from(ac[i]) * f64::from(ac[i]);
6616 }
6617 }
6618 if den == 0.0 {
6619 return 0;
6620 }
6621 let ideal = 64.0 * num / den;
6622 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
6623 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
6624 let alpha = alpha.clamp(-16, 16) as i32;
6625 if alpha == 0 {
6626 continue;
6627 }
6628 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
6629 if sse < best.0 {
6630 best = (sse, alpha);
6631 }
6632 }
6633 best.1
6634 };
6635 let picked = [
6636 pick_alpha(&chroma[0], &bases[0]),
6637 pick_alpha(&chroma[1], &bases[1]),
6638 ];
6639 if picked != [0, 0] {
6640 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
6641 let trial = |plane_idx: usize, alpha: i32| -> Trial {
6642 let prediction = if alpha == 0 {
6643 bases[plane_idx].clone()
6644 } else {
6645 apply(&bases[plane_idx], alpha)
6646 };
6647 chroma[plane_idx].code_from_prediction(
6648 at.x,
6649 at.y,
6650 at.side,
6651 &prediction,
6652 false,
6653 search.base_q_idx,
6654 search.deadzone,
6655 set,
6656 )
6657 };
6658 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
6659 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
6660 let combos: [(i32, i32); 3] = [
6661 (picked[0], picked[1]),
6662 (picked[0], 0),
6663 (0, picked[1]),
6664 ];
6665 for &(alpha_u, alpha_v) in &combos {
6666 if (alpha_u, alpha_v) == (0, 0) {
6667 continue;
6668 }
6669 let cu = trial(0, alpha_u);
6670 let cv = trial(1, alpha_v);
6671 let bits =
6672 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
6673 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
6674 if cost_cfl < cost {
6675 cost = cost_cfl;
6676 mode = crate::tile::UV_CFL_PRED as u8;
6677 u = cu;
6678 v = cv;
6679 palette_uv = None;
6680 cfl_alphas = Some((alpha_u, alpha_v));
6681 }
6682 }
6683 }
6684 }
6685 if let Some((alpha_u, alpha_v)) = cfl_alphas {
6686 for alpha in [alpha_u, alpha_v] {
6687 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
6688 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6689 }
6690 }
6691 if census_on() {
6692 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
6693 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6694 }
6695 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6696 chroma[0].commit(at.x, at.y, at.side, &u);
6697 chroma[1].commit(at.x, at.y, at.side, &v);
6698 (
6699 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
6700 mode,
6701 cost,
6702 palette_uv,
6703 cfl_alphas,
6704 )
6705}
6706
6707/// Codes one leaf of a straddling quadrant as whichever costs least of intra
6708/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
6709/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
6710/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
6711/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
6712/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
6713/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
6714/// attempted here: these leaves only ever fill the sliver of real content a
6715/// true edge lands in the middle of a larger block, not a leaf worth a full
6716/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
6717/// (see `write_inter_frame_leaf`'s doc comment).
6718#[allow(clippy::too_many_arguments)]
6719/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
6720/// as [`code_square_inter`] wants them: empty on a frame that codes no
6721/// `reference_select`, or when the leaf compound candidates are switched off.
6722/// One helper because THREE leaf call sites need it -- the split quadrants
6723/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
6724/// `&[]` and so coded no compound block anywhere along the frame's true edge.
6725#[allow(clippy::too_many_arguments)]
6726fn leaf_compound_stacks<'a>(
6727 grid: &MiGrid,
6728 mi_row: usize,
6729 mi_col: usize,
6730 bw4: usize,
6731 bh4: usize,
6732 mi_cols: usize,
6733 mi_rows: usize,
6734 reference_select: bool,
6735 golden: Option<&'a Picture>,
6736 altref: Option<&'a Picture>,
6737) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
6738 if !(reference_select && leaf_compound()) {
6739 return Vec::new();
6740 }
6741 [
6742 (crate::mvstack::GOLDEN_FRAME, golden),
6743 (crate::mvstack::ALTREF_FRAME, altref),
6744 ]
6745 .into_iter()
6746 .filter_map(|(r, pic)| {
6747 pic.map(|p| {
6748 (
6749 r,
6750 p,
6751 crate::mvstack::find_mv_stack_compound(
6752 grid, mi_row, mi_col, bw4, bh4,
6753 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6754 grid.sign_bias_table(), &[(0, 0); 7], None,
6755 ),
6756 )
6757 })
6758 })
6759 .collect()
6760}
6761
6762/// The OBMC prediction of one square single-reference block: this block's own
6763/// translation prediction (`mc::predict`) with every bordering above/left
6764/// neighbour blended into the overlap strips by the DECODER's own plan and
6765/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
6766/// the search prices is what a decoder reconstructs -- never a second
6767/// implementation of the blend. `None` when the block has no overlappable
6768/// neighbour at all (the writer would then code no `motion_mode` symbol) or
6769/// when the plan cannot be built (a neighbour naming a reference this encode
6770/// does not hold).
6771#[allow(clippy::too_many_arguments)]
6772fn obmc_prediction(
6773 grid: &MiGrid,
6774 (mi_row, mi_col): (usize, usize),
6775 (mi_rows, mi_cols): (usize, usize),
6776 (x, y): (usize, usize),
6777 side: usize,
6778 mv: (i32, i32),
6779 refs: &[Option<&Picture>; 8],
6780 // This block's OWN reference planes, luma then both chroma, each as
6781 // (samples, stride, true width, true height).
6782 ref_planes: [(&[u16], usize, usize, usize); 3],
6783 frame_width: usize,
6784 fctx: &crate::decode::FrameCtx,
6785) -> Option<[Vec<u8>; 3]> {
6786 let n4 = side / 4;
6787 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
6788 return None;
6789 }
6790 let refpix = crate::decode::RefPix::ready(*refs);
6791 let plan = crate::decode::obmc_plan(
6792 grid,
6793 &[],
6794 &[],
6795 mi_row,
6796 mi_col,
6797 n4,
6798 n4,
6799 mi_rows,
6800 mi_cols,
6801 side,
6802 side,
6803 side,
6804 crate::decode::ss_x(fctx),
6805 crate::decode::ss_y(fctx),
6806 side / 2,
6807 x,
6808 y,
6809 x / 2,
6810 y / 2,
6811 &refpix,
6812 Some(fctx.interp_filter.get()),
6813 frame_width,
6814 )
6815 .ok()?;
6816 let mut pred = [
6817 vec![0u16; side * side],
6818 vec![0u16; side * side / 4],
6819 vec![0u16; side * side / 4],
6820 ];
6821 for (i, r) in ref_planes.into_iter().enumerate() {
6822 let luma_plane = i == 0;
6823 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
6824 let s = if luma_plane { side } else { side / 2 };
6825 mc::predict(
6826 r.0,
6827 r.1,
6828 r.2,
6829 r.3,
6830 mv_to_q4(px, mv.1, luma_plane),
6831 mv_to_q4(py, mv.0, luma_plane),
6832 s,
6833 s,
6834 &mut pred[i],
6835 fctx,
6836 );
6837 }
6838 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
6839 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
6840 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
6841 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
6842}
6843
6844fn code_square_inter(
6845 luma: &mut Plane,
6846 chroma: &mut [Plane; 2],
6847 (x, y): (usize, usize),
6848 side: usize,
6849 search: &Search,
6850 mode_bits: &[f64; 13],
6851 reference: &Picture,
6852 stack: &MvStack,
6853 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
6854 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
6855 // `reference_select`, and at the straddling call sites).
6856 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
6857 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
6858 // (`record_mi`, in the writer's own coding order) and this leaf's place in
6859 // it -- what the OBMC candidate's eligibility walk and neighbour plan
6860 // read, the same state the tile writer reads when it codes the leaf's
6861 // `motion_mode` symbol.
6862 grid: &MiGrid,
6863 (mi_row, mi_col): (usize, usize),
6864 (mi_rows, mi_cols): (usize, usize),
6865 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
6866 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
6867 refs: &[Option<&Picture>; 8],
6868 fctx: &crate::decode::FrameCtx,
6869) -> (BlockCoeffs, f64) {
6870 // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra
6871 // candidate at all -- `intra_cost` stays at infinity, so every
6872 // comparison below takes an inter candidate and the fallback arm at the
6873 // tail is unreachable. The planes hold what the caller snapshotted until
6874 // the winner commits: the intra trial used to commit here and be
6875 // overwritten by the inter commit, so skipping it changes no committed
6876 // sample, only work.
6877 let (intra_block, intra_cost) = if search.arf_leaf_intra {
6878 code_square(
6879 luma,
6880 chroma,
6881 (x, y),
6882 side,
6883 search,
6884 mode_bits,
6885 tx_select() && tx_select_inter(),
6886 None,
6887 false,
6888 fctx,
6889 )
6890 } else {
6891 arfmode_hit(0);
6892 (BlockCoeffs::default(), f64::INFINITY)
6893 };
6894 let luma_set = if side == 8 {
6895 TxbSet::Luma8Inter
6896 } else {
6897 TxbSet::Luma16Inter
6898 };
6899 let chroma_set = if side == 8 {
6900 TxbSet::Chroma4
6901 } else {
6902 TxbSet::Chroma8
6903 };
6904
6905 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
6906 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
6907 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
6908 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
6909 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
6910 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
6911
6912 let mv = stack.nearest_mv;
6913 let ref_luma = (
6914 &reference.y,
6915 reference.width,
6916 luma.true_width,
6917 luma.true_height,
6918 );
6919 let ref_u = (
6920 &reference.u,
6921 reference.width / 2,
6922 chroma[0].true_width,
6923 chroma[0].true_height,
6924 );
6925 let ref_v = (
6926 &reference.v,
6927 reference.width / 2,
6928 chroma[1].true_width,
6929 chroma[1].true_height,
6930 );
6931 let luma_trial = mc_trial(
6932 luma,
6933 x,
6934 y,
6935 side,
6936 mv,
6937 true,
6938 ref_luma.0,
6939 ref_luma.1,
6940 ref_luma.2,
6941 ref_luma.3,
6942 false,
6943 search.base_q_idx,
6944 search.deadzone,
6945 luma_set, fctx,
6946 );
6947 let u = mc_trial(
6948 &chroma[0],
6949 x / 2,
6950 y / 2,
6951 side / 2,
6952 mv,
6953 false,
6954 ref_u.0,
6955 ref_u.1,
6956 ref_u.2,
6957 ref_u.3,
6958 false,
6959 search.base_q_idx,
6960 search.deadzone,
6961 chroma_set, fctx,
6962 );
6963 let v = mc_trial(
6964 &chroma[1],
6965 x / 2,
6966 y / 2,
6967 side / 2,
6968 mv,
6969 false,
6970 ref_v.0,
6971 ref_v.1,
6972 ref_v.2,
6973 ref_v.3,
6974 false,
6975 search.base_q_idx,
6976 search.deadzone,
6977 chroma_set, fctx,
6978 );
6979 let skip = luma_trial.levels.iter().all(|&l| l == 0)
6980 && u.levels.iter().all(|&l| l == 0)
6981 && v.levels.iter().all(|&l| l == 0);
6982 let inter_cost = luma_trial.sse
6983 + u.sse
6984 + v.sse
6985 + search.lambda
6986 * (skip_bits(skip)
6987 + intra_inter_bits(true)
6988 + single_ref_bits
6989 + mode_bits_inter
6990 + if skip {
6991 0.0
6992 } else {
6993 luma_trial.bits + u.bits + v.bits
6994 });
6995
6996 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
6997 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
6998 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
6999 // scan's own coverage already reached as far) but a real gap at 4-mi
7000 // leaf geometry. r3 ported the extended scan and, while proving it a
7001 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
7002 // `mvstack.rs`), found and fixed a second bug the extended scan's
7003 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
7004 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
7005 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
7006 // regardless of whether it also casts a ref-frame-matching vote) --
7007 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
7008 // branches), which is what made 8-mi geometry a true no-op instead of
7009 // one that only held when every neighbour happened to be inter.
7010 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
7011 // only ever took the stack's NEARESTMV candidate or went intra, so a
7012 // 32x32 block splitting because its four quarters MOVE differently could
7013 // not code the movement it split for. Same candidate `search_inter_block`
7014 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
7015 // a vector the residual syntax can name -- at this leaf's own side.
7016 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
7017 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
7018 // re-price below can hand it back as the winner's own mode info.
7019 let nearest_info = InterInfo {
7020 ref1: None,
7021 mv1: (0, 0),
7022 ref_frame: crate::mvstack::LAST_FRAME,
7023 mode: InterMode::NearestMv,
7024 mv,
7025 ref_mv_idx: 0,
7026 };
7027 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
7028 // syntax, apart from its residual: the OBMC candidate re-prices the same
7029 // syntax against a different prediction, so both sides of that comparison
7030 // carry it.
7031 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
7032 // This leaf's own `NEWMV` vector, kept whether or not it won the
7033 // single-reference comparison: it seeds the compound half-new candidate
7034 // below, exactly as `search_inter_block` seeds its own from the searches
7035 // it already ran.
7036 let mut searched_new: Option<(i32, i32)> = None;
7037 // What that search cost, kept for the second reference's own early-out
7038 // below (`None` when this leaf ran no search at all).
7039 let mut searched_new_cost: Option<f64> = None;
7040 let source_block = luma.source_block(x, y, side);
7041 if leaf_new_mv() {
7042 let (seeds, seed_n) = mv_seeds(stack);
7043 let found = motion::search(
7044 ref_luma.0,
7045 ref_luma.1,
7046 ref_luma.2,
7047 ref_luma.3,
7048 &source_block,
7049 x,
7050 y,
7051 side,
7052 side,
7053 stack.pred_mv,
7054 &seeds[..seed_n],
7055 search.lambda, fctx,
7056 1,
7057 );
7058 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
7059 searched_new_cost = Some(found.cost);
7060 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
7061 if mv_residual.is_none() {
7062 // lane-newmv: a vector the writer cannot name never reaches RD.
7063 newmv_census_block(side, false, f64::INFINITY, best.0, new_mv, stack.nearest_mv, 0.0);
7064 }
7065 if let Some(mv_bits) = mv_residual {
7066 searched_new = Some(new_mv);
7067 // Same reuse as `search_inter_block`: a NEWMV equal to the
7068 // stack's NEARESTMV is the same three trials, already run above.
7069 let (luma_new, u_new, v_new) = if new_mv == mv {
7070 (luma_trial.clone(), u.clone(), v.clone())
7071 } else {
7072 (
7073 mc_trial(
7074 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
7075 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
7076 ),
7077 mc_trial(
7078 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
7079 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
7080 fctx,
7081 ),
7082 mc_trial(
7083 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
7084 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
7085 fctx,
7086 ),
7087 )
7088 };
7089 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
7090 && u_new.levels.iter().all(|&l| l == 0)
7091 && v_new.levels.iter().all(|&l| l == 0);
7092 let drl_bits = if stack.entries.len() > 1 {
7093 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
7094 } else {
7095 0.0
7096 };
7097 let cost_new = luma_new.sse
7098 + u_new.sse
7099 + v_new.sse
7100 + search.lambda
7101 * (skip_bits(skip_new)
7102 + intra_inter_bits(true)
7103 + single_ref_bits
7104 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7105 + drl_bits
7106 + mv_bits
7107 + mv_rate_surcharge(mv_bits)
7108 + if skip_new {
7109 0.0
7110 } else {
7111 luma_new.bits + u_new.bits + v_new.bits
7112 });
7113 newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits);
7114 if cost_new < best.0 {
7115 single_syntax = intra_inter_bits(true)
7116 + single_ref_bits
7117 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7118 + drl_bits
7119 + mv_bits;
7120 best = (
7121 cost_new,
7122 Some((
7123 luma_new,
7124 u_new,
7125 v_new,
7126 skip_new,
7127 InterInfo {
7128 ref1: None,
7129 mv1: (0, 0),
7130 ref_frame: crate::mvstack::LAST_FRAME,
7131 mode: InterMode::NewMv,
7132 mv: new_mv,
7133 ref_mv_idx: 0,
7134 },
7135 )),
7136 );
7137 }
7138 }
7139 }
7140
7141 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
7142 // `search_inter_block` prices for a whole 32x32 block:
7143 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
7144 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
7145 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
7146 // too. Priced with the same static-CDF approximation, plus the
7147 // compound-only syntax the writer emits.
7148 if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() {
7149 // lane-arfmode: arm 4 drops this leaf's compound set (counted once
7150 // per leaf, not once per pair); the single-reference candidates
7151 // above stay.
7152 arfmode_hit(2);
7153 }
7154 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound() && search.arf_leaf_compound) {
7155 let (ref1, g) = (*ref1, *g);
7156 // The whole `comp_mode` + reference-pair tree at the writer's own
7157 // contexts, for THIS pair (lane-ctx).
7158 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
7159 let mode_ctx =
7160 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7161 let mode_bits_of =
7162 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7163 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7164 (
7165 cstack.nearest_mv,
7166 mode_bits_of(0),
7167 InterInfo {
7168 ref_frame: crate::mvstack::LAST_FRAME,
7169 mode: InterMode::NearestNearestMv,
7170 mv: cstack.nearest_mv.0,
7171 mv1: cstack.nearest_mv.1,
7172 ref1: Some(ref1),
7173 ref_mv_idx: 0,
7174 },
7175 ),
7176 (
7177 ((0, 0), (0, 0)),
7178 mode_bits_of(6),
7179 InterInfo {
7180 ref_frame: crate::mvstack::LAST_FRAME,
7181 mode: InterMode::GlobalGlobalMv,
7182 mv: (0, 0),
7183 mv1: (0, 0),
7184 ref1: Some(ref1),
7185 ref_mv_idx: 0,
7186 },
7187 ),
7188 ];
7189 // Every compound MV residual here is priced against compound stack
7190 // entry 0, which is what `assign_compound_mv` predicts from at
7191 // `ref_mv_idx = 0` -- so it is also what the second-reference search
7192 // below seeds from and rounds to, and no candidate it finds can then
7193 // fail `mv_residual_bits`.
7194 let cbase = cstack
7195 .entries
7196 .first()
7197 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
7198 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
7199 // it a leaf could only name a stack vector for the second half, and
7200 // screen capture showed the consequence: every leaf compound block
7201 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
7202 // extra-reference `NEWMV`, when this reference's own
7203 // `NEAREST_NEARESTMV` vector already prices `margin` times better
7204 // than the `LAST` search of this same leaf did -- one candidate
7205 // evaluation standing in for a whole search.
7206 let margin = leaf_second_new_margin();
7207 let mut second_new: Option<(i32, i32)> = None;
7208 if leaf_second_new_mv() {
7209 newmv_census_global(2);
7210 let skip = margin > 0.0
7211 && searched_new_cost.is_some_and(|last| {
7212 motion::cost_at(
7213 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
7214 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
7215 ) * margin
7216 <= last
7217 });
7218 if skip {
7219 newmv_census_global(3);
7220 }
7221 if !skip {
7222 let mut seeds = [(0, 0); 4];
7223 let mut seed_n = 1;
7224 for e in cstack.entries.iter().take(3) {
7225 seeds[seed_n] = e.mv1;
7226 seed_n += 1;
7227 }
7228 let found = motion::search(
7229 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
7230 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
7231 );
7232 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
7233 }
7234 }
7235 if let Some(new_mv) = searched_new {
7236 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
7237 ccands.push((
7238 (new_mv, cstack.nearest_mv.1),
7239 mode_bits_of(3) + b0,
7240 InterInfo {
7241 ref_frame: crate::mvstack::LAST_FRAME,
7242 mode: InterMode::NewNearestMv,
7243 mv: new_mv,
7244 mv1: cstack.nearest_mv.1,
7245 ref1: Some(ref1),
7246 ref_mv_idx: 0,
7247 },
7248 ));
7249 }
7250 }
7251 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
7252 // searches this leaf ran, each residual priced against `cbase`.
7253 if let Some(mv1) = second_new {
7254 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
7255 ccands.push((
7256 (cstack.nearest_mv.0, mv1),
7257 mode_bits_of(2) + b1,
7258 InterInfo {
7259 ref_frame: crate::mvstack::LAST_FRAME,
7260 mode: InterMode::NearestNewMv,
7261 mv: cstack.nearest_mv.0,
7262 mv1,
7263 ref1: Some(ref1),
7264 ref_mv_idx: 0,
7265 },
7266 ));
7267 if let Some((new_mv, b0)) =
7268 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
7269 {
7270 ccands.push((
7271 (new_mv, mv1),
7272 mode_bits_of(7) + b0 + b1,
7273 InterInfo {
7274 ref_frame: crate::mvstack::LAST_FRAME,
7275 mode: InterMode::NewNewMv,
7276 mv: new_mv,
7277 mv1,
7278 ref1: Some(ref1),
7279 ref_mv_idx: 0,
7280 },
7281 ));
7282 }
7283 }
7284 }
7285 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
7286 ccands.dedup_by_key(|c| c.0);
7287 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
7288 let g_u = (
7289 g.u.as_slice(),
7290 g.width / 2,
7291 chroma[0].true_width,
7292 chroma[0].true_height,
7293 );
7294 let g_v = (
7295 g.v.as_slice(),
7296 g.width / 2,
7297 chroma[1].true_width,
7298 chroma[1].true_height,
7299 );
7300 for (mvs, bits, info) in ccands {
7301 let luma_c = mc_trial_compound(
7302 luma, x, y, side, mvs, true,
7303 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
7304 search.base_q_idx, search.deadzone, luma_set, fctx,
7305 );
7306 let u_c = mc_trial_compound(
7307 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
7308 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
7309 search.base_q_idx, search.deadzone, chroma_set, fctx,
7310 );
7311 let v_c = mc_trial_compound(
7312 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
7313 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
7314 search.base_q_idx, search.deadzone, chroma_set, fctx,
7315 );
7316 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
7317 && u_c.levels.iter().all(|&l| l == 0)
7318 && v_c.levels.iter().all(|&l| l == 0);
7319 let cost_c = luma_c.sse
7320 + u_c.sse
7321 + v_c.sse
7322 + search.lambda
7323 * (skip_bits(skip_c)
7324 + intra_inter_bits(true)
7325 + bits
7326 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
7327 if cost_c < best.0 {
7328 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
7329 }
7330 }
7331 }
7332
7333 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
7334 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
7335 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
7336 // the writer codes no symbol for one. The prediction is the decoder's own
7337 // plan and blend over the neighbours this leaf's `grid` already carries
7338 // (published by `record_mi` in the writer's coding order), so the
7339 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
7340 // offered this only at 32x32, which is not where libaom cashes its OBMC
7341 // gain.
7342 let mut motion_won = 0u8;
7343 let single = match &best.1 {
7344 None => Some(nearest_info),
7345 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
7346 Some(_) => None,
7347 };
7348 if let Some(info) = single.filter(|i| {
7349 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
7350 && i.ref_frame == crate::mvstack::LAST_FRAME
7351 }) {
7352 let planes = [
7353 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7354 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7355 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7356 ];
7357 // Which alphabet this block's writer will code the symbol against
7358 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
7359 // 3-symbol one only under `allow_warped_motion` and at least one warp
7360 // sample. Mirrored here so the candidates are priced against the
7361 // table the tile really narrows.
7362 let warp_alphabet = warp_on()
7363 && crate::decode::num_proj_ref(
7364 grid,
7365 mi_row,
7366 mi_col,
7367 side / 4,
7368 side / 4,
7369 mi_cols,
7370 mi_rows,
7371 info.ref_frame,
7372 fctx,
7373 ) >= 1;
7374 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
7375 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
7376 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
7377 if let Some(pred) = obmc_prediction(
7378 grid,
7379 (mi_row, mi_col),
7380 (mi_rows, mi_cols),
7381 (x, y),
7382 side,
7383 info.mv,
7384 refs,
7385 planes,
7386 reference.width,
7387 fctx,
7388 ) {
7389 candidates.push((1, pred));
7390 }
7391 }
7392 if warp_alphabet {
7393 if let Some(pred) = warp_prediction(
7394 grid,
7395 (mi_row, mi_col),
7396 (mi_rows, mi_cols),
7397 (x, y),
7398 side,
7399 info.mv,
7400 info.ref_frame,
7401 planes,
7402 fctx,
7403 ) {
7404 candidates.push((2, pred));
7405 }
7406 }
7407 for (motion, pred) in candidates {
7408 let luma_o = luma.code_from_prediction(
7409 x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
7410 );
7411 let u_o = chroma[0].code_from_prediction(
7412 x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
7413 chroma_set,
7414 );
7415 let v_o = chroma[1].code_from_prediction(
7416 x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
7417 chroma_set,
7418 );
7419 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
7420 && u_o.levels.iter().all(|&l| l == 0)
7421 && v_o.levels.iter().all(|&l| l == 0);
7422 let cost_o = luma_o.sse
7423 + u_o.sse
7424 + v_o.sse
7425 + search.lambda
7426 * (skip_bits(skip_o)
7427 + single_syntax
7428 + mm(motion)
7429 + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
7430 // The incumbent pays the motion_mode symbol IT would code, so
7431 // both sides of the comparison carry that syntax.
7432 if cost_o < best.0 + search.lambda * mm(motion_won) {
7433 motion_won = motion;
7434 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
7435 }
7436 }
7437 }
7438
7439 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
7440 if cost < intra_cost {
7441 // A compound winner commits the flat trial it was priced from:
7442 // `commit_inter_luma`'s var-tx trial set is single-reference
7443 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
7444 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
7445 // predicting each half-side trial from BOTH references, verified
7446 // byte-identical to this when its split is disabled) and MEASURED
7447 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
7448 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
7449 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
7450 // compound block's residual is small enough that the four extra
7451 // per-unit txb_skip/eob symbols cost more ladder bytes than this
7452 // encoder's static-CDF estimate prices them at, so the local RD
7453 // win does not convert. lane-av1txbits REBUILT it on top of a
7454 // search that prices against the tables the frame is really
7455 // written with (`tile::arm_pricing_cdfs`, the estimate error on
7456 // these very blocks measured down from +31% to +3%) and measured
7457 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
7458 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
7459 // same build without it. The static-CDF estimate was NOT what
7460 // held the compound var-tx trial back. The flat trial stays.
7461 // An OBMC winner commits the flat trial too: `commit_inter_luma`
7462 // re-predicts each var-tx unit by plain translation, which is not
7463 // the prediction this candidate was priced from.
7464 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
7465 // 0.05 (both rejections above were measured at 0.1, the weight
7466 // the lambda lane showed was 2x too heavy): a compound winner is
7467 // offered the same var-tx split, its units predicted from BOTH
7468 // references (`mc_trial_compound`). RE-MEASURED native: film
7469 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
7470 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
7471 // one row 0.2 down, two flat, short of the two-down-one-flat keep
7472 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
7473 // rather than change the default on a single 0.2 row. It fires:
7474 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
7475 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
7476 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
7477 // 1.3/1.2 down there, which is where the upgrade path is if this
7478 // is picked up again.
7479 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7480 refs[r as usize].map(|g| {
7481 (
7482 info.mv1,
7483 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
7484 )
7485 })
7486 });
7487 let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0
7488 || (info.ref1.is_some() && second.is_none())
7489 {
7490 luma.commit(x, y, side, &luma_new);
7491 (luma_new.levels.clone(), 0, 0.0, Vec::new())
7492 } else {
7493 commit_inter_luma(
7494 luma, (x, y), side, info.mv,
7495 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7496 search, &luma_new, skip_new, second, fctx,
7497 )
7498 };
7499 // lane-txrd: chroma follows the luma type the search just chose.
7500 let [u_new, v_new] = match luma_tx_types.first().copied() {
7501 Some(t) => recode_inter_chroma(
7502 chroma, (x, y), side, info.mv,
7503 [
7504 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7505 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7506 ],
7507 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7508 refs[r as usize].map(|g| {
7509 (
7510 info.mv1,
7511 [
7512 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
7513 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
7514 ],
7515 )
7516 })
7517 }),
7518 search, chroma_set, t, fctx,
7519 )
7520 .unwrap_or([u_new, v_new]),
7521 None => [u_new, v_new],
7522 };
7523 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
7524 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
7525 return (
7526 BlockCoeffs {
7527 angle_delta_y: 0,
7528 cfl_alphas: None,
7529 filter_intra: None,
7530 luma: coeffs(&levels, side),
7531 u: coeffs(&u_new.levels, side / 2),
7532 v: coeffs(&v_new.levels, side / 2),
7533 mode: DC_PRED as u8,
7534 uv_mode: DC_PRED,
7535 skip: skip_new,
7536 eight: None,
7537 dv: None,
7538 palette: None,
7539 palette_uv: None,
7540 tx_depth,
7541 luma_tx_types,
7542 inter: Some(info),
7543 motion_mode: motion_won,
7544 },
7545 cost + dcost,
7546 );
7547 }
7548 }
7549
7550 census_add(8, 1);
7551 if skip {
7552 census_add(10, 1);
7553 }
7554 if inter_cost >= intra_cost {
7555 census_add(9, 1);
7556 }
7557 if inter_cost < intra_cost {
7558 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
7559 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, None, fctx,
7560 );
7561 // lane-txrd: chroma follows the luma type (this tail's block is
7562 // single-reference `NEARESTMV`, so no compound second half).
7563 let [u, v] = match luma_tx_types.first().copied() {
7564 Some(t) => recode_inter_chroma(
7565 chroma, (x, y), side, mv,
7566 [
7567 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7568 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7569 ],
7570 None, search, chroma_set, t, fctx,
7571 )
7572 .unwrap_or([u, v]),
7573 None => [u, v],
7574 };
7575 chroma[0].commit(x / 2, y / 2, side / 2, &u);
7576 chroma[1].commit(x / 2, y / 2, side / 2, &v);
7577 (BlockCoeffs {
7578 luma_tx_types,
7579 angle_delta_y: 0,
7580 cfl_alphas: None,
7581 filter_intra: None,
7582 luma: coeffs(&levels, side),
7583 u: coeffs(&u.levels, side / 2),
7584 v: coeffs(&v.levels, side / 2),
7585 mode: DC_PRED as u8,
7586 uv_mode: DC_PRED,
7587 skip,
7588 eight: None,
7589 dv: None,
7590 palette: None,
7591 palette_uv: None,
7592 tx_depth,
7593 motion_mode: 0,
7594 inter: Some(InterInfo {
7595 ref1: None,
7596 mv1: (0, 0),
7597 ref_frame: crate::mvstack::LAST_FRAME,
7598 mode: InterMode::NearestMv,
7599 mv,
7600 ref_mv_idx: 0,
7601 }),
7602 }, inter_cost + dcost)
7603 } else {
7604 (intra_block, intra_cost)
7605 }
7606}
7607
7608/// Publishes one coded inter-frame block into the `mi` grid the next block's
7609/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
7610/// block casts no vote but is still a coded cell (see `code_square_inter`'s
7611/// note on `processed_rows`/`processed_cols`).
7612fn record_mi(
7613 grid: &mut MiGrid,
7614 mi_row: usize,
7615 mi_col: usize,
7616 size: u8,
7617 inter: Option<InterInfo>,
7618 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
7619 // the RD pricer the two cells the writer's `skip_ctx` sums.
7620 skip: bool,
7621) {
7622 let info = match inter {
7623 Some(info) => MiInfo {
7624 is_inter: true,
7625 ref_frame: info.ref_frame,
7626 // A COMPOUND block votes with BOTH of its references and both of
7627 // its vectors, exactly as the tile writer publishes it: recording
7628 // a compound block as a single-reference one here left the
7629 // encoder's own grid disagreeing with the writer's from the first
7630 // compound block on, so every later stack it searched against was
7631 // not the stack the decoder derives.
7632 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7633 mv1: mv16(info.mv1),
7634 mv: mv16(info.mv),
7635 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
7636 // side, compound modes 2/3/7 on the other.
7637 is_new_mv: matches!(
7638 info.mode,
7639 InterMode::NewMv
7640 | InterMode::NewNewMv
7641 | InterMode::NearestNewMv
7642 | InterMode::NewNearestMv
7643 ),
7644 size,
7645 size_h: size,
7646 is_global_mv0: false,
7647 is_global_mv1: false,
7648 },
7649 None => MiInfo {
7650 is_inter: false,
7651 ref_frame: -1,
7652 ref_frame1: NO_REF1,
7653 mv1: (0, 0),
7654 mv: (0, 0),
7655 is_new_mv: false,
7656 size,
7657 size_h: size,
7658 is_global_mv0: false,
7659 is_global_mv1: false,
7660 },
7661 };
7662 for dr in 0..usize::from(size) {
7663 for dc in 0..usize::from(size) {
7664 grid.set(mi_row + dr, mi_col + dc, info);
7665 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7666 }
7667 }
7668}
7669
7670/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
7671/// writer's own `write_inter_block_128_rect` makes, so the second half of a
7672/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
7673fn record_mi_rect(
7674 grid: &mut MiGrid,
7675 mi_row: usize,
7676 mi_col: usize,
7677 (w_mi, h_mi): (usize, usize),
7678 inter: Option<InterInfo>,
7679 skip: bool,
7680) {
7681 record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
7682 // `record_mi` stamped the square corner; widen it to the true footprint,
7683 // with the block's own (rect) size fields.
7684 let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
7685 info.size = w_mi as u8;
7686 info.size_h = h_mi as u8;
7687 for dr in 0..h_mi {
7688 for dc in 0..w_mi {
7689 grid.set(mi_row + dr, mi_col + dc, info);
7690 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7691 }
7692 }
7693}
7694
7695/// The reconstructed samples one 32x32 square covers in all three planes, so
7696/// that a partition trial can be undone.
7697/// One square of a plane, row-major, the inverse of [`Plane::restore`].
7698///
7699/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
7700/// which allocated and freed a `Vec` per row of every block it copied --
7701/// `Plane::snapshot` runs once per partition trial.
7702fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
7703 let mut out = vec![0u8; side * side];
7704 for row in 0..side {
7705 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
7706 }
7707 out
7708}
7709
7710fn snapshot(
7711 luma: &Plane,
7712 chroma: &[Plane; 2],
7713 (x, y): (usize, usize),
7714 side: usize,
7715) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
7716 [
7717 luma.snapshot(x, y, side),
7718 chroma[0].snapshot(x / 2, y / 2, side / 2),
7719 chroma[1].snapshot(x / 2, y / 2, side / 2),
7720 ]
7721}
7722
7723/// Puts such a snapshot back.
7724fn restore(
7725 luma: &mut Plane,
7726 chroma: &mut [Plane; 2],
7727 (x, y): (usize, usize),
7728 side: usize,
7729 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
7730) {
7731 luma.restore(x, y, side, &saved[0]);
7732 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
7733 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
7734}
7735
7736/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
7737/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
7738/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
7739/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
7740/// rule shared with the key-frame path, not a second one that could diverge.
7741fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
7742 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
7743 let dc_entry = dc_pos.map(|i| scored.remove(i));
7744 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
7745 scored.truncate(if dc_entry.is_some() {
7746 top_k.saturating_sub(1)
7747 } else {
7748 top_k
7749 });
7750 if let Some(dc_entry) = dc_entry {
7751 scored.push(dc_entry);
7752 }
7753 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
7754 modes.iter().copied().filter(|m| keep.contains(m)).collect()
7755}
7756
7757fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
7758 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
7759 [INTRA_MODE_CTX[usize::from(left_mode)]];
7760 std::array::from_fn(|mode| {
7761 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
7762 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
7763 } else {
7764 0.0
7765 };
7766 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
7767 })
7768}
7769
7770/// What the luma mode search picks between, and under what terms.
7771#[derive(Clone, Copy)]
7772struct Search<'a> {
7773 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
7774 /// luma search then offers a palette candidate beside the intra modes.
7775 screen: bool,
7776 base_q_idx: u8,
7777 deadzone: f64,
7778 lambda: f64,
7779 modes: &'a [u8],
7780 /// How many of `modes` the full RD trial (forward transform, quantize,
7781 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
7782 /// pre-pass on the prediction residual alone plus DC (always kept, since
7783 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
7784 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
7785 /// mode through full RD, unchanged from before this lever.
7786 top_k: Option<usize>,
7787 /// lane-arfmode: the top ARF's offer set ([`crate::speed::ARFMODE`])
7788 /// -- `false` cuts the named candidate group from the whole-32 search
7789 /// ([`search_inter_block`]), the 16x16/8x8 leaf search
7790 /// ([`code_square_inter`]) and the 8x8 split offer, at the top ARF
7791 /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is
7792 /// the pre-lane behaviour: the mid and quarter hidden frames, the shown
7793 /// leaves and the flat path keep intra and compound, and the
7794 /// straddling-edge 8x8s are only mode-gated, never partition-gated.
7795 /// The probe's correction: with the leaf gate ALONE the film A stream
7796 /// was byte-identical to the control -- the ARF's intra area lives at
7797 /// the whole-32 level, so the intra arm must cut it there too.
7798 arf_leaf_intra: bool,
7799 arf_leaf8: bool,
7800 arf_leaf_compound: bool,
7801}
7802
7803/// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what
7804/// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the
7805/// shipped table -- 0, bit-exact with the pre-lane encoder).
7806fn arfmode() -> u8 {
7807 match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
7808 u8::MAX => {}
7809 n => return n,
7810 }
7811 static ENV: std::sync::LazyLock<Option<u8>> = std::sync::LazyLock::new(|| {
7812 crate::envflags::var("EC_AV1_ARFMODE").ok().and_then(|v| v.parse().ok())
7813 });
7814 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE))
7815}
7816
7817/// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.
7818static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
7819
7820/// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
7821/// process constant ([`crate::envflags`]), so an in-process witness needs
7822/// this to arm the lever.
7823#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
7824pub(crate) fn set_arfmode(n: Option<u8>) {
7825 ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed);
7826}
7827
7828/// How often each armed [`crate::speed::ARFMODE`] arm actually fired since
7829/// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded
7830/// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8
7831/// split the search would have offered and the arm refused, 2 = a top-ARF
7832/// leaf whose compound set was dropped. A green gate over counts of zero
7833/// proves nothing about the lever.
7834static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [
7835 std::sync::atomic::AtomicUsize::new(0),
7836 std::sync::atomic::AtomicUsize::new(0),
7837 std::sync::atomic::AtomicUsize::new(0),
7838];
7839
7840/// Records one such hit.
7841fn arfmode_hit(which: usize) {
7842 ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7843}
7844
7845/// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer
7846/// condition, so the counter only runs when every other prune let the split
7847/// through and the arm alone refuses it.
7848fn arfmode_hit_and_no() -> bool {
7849 arfmode_hit(1);
7850 false
7851}
7852
7853/// Takes (and clears) the counts. `pub` for `examples/enc_probe`, so a
7854/// probe point can print a non-zero engagement count under the env knob
7855/// itself -- the counter the gate BD numbers are read against.
7856pub fn take_arfmode_hits() -> [usize; 3] {
7857 [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7858}
7859
7860fn prune_top_k() -> Option<usize> {
7861 #[cfg(test)]
7862 {
7863 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
7864 return k;
7865 }
7866 }
7867 let swept = std::env::var("EC_AV1_PRUNE_K")
7868 .ok()
7869 .and_then(|v| v.parse::<usize>().ok());
7870 match swept {
7871 Some(k) if cfg!(test) => Some(k),
7872 _ => crate::speed::at(&crate::speed::PRUNE_K),
7873 }
7874}
7875
7876// A per-thread override [`prune_top_k`] checks first, so one test can sweep
7877// `top_k` in-process without mutating the environment (forbidden here --
7878// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
7879#[cfg(test)]
7880thread_local! {
7881 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
7882 const { std::cell::Cell::new(None) };
7883}
7884
7885#[cfg(test)]
7886fn set_test_top_k_override(value: Option<usize>) {
7887 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
7888}
7889
7890/// The default: unpruned, thirteen full trials per block, same as before this
7891/// lever. Set from the sweep in the lane report if the quality gate clears it.
7892pub(crate) const PRUNE_TOP_K: Option<usize> = None;
7893
7894/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
7895/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
7896/// quality gates were measured separately and may land on different
7897/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
7898/// [`EC_AV1_PRUNE_K`] or the key-frame path.
7899fn prune_top_k_inter() -> Option<usize> {
7900 #[cfg(test)]
7901 {
7902 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
7903 return k;
7904 }
7905 }
7906 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
7907 .ok()
7908 .and_then(|v| v.parse::<usize>().ok());
7909 match swept {
7910 Some(k) if cfg!(test) => Some(k),
7911 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
7912 }
7913}
7914
7915// A per-thread override [`prune_top_k_inter`] checks first, same reason as
7916// [`TEST_TOP_K_OVERRIDE`].
7917#[cfg(test)]
7918thread_local! {
7919 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
7920 const { std::cell::Cell::new(None) };
7921}
7922
7923#[cfg(test)]
7924fn set_test_top_k_override_inter(value: Option<usize>) {
7925 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
7926}
7927
7928/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
7929/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
7930/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
7931/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
7932/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
7933/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
7934/// pruning them costs less quality here.
7935pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
7936
7937// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
7938// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
7939// inter frame's cost can be attributed to a bucket without changing what
7940// the search actually does. Index: 0 = whole-call time inside
7941// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
7942// [`crate::mc::predict`] (every call, from the motion search's own
7943// candidates and from a committed inter block's final prediction alike),
7944// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
7945#[cfg(test)]
7946thread_local! {
7947 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
7948 std::cell::Cell::new(0),
7949 std::cell::Cell::new(0),
7950 std::cell::Cell::new(0),
7951 std::cell::Cell::new(0),
7952 ];
7953}
7954
7955/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
7956/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
7957/// per transform trial and per `mc::predict` call whether or not anyone was
7958/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
7959/// The clock is now read only when [`crate::par::stage_times`] is on, which
7960/// is what prints the breakdown in the first place.
7961#[cfg(test)]
7962pub(crate) fn stage_start() -> Option<std::time::Instant> {
7963 crate::par::stage_times().then(std::time::Instant::now)
7964}
7965
7966#[cfg(test)]
7967pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
7968 if let Some(t) = t {
7969 stage_add(bucket, t.elapsed());
7970 }
7971}
7972
7973#[cfg(test)]
7974pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
7975 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
7976}
7977
7978#[cfg(test)]
7979fn stage_reset() {
7980 crate::par::set_stage_times(true);
7981 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
7982}
7983
7984#[cfg(test)]
7985fn stage_read() -> [std::time::Duration; 4] {
7986 crate::par::set_stage_times(false);
7987 STAGE_NS.with(|c| {
7988 c.each_ref()
7989 .map(|cell| std::time::Duration::from_nanos(cell.get()))
7990 })
7991}
7992
7993/// One mode's coding of one block, before it is committed.
7994#[derive(Clone)]
7995struct Trial {
7996 levels: Vec<i32>,
7997 reconstruction: Vec<u8>,
7998 sse: f64,
7999 bits: f64,
8000}
8001
8002/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
8003/// of a 64-point transform that is actually coded (everything outside it is
8004/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
8005fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
8006 let mut out = vec![0i32; to * to];
8007 for row in 0..to {
8008 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
8009 }
8010 out
8011}
8012
8013/// The non-zero levels of a block, as the tile writer takes them.
8014fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
8015 levels
8016 .iter()
8017 .enumerate()
8018 .filter(|&(_, &level)| level != 0)
8019 .map(|(i, &level)| Coeff {
8020 row: (i / side) as u8,
8021 col: (i % side) as u8,
8022 level,
8023 })
8024 .collect()
8025}
8026
8027thread_local! {
8028 /// The tile grid the next frame is coded with, as `(TileColsLog2,
8029 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
8030 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
8031 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
8032 /// one tile per frame, what every caller that never arms anything gets
8033 /// and what every stream this crate wrote before tiles existed carries.
8034 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
8035}
8036
8037/// Arms this thread's next frame encodes with a tile grid (log2 counts).
8038pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
8039 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
8040}
8041
8042fn armed_tiles() -> (u32, u32) {
8043 let armed = TILE_LOG2.with(std::cell::Cell::get);
8044 if armed != (0, 0) {
8045 return armed;
8046 }
8047 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
8048 // (which codes through `encode_sequence`, not the facade) can measure what
8049 // a tile grid costs without a knob of its own -- same shape as
8050 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
8051 match std::env::var("EC_AV1_TILES").ok() {
8052 Some(v) if cfg!(test) => {
8053 let mut f = v.split(':');
8054 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
8055 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
8056 (cols, rows)
8057 }
8058 _ => armed,
8059 }
8060}
8061
8062/// Codes a frame's `tiles` tiles, each entirely on its own (see
8063/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
8064/// the crate's own pool, and hands back their payloads in tile order plus
8065/// whatever `code` returned for tile `store` -- the CDF state
8066/// `context_update_tile_id` names. The result cannot depend on the thread
8067/// count: each job writes one tile from the frame's own starting tables into
8068/// its own slot.
8069fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
8070where
8071 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
8072{
8073 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
8074 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
8075 let threads = crate::par::tile_threads().min(tiles);
8076 let mut slots: Vec<Slot> = Vec::new();
8077 if threads <= 1 {
8078 for index in 0..tiles {
8079 slots.push(Some(code(index)));
8080 }
8081 } else {
8082 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8083 {
8084 let batch = crate::par::Batch::new("ec-av1-tile");
8085 for (from, to) in crate::par::bands(tiles, threads) {
8086 let done = &done;
8087 let code = &code;
8088 batch.submit(move || {
8089 for index in from..to {
8090 let coded = code(index);
8091 done.lock().expect("tile slots")[index] = Some(coded);
8092 }
8093 });
8094 }
8095 }
8096 slots = done.into_inner().expect("tile slots");
8097 }
8098 let mut out = Vec::with_capacity(tiles);
8099 let mut stored = None;
8100 for (index, slot) in slots.into_iter().enumerate() {
8101 let (bytes, cdfs) = slot.expect("every tile was coded")?;
8102 if index == store {
8103 stored = cdfs;
8104 }
8105 out.push(bytes);
8106 }
8107 Ok((out, stored))
8108}
8109
8110/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
8111/// workers, and returns the results in tile order. The counterpart of
8112/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
8113/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
8114/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
8115/// availability is already tile-relative (`clip_planes_to_tile`,
8116/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
8117/// other tiles have run -- gated by
8118/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
8119/// covers the search as well as the write.
8120///
8121/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
8122/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
8123/// does it for the decoder's filter bands.
8124fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
8125where
8126 T: Send,
8127 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
8128{
8129 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
8130 let threads = crate::par::tile_threads().min(tiles);
8131 if threads <= 1 {
8132 return (0..tiles).map(|index| job(index, fctx)).collect();
8133 }
8134 type Slot<T> = Option<Result<T>>;
8135 let done: std::sync::Mutex<Vec<Slot<T>>> =
8136 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8137 {
8138 let batch = crate::par::Batch::new("ec-av1-tile-search");
8139 for (from, to) in crate::par::bands(tiles, threads) {
8140 let done = &done;
8141 let job = &job;
8142 let ctx = crate::decode::filter_ctx_copy(fctx);
8143 batch.submit(move || {
8144 for index in from..to {
8145 let searched = job(index, &ctx);
8146 done.lock().expect("tile slots")[index] = Some(searched);
8147 }
8148 });
8149 }
8150 }
8151 done.into_inner()
8152 .expect("tile slots")
8153 .into_iter()
8154 .map(|slot| slot.expect("every tile was searched"))
8155 .collect()
8156}
8157
8158/// One tile job's own copy of a plane: the frame's source, a blank
8159/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
8160/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
8161/// of the frame's reconstruction because a tile's prediction never reads a
8162/// sample outside its own rectangle, and every sample inside it is written
8163/// before it is read.
8164fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
8165 Plane {
8166 source,
8167 reconstruction: vec![128; source.len()],
8168 width,
8169 height,
8170 true_width,
8171 true_height,
8172 tile_x0: 0,
8173 tile_y0: 0,
8174 tile_x1: width,
8175 tile_y1: height,
8176 ctx: CoefCtxMap::default(),
8177 }
8178}
8179
8180/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
8181/// the frame's plane, through the [`crate::par::Shared`] every job holds.
8182///
8183/// corner-cut: the disjointness that makes the aliasing sound is the caller's
8184/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
8185/// rectangles partition it -- checked end-to-end by
8186/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
8187/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
8188/// row-range `split_at_mut` plumbing through `Plane`, which would have to
8189/// thread an origin offset through every prediction and transform call site
8190/// for the same bytes.
8191#[allow(unsafe_code)]
8192fn copy_rect(
8193 dst: crate::par::Shared<'_, Vec<u8>>,
8194 src: &[u8],
8195 stride: usize,
8196 x0: usize,
8197 y0: usize,
8198 x1: usize,
8199 y1: usize,
8200) {
8201 // SAFETY: this job touches only its own tile rectangle (see above).
8202 let dst = unsafe { dst.get() };
8203 for y in y0..y1 {
8204 let (a, b) = (y * stride + x0, y * stride + x1);
8205 dst[a..b].copy_from_slice(&src[a..b]);
8206 }
8207}
8208
8209/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
8210/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
8211/// tables the frame stores (spec 7.20), which is what
8212/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
8213/// below publish.
8214fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
8215 ec_av1_syntax::TileInfo {
8216 uniform_spacing: true,
8217 cols: layout.cols(),
8218 rows: layout.rows(),
8219 cols_log2: layout.cols_log2,
8220 rows_log2: layout.rows_log2,
8221 mi_col_starts: layout.mi_col_starts(),
8222 mi_row_starts: layout.mi_row_starts(),
8223 context_update_tile_id: layout.largest_tile() as u32,
8224 tile_size_bytes,
8225 }
8226}
8227
8228/// Clips the three planes' intra edge reads to `rect`, the tile the
8229/// superblock about to be searched belongs to (the encoder side of the
8230/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
8231/// raster order -- which is a linear extension of every tile's own coding
8232/// order, so a block still only ever predicts from samples already
8233/// reconstructed -- and only availability is tile-relative.
8234fn clip_planes_to_tile(
8235 luma: &mut Plane<'_>,
8236 chroma: &mut [Plane<'_>; 2],
8237 rect: crate::tile::TileRect,
8238) {
8239 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8240 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8241 luma.set_tile(x0, y0, x1, y1);
8242 for plane in chroma.iter_mut() {
8243 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
8244 }
8245}
8246
8247/// Encodes one picture as a key frame.
8248///
8249/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
8250/// picks its coefficient CDFs from one of four q contexts by that index.
8251/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
8252/// smaller values trade fidelity for rate.
8253///
8254/// The picture may be any even width and height: the encoder pads it by edge
8255/// replication to a whole number of 32x32 blocks internally, and the frame it
8256/// writes crops back to the picture's own size (`render_width`/
8257/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
8258/// own size, never the padded one.
8259///
8260/// # Errors
8261/// Returns an error when the picture's width or height is zero or odd, or
8262/// when its planes are not 4:2:0 of that size.
8263/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
8264/// stream. The per-frame decode state this needs lives for exactly this call.
8265///
8266/// # Errors
8267/// Returns an error under the same conditions
8268/// [`encode_key_frame_with_modes`] does.
8269pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
8270 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
8271}
8272
8273/// [`encode_key_frame`] with the per-block intra modes given rather than
8274/// searched.
8275///
8276/// # Errors
8277/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
8278/// is empty, or when a block's coefficients do not fit the coded frame.
8279pub fn encode_key_frame_with_modes(
8280 picture: &Picture,
8281 base_q_idx: u8,
8282 deadzone: f64,
8283 modes: &[u8],
8284) -> Result<Encoded> {
8285 encode_key_frame_with_modes_with_ctx(
8286 picture,
8287 base_q_idx,
8288 deadzone,
8289 modes,
8290 &crate::decode::FrameCtx::for_encoder(),
8291 )
8292}
8293
8294/// Codes `pictures` as one key frame followed by inter frames.
8295///
8296/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
8297/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
8298/// `show_existing_frame` header, so `stream` is in CODING order while
8299/// `frames` stays in display order (`EncodedSequence::coding_order` is the
8300/// map). Screen content codes flat, decided once per sequence by the same
8301/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
8302/// puts every stream back on the flat path for an A/B.
8303///
8304/// # Errors
8305/// Returns an error under the same conditions [`encode_key_frame`] and the
8306/// inter frame path do.
8307pub fn encode_sequence(
8308 pictures: &[Picture],
8309 base_q_idx: u8,
8310 deadzone: f64,
8311) -> Result<EncodedSequence> {
8312 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
8313}
8314
8315pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
8316 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
8317}
8318
8319/// Encodes one picture as a key frame, choosing each block's luma mode from
8320/// `modes` alone.
8321///
8322/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
8323/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
8324/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
8325/// uses.
8326///
8327/// # Errors
8328/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
8329/// names a mode [`crate::intra::predict`] does not predict.
8330pub(crate) fn encode_key_frame_with_modes_with_ctx(
8331 picture: &Picture,
8332 base_q_idx: u8,
8333 deadzone: f64,
8334 modes: &[u8], fctx: &crate::decode::FrameCtx,
8335) -> Result<Encoded> {
8336 picture.check_even()?;
8337 let padded = picture.padded_to(BLOCK);
8338 let encoded = encode_key_frame_inner(
8339 &padded,
8340 base_q_idx,
8341 deadzone,
8342 modes,
8343 split_blocks(),
8344 (picture.width, picture.height),
8345 unspecified_color_config(), fctx,
8346 )?;
8347 Ok(crop_encoded(&encoded, picture.width, picture.height))
8348}
8349
8350/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
8351/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
8352/// already padded to a whole number of 32x32 blocks; `render` is the real
8353/// (pre-pad) size the frame header tells a decoder to crop back to.
8354pub(crate) fn encode_key_frame_inner(
8355 picture: &Picture,
8356 base_q_idx: u8,
8357 deadzone: f64,
8358 modes: &[u8],
8359 split_blocks: bool,
8360 render: (usize, usize),
8361 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
8362) -> Result<Encoded> {
8363 // lane-refs: an intra frame runs no motion compensation, and the
8364 // context is shared across the sequence -- put the kernel back to the
8365 // default so nothing reads the previous inter frame's.
8366 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
8367 picture.check()?;
8368 if modes.is_empty() {
8369 return Err(Error::unsupported(
8370 "AV1 encode",
8371 "a mode search needs at least one mode to choose from",
8372 ));
8373 }
8374 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
8375 return Err(Error::unsupported(
8376 "AV1 encode",
8377 format!("intra mode {bad} is not one the encoder predicts"),
8378 ));
8379 }
8380 // The header carries the frame's true (unpadded) size as `frame_width`/
8381 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
8382 // `mi_rows` derived from that same true size (spec `compute_image_size`).
8383 // `render_width`/`render_height` come out equal to it too, so
8384 // `render_and_frame_size_different` is false and no render_size bits are
8385 // written, mirroring libaom/rav1e: the padded `picture` below is only the
8386 // internal coding surface, never what the header names.
8387 // Screen-content detection runs on the SOURCE luma, before any header is
8388 // built: it decides this sequence's `seq_force_screen_content_tools` (and
8389 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
8390 // this frame's own `allow_screen_content_tools`.
8391 let screen = screen_content(
8392 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8393 picture.width,
8394 (picture.width).min(render.0),
8395 (picture.height).min(render.1),
8396 );
8397 arm_seq_screen(screen);
8398 // A key frame's writer really does start from the defaults, and a search
8399 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
8400 // disarm, or a key frame's bits would depend on which thread searched it.
8401 crate::tile::arm_pricing_cdfs(None, false);
8402 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
8403 // forces deblocking, CDEF and loop restoration OFF for this frame
8404 // (frame.rs:194/210/252/272), so it is only set when the source repeats
8405 // itself enough for the copied blocks to pay that back
8406 // ([`intrabc_worth_it`]).
8407 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
8408 // grid across every tile while this writer builds one per tile, so a
8409 // multi-tile allow_intrabc frame would predict its DVs off a different
8410 // grid than the decoder does. corner-cut, ceiling named: the upgrade
8411 // path is a frame-scoped grid shared by the tile writers.
8412 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
8413 intrabc_worth_it(
8414 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8415 picture.width,
8416 picture.width.min(render.0),
8417 picture.height.min(render.1),
8418 )
8419 } else {
8420 (false, 0.0)
8421 };
8422 IBC_SHARE.with(|c| c.set(ibc_share));
8423 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
8424 header.allow_screen_content_tools = screen;
8425 // lane-txi: the wider `tx_type` alphabets, gated by the same content
8426 // rule the type search itself stands behind ([`wide_tx_set`]).
8427 header.reduced_tx_set = !wide_tx_set(screen);
8428 header.allow_intrabc = allow_intrabc;
8429 header.render_width = render.0 as u32;
8430 header.render_height = render.1 as u32;
8431 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
8432 // its luma transform below its own side (`crate::tile::write_luma_select`).
8433 // Set here rather than in `key_frame_headers_colour` so the header
8434 // builders' other callers -- the hand-built tile writers, which code no
8435 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
8436 let tx_select = tx_select();
8437 if tx_select {
8438 header.tx_mode = TxMode::Select;
8439 }
8440 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
8441
8442 // Prediction reads no further than this, in each plane's own units --
8443 // see `Plane::true_width`/`true_height`.
8444 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
8445 // lane-palw: the encoder's own in-process reconstruct reads its palette
8446 // colour-index maps back through `decode::palette_onscreen`, which takes
8447 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
8448 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
8449 // them here so the reconstruct clamps a block cut by the frame edge
8450 // exactly as the writer now does.
8451 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
8452 fctx.seg_mi_dims.set(frame_mi_dims);
8453 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
8454 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
8455 // design (see `intra_predict_u8`'s doc comment), so narrow the source
8456 // once here.
8457 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
8458 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
8459 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
8460 let mut luma = Plane {
8461 source: &picture_y8,
8462 reconstruction: vec![128; picture_y8.len()],
8463 width: picture.width,
8464 height: picture.height,
8465 true_width,
8466 true_height,
8467 tile_x0: 0,
8468 tile_y0: 0,
8469 tile_x1: picture.width,
8470 tile_y1: picture.height,
8471 ctx: CoefCtxMap::default(),
8472 };
8473 let mut chroma = [
8474 Plane {
8475 source: &picture_u8,
8476 reconstruction: vec![128; picture_u8.len()],
8477 width: picture.width / 2,
8478 height: picture.height / 2,
8479 true_width: true_width / 2,
8480 true_height: true_height / 2,
8481 tile_x0: 0,
8482 tile_y0: 0,
8483 tile_x1: picture.width / 2,
8484 tile_y1: picture.height / 2,
8485 ctx: CoefCtxMap::default(),
8486 },
8487 Plane {
8488 source: &picture_v8,
8489 reconstruction: vec![128; picture_v8.len()],
8490 width: picture.width / 2,
8491 height: picture.height / 2,
8492 true_width: true_width / 2,
8493 true_height: true_height / 2,
8494 tile_x0: 0,
8495 tile_y0: 0,
8496 tile_x1: picture.width / 2,
8497 tile_y1: picture.height / 2,
8498 ctx: CoefCtxMap::default(),
8499 },
8500 ];
8501
8502 // The search trades a bit for the squared error it saves, in the units the
8503 // reconstruction is measured in: one step of the quantizer, squared.
8504 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
8505 let search = Search {
8506 base_q_idx,
8507 deadzone,
8508 lambda: lambda_scale() * key_lambda_factor() * step * step,
8509 modes,
8510 top_k: prune_top_k(),
8511 screen,
8512 arf_leaf_intra: true,
8513 arf_leaf8: true,
8514 arf_leaf_compound: true,
8515 };
8516
8517 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
8518 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
8519 // which may be fewer columns/rows than the padded picture has room for
8520 // -- a block whose origin sits past the true bound is not coded at all,
8521 // matching what a decoder derives from `frame_width`/`frame_height` and
8522 // so never visits either.
8523 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
8524 let (cols, rows) = (cols as usize, rows as usize);
8525 // The luma mode of the block above and of the block to the left, which is
8526 // what picks the CDF the next block's mode is coded against -- the same
8527 // bookkeeping the tile writer keeps, so that the search is costing the
8528 // symbol the writer will actually write.
8529 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
8530 // because a 32x32 block may be split into four 16x16 ones.
8531 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
8532 // This frame's tile grid (one tile unless the facade armed more).
8533 let layout =
8534 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
8535 header.tile_info = tile_info_of(&layout, 1);
8536 // The filter search re-decodes this frame's tiles; the decoder derives
8537 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
8538 // `mi_row_starts`), which is what makes the writer's rects and the
8539 // reader's the same rects.
8540 let header_tile_info = header.tile_info.clone();
8541 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
8542 // once over the whole frame. Each tile job builds its own reconstruction
8543 // planes and its own `above_mode`/`left_mode` bands, which is also what
8544 // the tile writer reads -- a tile resets its neighbour contexts (spec
8545 // 5.11.1), so a block at a tile's left edge must cost its mode against
8546 // the default context, not against whatever the tile to its west left in
8547 // that row. At one tile the bands are the frame's, exactly as before.
8548 let (frame_width, frame_height) = (picture.width, picture.height);
8549 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
8550 let [cb, cr] = &mut chroma;
8551 let chroma_out = [
8552 crate::par::Shared::new(&mut cb.reconstruction),
8553 crate::par::Shared::new(&mut cr.reconstruction),
8554 ];
8555 let search_tile = |index: usize,
8556 fctx: &crate::decode::FrameCtx|
8557 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
8558 crate::tile::arm_pricing_cdfs(None, false);
8559 let rect = layout.rect(index);
8560 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
8561 let mut chroma = [
8562 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8563 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8564 ];
8565 clip_planes_to_tile(&mut luma, &mut chroma, rect);
8566 let mut above_mode = vec![DC_PRED; cols * 2];
8567 let mut left_mode = vec![DC_PRED; rows * 2];
8568 let mut ibc = allow_intrabc.then(|| {
8569 Ibc::new(
8570 (
8571 rect.mi_col0 as usize * 4,
8572 rect.mi_row0 as usize * 4,
8573 (rect.mi_col1 as usize * 4).min(true_width),
8574 (rect.mi_row1 as usize * 4).min(true_height),
8575 ),
8576 &picture_y8,
8577 frame_width,
8578 )
8579 });
8580 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
8581 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
8582 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
8583 let mut modes = Vec::with_capacity(4);
8584 // The quadrants of a superblock are coded in the order the decoder
8585 // walks them, which for a 64x64 split into 32x32 blocks is raster
8586 // order among the quadrants that are inside the frame.
8587 let mut blocks = Vec::with_capacity(4);
8588 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
8589 // BEFORE its quadrants (so both start from the same
8590 // reconstruction) and compared against the four of them below --
8591 // the shape the inter frame's own 64 root takes
8592 // (`search_skip_64`). A frame that allows intrabc is refused
8593 // outright ([`I64_ROOT`]) because the quadrant searches below
8594 // carry DV state a discarded trial would desync.
8595 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
8596 // lane-corner LIFTED the two guards this root shipped with: the
8597 // frame no longer has to be a whole number of superblocks, and
8598 // the superblock no longer has to be wholly inside the frame.
8599 // The desync the guards were written for (a 248x152 corner's
8600 // chroma disagreeing three ways) does NOT reproduce at this
8601 // revision -- see
8602 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
8603 // which pins all three planes of the encoder's reconstruction,
8604 // our decoder and ffmpeg on four straddling sizes, three of them
8605 // cut on BOTH axes, with the edge fire count asserted. What the
8606 // guards cost was every key-frame root on an arbitrary export
8607 // size (the `aligned` line switched the whole feature off on, for
8608 // instance, a 1920x792 frame).
8609 let whole_inside = x64 + SUPERBLOCK <= luma.true_width
8610 && y64 + SUPERBLOCK <= luma.true_height;
8611 // lane-corner: and the superblock the true frame edge CUTS
8612 // THROUGH with more than half of each axis still inside, which is
8613 // all AV1 asks of a `PARTITION_NONE` root (spec
8614 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
8615 // key writer's `Superblock::Whole` arm checks) -- the shape the
8616 // inter root already takes ([`b64_edge`]).
8617 let edge_inside = edge_root_enabled()
8618 && crate::tile::has_half(
8619 sb_col as u32 * crate::tile::SB_MI,
8620 crate::tile::SB_MI,
8621 header.mi_cols,
8622 )
8623 && crate::tile::has_half(
8624 sb_row as u32 * crate::tile::SB_MI,
8625 crate::tile::SB_MI,
8626 header.mi_rows,
8627 );
8628 let sb64_legal = i64_root()
8629 && ibc.is_none()
8630 && sb_row * 2 + 1 < rows
8631 && sb_col * 2 + 1 < cols
8632 && (whole_inside || edge_inside);
8633 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
8634 if sb64_legal {
8635 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8636 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8637 let (c64, r64) = (sb_col * 4, sb_row * 4);
8638 let (block, cost) = code_square(
8639 &mut luma,
8640 &mut chroma,
8641 (x64, y64),
8642 SUPERBLOCK,
8643 &search,
8644 &mode_bits(above_mode[c64], left_mode[r64]),
8645 tx_select,
8646 None,
8647 true,
8648 fctx,
8649 );
8650 let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
8651 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8652 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
8653 sb64 = Some((cost, block, after));
8654 }
8655 // A superblock whose 64x64 trial already codes almost nothing per
8656 // pixel is taken outright and its quadrants are never searched --
8657 // `split_rd_breakout` one size up, at the threshold the inter
8658 // root clamps to ([`b64_breakout_threshold`]), where this lever
8659 // BUYS wall instead of spending it.
8660 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
8661 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
8662 });
8663 // What the four quadrants cost together, including the split
8664 // partition symbol at the superblock level, so the two arms are
8665 // one comparable number.
8666 let mut sb_cost = match sb64 {
8667 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
8668 None => 0.0,
8669 };
8670 for quadrant in 0..if early64 { 0 } else { 4 } {
8671 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
8672 if col >= cols || row >= rows {
8673 continue;
8674 }
8675 let (x, y) = (col * BLOCK, row * BLOCK);
8676 let (c0, r0) = (col * 2, row * 2);
8677 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
8678
8679 // spec `decode_partition`'s hasRows/hasCols recomputed at this
8680 // 32x32 block's own half (see `crate::tile::has_half`): the
8681 // true frame edge can fall inside a quadrant a superblock-level
8682 // check already let through. A quadrant that fails either may
8683 // not be left whole; a 16x16 sub-block that fails either (once
8684 // split) is a leaf this writer has no rectangular transform
8685 // for, so the search must not pick a split that would need one.
8686 let (has_cols32, has_rows32) = (
8687 crate::tile::has_half(
8688 col as u32 * crate::tile::BLOCK_MI,
8689 crate::tile::BLOCK_MI,
8690 header.mi_cols,
8691 ),
8692 crate::tile::has_half(
8693 row as u32 * crate::tile::BLOCK_MI,
8694 crate::tile::BLOCK_MI,
8695 header.mi_rows,
8696 ),
8697 );
8698 let whole_legal = has_cols32 && has_rows32;
8699 // A 16x16 sub-block's own hasCols/hasRows (spec
8700 // `decode_partition`, recomputed at this leaf's own half):
8701 // either axis false is a straddling leaf this writer codes as
8702 // the 8x8 leaves that are inside it
8703 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
8704 // false is the same split with the partition symbol inferred
8705 // rather than coded -- no rectangular transform is needed
8706 // (lane-av1rect).
8707 let sub_half = |sr: usize, sc: usize| {
8708 (
8709 crate::tile::has_half(
8710 sc as u32 * crate::tile::SUB_MI,
8711 crate::tile::SUB_MI,
8712 header.mi_cols,
8713 ),
8714 crate::tile::has_half(
8715 sr as u32 * crate::tile::SUB_MI,
8716 crate::tile::SUB_MI,
8717 header.mi_rows,
8718 ),
8719 )
8720 };
8721 // What the whole 32x32 costs, including the partition symbol
8722 // that says it is not split.
8723 let (whole, mut cost_whole) = code_square(
8724 &mut luma,
8725 &mut chroma,
8726 (x, y),
8727 BLOCK,
8728 &search,
8729 &mode_bits(above_mode[c0], left_mode[r0]),
8730 tx_select,
8731 ibc.as_mut(),
8732 true,
8733 fctx,
8734 );
8735 cost_whole += search.lambda * partition_bits(BLOCK, false);
8736 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
8737
8738 // What four 16x16 blocks cost instead, each searched against
8739 // the reconstruction the ones before it left.
8740 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
8741 let mut split = Vec::with_capacity(4);
8742 let mut cost_split = search.lambda
8743 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
8744 let mut split_modes = Vec::with_capacity(4);
8745 for sub in 0..4 {
8746 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
8747 // Same filter as the writer's `sub_positions` (spec
8748 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
8749 // return): a sub-block whose own origin sits past the
8750 // true frame is never coded, so it must not be searched
8751 // or pushed onto `split` either, or the writer's block
8752 // count will not match what it is prepared to name.
8753 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
8754 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
8755 {
8756 continue;
8757 }
8758 let (has_cols16, has_rows16) = sub_half(sr, sc);
8759 if has_cols16 && has_rows16 {
8760 let (block, cost) = code_square(
8761 &mut luma,
8762 &mut chroma,
8763 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
8764 SUB,
8765 &search,
8766 &mode_bits(above_mode[sc], left_mode[sr]),
8767 tx_select,
8768 ibc.as_mut(),
8769 true,
8770 fctx,
8771 );
8772 cost_split += cost;
8773 split_modes.push(block.mode);
8774 above_mode[sc] = block.mode;
8775 left_mode[sr] = block.mode;
8776 split.push(block);
8777 } else {
8778 // A straddling 16x16: two (or, at a true corner, one)
8779 // 8x8 leaves, in the raster order `write_leaf8`'s
8780 // caller expects. Both leaves cost against the SAME
8781 // enclosing-slot mode context (see
8782 // `crate::tile::write_leaf8`'s doc), and neither
8783 // updates `above_mode`/`left_mode` at this SUB slot --
8784 // the writer never does either, so the search must
8785 // not diverge from what it will actually read next.
8786 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
8787 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
8788 let mut leaves = Vec::with_capacity(2);
8789 for i in 0..4 {
8790 let leaf_x = x_sub + (i % 2) * 8;
8791 let leaf_y = y_sub + (i / 2) * 8;
8792 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
8793 continue;
8794 }
8795 let (leaf, cost) = code_square(
8796 &mut luma,
8797 &mut chroma,
8798 (leaf_x, leaf_y),
8799 8,
8800 &search,
8801 &leaf_mode_bits,
8802 tx_select,
8803 None,
8804 true,
8805 fctx,
8806 );
8807 cost_split += cost;
8808 split_modes.push(leaf.mode);
8809 leaves.push(leaf);
8810 }
8811 split.push(BlockCoeffs {
8812 eight: Some(leaves),
8813 ..BlockCoeffs::default()
8814 });
8815 }
8816 }
8817
8818 // A split whose subs are all whole 16x16 is a real quality
8819 // alternative to `whole`, exactly as before. Through r14, a
8820 // split carrying an 8x8-leaf sub was only ever forced
8821 // (`!whole_legal`), never chosen on cost, because the leaf
8822 // path was not yet proven against a real decoder; r15 proved
8823 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
8824 // the read path (`decode_leaf8`), so leaf8 can now win on
8825 // cost anywhere, same as any other split.
8826 if !whole_legal || (split_blocks && cost_split < cost_whole) {
8827 sb_cost += cost_split;
8828 modes.extend_from_slice(&split_modes);
8829 blocks.push(Quadrant::Split(split));
8830 } else {
8831 sb_cost += cost_whole;
8832 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
8833 for cell in 0..2 {
8834 above_mode[c0 + cell] = whole.mode;
8835 left_mode[r0 + cell] = whole.mode;
8836 }
8837 modes.push(whole.mode);
8838 blocks.push(Quadrant::Whole(whole));
8839 }
8840 }
8841 let index = sb_row * sb_cols + sb_col;
8842 match sb64 {
8843 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
8844 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
8845 for cell in 0..4 {
8846 above_mode[sb_col * 4 + cell] = block.mode;
8847 left_mode[sb_row * 4 + cell] = block.mode;
8848 }
8849 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8850 if !whole_inside {
8851 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8852 }
8853 let mode = block.mode;
8854 coded.push((index, Superblock::Whole(block), vec![mode]));
8855 }
8856 _ => coded.push((index, Superblock::Split(blocks), modes)),
8857 }
8858 }
8859 }
8860 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8861 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8862 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
8863 for (&out, tile) in chroma_out.iter().zip(&chroma) {
8864 copy_rect(
8865 out,
8866 &tile.reconstruction,
8867 frame_width / 2,
8868 x0 / 2,
8869 y0 / 2,
8870 x1.div_ceil(2),
8871 y1.div_ceil(2),
8872 );
8873 }
8874 Ok(coded)
8875 };
8876 let searched = search_tiles(layout.count(), fctx, search_tile)?;
8877 // Back into frame raster order: the tile writer indexes `superblocks` by
8878 // the frame's own superblock index, and `modes` is the coding order the
8879 // ablation drivers read.
8880 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
8881 for (at, superblock, block_modes) in searched.into_iter().flatten() {
8882 in_order[at] = Some((superblock, block_modes));
8883 }
8884 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
8885 let mut modes = Vec::with_capacity(cols * rows);
8886 for slot in in_order {
8887 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
8888 superblocks.push(superblock);
8889 modes.extend_from_slice(&block_modes);
8890 }
8891
8892 #[cfg(test)]
8893 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
8894 // A key frame always starts from the defaults (`primary_ref_frame` is
8895 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
8896 // set, so what it stores into the slots it refreshes is exactly those
8897 // defaults again (spec 7.20's `started_from` arm) -- the first inter
8898 // frame after it therefore starts from the defaults too.
8899 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
8900 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
8901 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
8902 // from -- `Cdfs::txb` widens every luma set under it.
8903 cdfs.reduced_tx_set = header.reduced_tx_set;
8904 let start_cdfs = CdfSnapshot(cdfs);
8905 // The luma restoration-unit grid this frame's `lr_params` implies
8906 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
8907 // swallowed by the one before it), for the tile writer's own per-unit
8908 // walk.
8909 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
8910 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
8911 // Every tile is coded from this frame's OWN starting tables and leaves
8912 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
8913 // loop-restoration reference and its neighbour contexts), so the tiles
8914 // are independent of each other and of the order they are written in.
8915 let code_tiles = |bits: u8,
8916 sb_cols: usize,
8917 grid: &[u8],
8918 units: &[Option<crate::restoration::WienerInfo>]|
8919 -> Result<Vec<Vec<u8>>> {
8920 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
8921 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
8922 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
8923 crate::tile::arm_sb128(sb128_on());
8924 let mut cdfs = start_cdfs.0.clone();
8925 crate::tile::arm_screen(screen);
8926 crate::tile::arm_frame_mi_dims(frame_mi_dims);
8927 crate::tile::arm_filter_intra(filter_intra_on());
8928 crate::tile::arm_intrabc(allow_intrabc);
8929 crate::tile::arm_pricing_cdfs(None, false);
8930 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
8931 mi_cols,
8932 mi_rows,
8933 base_q_idx,
8934 &superblocks,
8935 tx_select,
8936 &mut cdfs,
8937 layout.rect(index),
8938 )?;
8939 Ok((bytes, None))
8940 })?;
8941 Ok(out)
8942 };
8943 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
8944 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
8945 // the tile just coded back to the decoder under each candidate (see
8946 // `crate::filter_search`), and keep the filtered picture that wins as
8947 // the reconstruction -- what a decoder outputs, and what the next
8948 // frame predicts from.
8949 pick_and_apply_filters(
8950 &mut header,
8951 &mut luma,
8952 &mut chroma,
8953 [&picture_y8, &picture_u8, &picture_v8],
8954 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
8955 // and loop restoration off and codes none of their parameters
8956 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
8957 // the encoder's reconstruction is already what a decoder produces.
8958 !allow_intrabc,
8959 &mut tiles,
8960 search.lambda,
8961 fctx,
8962 // A key frame codes no 128x128 root block (the writer has no intra
8963 // path at that size), so every unit carries its own literal.
8964 &[],
8965 // Every re-code starts from this frame's OWN starting tables, never
8966 // from where the first write left them: the second tile is the same
8967 // symbol sequence plus new ones, so it must adapt from the same
8968 // point the decoder will.
8969 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
8970 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
8971 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
8972 crate::decode::decode_key_frame_tiles_lr(
8973 &payloads,
8974 &header_tile_info,
8975 h.mi_cols,
8976 h.mi_rows,
8977 base_q_idx,
8978 h.frame_width,
8979 h.frame_height,
8980 seq.enable_filter_intra,
8981 cdef,
8982 lf,
8983 tx_select,
8984 h.reduced_tx_set,
8985 h.allow_screen_content_tools,
8986 h.allow_intrabc,
8987 lr,
8988 fctx,
8989 )
8990 },
8991 )?;
8992 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
8993 header.tile_info.tile_size_bytes = tile_size_bytes;
8994 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
8995 let mut stream = temporal_delimiter();
8996 stream.extend_from_slice(&sequence_header_obu(&seq)?);
8997 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
8998
8999 let [u, v] = chroma;
9000 Ok(Encoded {
9001 stream,
9002 modes,
9003 inter_block_share: 0.0,
9004 reconstruction: Picture {
9005 width: luma.width,
9006 height: luma.height,
9007 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9008 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9009 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9010 },
9011 tile,
9012 mi_cols: header.mi_cols,
9013 mi_rows: header.mi_rows,
9014 base_q_idx,
9015 tx_select,
9016 // A key frame codes no inter block, so no motion_mode symbol.
9017 switchable_motion_mode: false,
9018 screen,
9019 reduced_tx_set: header.reduced_tx_set,
9020 next_cdfs: start_cdfs.clone(),
9021 start_cdfs,
9022 loop_filter: header.loop_filter,
9023 cdef: header.cdef,
9024 loop_restoration: header.loop_restoration,
9025 allow_intrabc,
9026 delta: header.delta.clone(),
9027 })
9028}
9029
9030/// Chooses this frame's deblocking levels and CDEF strengths, writes them
9031/// into `header` and
9032/// replaces the frame's own region of the encoder's reconstruction with the
9033/// filtered picture the decoder produced under them
9034/// ([`crate::filter_search::pick_deblock`]).
9035///
9036/// `search == false` leaves the header at level 0 (deblocking off) and the
9037/// reconstruction untouched: the caller's stream is one this crate's own
9038/// decoder cannot read back, so there is nothing to search against.
9039///
9040/// # Errors
9041/// The decoder's own error, when it refuses the tile the encoder just wrote
9042/// -- that is an encoder defect, not a filter one, so it is propagated
9043/// rather than swallowed into "no deblocking".
9044fn pick_and_apply_filters(
9045 header: &mut FrameHeader,
9046 luma: &mut Plane<'_>,
9047 chroma: &mut [Plane<'_>; 2],
9048 source: [&[u8]; 3],
9049 search: bool,
9050 // The coded tiles, one payload per tile of the frame's grid, replaced in
9051 // place when the search chooses a per-64x64 `cdef_idx` list
9052 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
9053 // tile is written a second time under `recode` and the winner
9054 // re-decoded from them.
9055 tiles: &mut Vec<Vec<u8>>,
9056 lambda: f64,
9057 fctx: &crate::decode::FrameCtx,
9058 // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles
9059 // carry -- empty (the identity map) for a frame whose every block covers
9060 // one 64x64 CDEF unit.
9061 cdef_owner: &[u32],
9062 recode: impl Fn(
9063 u8,
9064 usize,
9065 &[u8],
9066 &[Option<crate::restoration::WienerInfo>],
9067 ) -> Result<Vec<Vec<u8>>>,
9068 decode: impl Fn(
9069 &LoopFilterParams,
9070 &CdefParams,
9071 &FrameHeader,
9072 &[Vec<u8>],
9073 &LoopRestorationParams,
9074 ) -> Result<Picture>,
9075) -> Result<()> {
9076 if !search {
9077 return Ok(());
9078 }
9079 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
9080 let hdr = header.clone();
9081 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
9082 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
9083 let damping = 3 + (header.quantization.base_q_idx >> 6);
9084 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9085 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
9086 let none_lr = LoopRestorationParams::default();
9087 // Every candidate scores the same coded tile: decode it once and re-run
9088 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
9089 // the encoder's profile before this). The per-64x64 error the CDEF
9090 // preset search reads comes off the REPLAYED picture, which is the same
9091 // picture a decode produces -- that is what the replay is pinned on.
9092 crate::decode::clear_filter_replay();
9093 // lane-av1fpar: the per-tile search is over, so every core is idle from
9094 // here to the end of the frame -- band each candidate's deblock/CDEF
9095 // replay, the capture decode's own filter chain and the loop-restoration
9096 // passes across the same workers the search used.
9097 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
9098 let ft = crate::par::timer(crate::par::S_FILTER);
9099 let search_result = crate::filter_search::pick_filters(
9100 |lf, cdef| {
9101 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
9102 return Ok(picture);
9103 }
9104 crate::decode::arm_filter_replay();
9105 let _t = crate::par::timer(crate::par::S_FIRST);
9106 decode(lf, cdef, &hdr, tiles, &none_lr)
9107 },
9108 source,
9109 luma.width,
9110 (fw, fh),
9111 damping,
9112 (sb_cols, sb_rows),
9113 lambda,
9114 cdef_owner,
9115 );
9116 drop(ft);
9117 let (lf, cdef, idx_grid, picture) = search_result?;
9118 header.loop_filter = lf;
9119 header.cdef = cdef;
9120 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
9121 // in the frame header, so a re-decode under candidate parameters cannot
9122 // search them the way deblocking and CDEF are searched above. What the
9123 // decoder hands back instead is its own filter chain's intermediates
9124 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
9125 // those, through the decoder's own Wiener kernel.
9126 //
9127 // The capture rides the decode this stage was already going to do: the
9128 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
9129 // decode of the tile as it stands. That decode's header still says
9130 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
9131 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
9132 // an approximation inside the SEARCH only; the reconstruction this
9133 // function ends up splicing is always a real decode of the real tile.
9134 let lr_on = restoration_enabled();
9135 // The `cdef_idx` literals live in the tile payload, so a frame that
9136 // chose a per-64x64 preset list codes its tiles a second time.
9137 if !idx_grid.is_empty() {
9138 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
9139 }
9140 // lane-av1cap: that re-coded tile used to be DECODED here as well --
9141 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
9142 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
9143 // and the picture this function splices. Both come out of ONE more
9144 // replay of the winning parameters on the same captured pre-filter
9145 // planes every candidate was scored on: the same two filter kernels, on
9146 // the same input, in the same order, so the same bytes. Re-coding the
9147 // tile does not move the reconstruction the replay holds -- `cdef_idx`
9148 // is an equiprobable literal, so it adapts no CDF and changes no
9149 // residual.
9150 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
9151 #[cfg(test)]
9152 let replay_was_used = replayed.is_some();
9153 let (mut filtered, mut stages) = match replayed {
9154 Some((picture, stages)) => (picture, stages),
9155 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
9156 // refuses): every candidate was a full decode, so the winner's own
9157 // picture stands, and the stages still need a capturing decode.
9158 None => {
9159 fctx.capture_stages.set(lr_on);
9160 let picture = if idx_grid.is_empty() && !lr_on {
9161 picture
9162 } else {
9163 let _t = crate::par::timer(crate::par::S_CAPTURE);
9164 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
9165 };
9166 fctx.capture_stages.set(false);
9167 (picture, crate::decode::take_filter_stages(fctx))
9168 }
9169 };
9170 #[cfg(test)]
9171 if crate::decode::verify_final_replay() && replay_was_used {
9172 fctx.capture_stages.set(lr_on);
9173 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
9174 fctx.capture_stages.set(false);
9175 let want_stages = crate::decode::take_filter_stages(fctx);
9176 assert!(
9177 (want.width, want.height) == (filtered.width, filtered.height)
9178 && want.y == filtered.y
9179 && want.u == filtered.u
9180 && want.v == filtered.v,
9181 "the final filter replay is not the capture decode it stands in for",
9182 );
9183 // Only the frame's own cropped region: the plane is padded to the
9184 // superblock grid and the columns past the mi extent are written by
9185 // nothing (the decoder's plane pool leaves whatever the last frame
9186 // put there), while the restoration search reads strictly inside
9187 // `fw x fh` -- `restoration::lr_sample` clamps its column to
9188 // `plane_w - 1` and its row to the frame's, and
9189 // `filter_search::pick_restoration`'s own SSE walk never leaves the
9190 // crop either.
9191 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
9192 for row in 0..h {
9193 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
9194 assert!(
9195 x == y,
9196 "{what}: the replayed filter stages are not the ones the capture \
9197 decode returns (row {row} of {h}, width {w}, stride {stride})",
9198 );
9199 }
9200 };
9201 match (&want_stages, &stages) {
9202 (Some(a), Some(b)) => {
9203 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
9204 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9205 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
9206 region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked");
9207 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
9208 }
9209 }
9210 (None, None) => {}
9211 _ => panic!("one path captured filter stages and the other did not"),
9212 }
9213 }
9214 // lane-av1cap2: the capture stays live past the restoration search --
9215 // `crate::decode::replay_restoration` filters the same post-CDEF plane
9216 // rather than decoding the re-coded tile. Cleared at the end instead.
9217 let mut lr = LoopRestorationParams::default();
9218 if lr_on {
9219 let unit = lr_unit();
9220 let mut want = LoopRestorationParams {
9221 loop_restoration_size: [unit, unit, unit],
9222 uses_lr: true,
9223 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
9224 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
9225 lr_unit_shift: u8::from(unit == 128),
9226 ..LoopRestorationParams::default()
9227 };
9228 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
9229 let lrt = crate::par::timer(crate::par::S_LR);
9230 let units = match stages.take() {
9231 Some(stages) => crate::filter_search::pick_restoration(
9232 &stages,
9233 source[0],
9234 luma.width,
9235 (fw, fh),
9236 &want,
9237 lambda,
9238 fctx,
9239 ),
9240 None => Vec::new(),
9241 };
9242 // A frame no unit restores keeps `RESTORE_NONE` on every plane
9243 // rather than paying ~1 bit per 64x64 for a tile full of
9244 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
9245 // clip whose units never take a filter).
9246 drop(lrt);
9247 if units.iter().any(Option::is_some) {
9248 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
9249 let _t = crate::par::timer(crate::par::S_CAPTURE);
9250 // lane-av1cap2: that re-coded tile used to be DECODED here to
9251 // reach the restored reference frame -- 5.6% of a 4K frame,
9252 // for a filter that reads nothing of the tile but the per-unit
9253 // Wiener filters this stage just chose. Run the decoder's own
9254 // restoration kernel on the replay's post-CDEF plane instead
9255 // (`crate::decode::replay_restoration`), with the real
9256 // post-deblock stripe borders.
9257 match crate::decode::replay_restoration(&want, &units, fctx) {
9258 Some(y) => {
9259 #[cfg(test)]
9260 let margin = fctx
9261 .last_frame_wide_margin
9262 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
9263 #[cfg(test)]
9264 if crate::decode::verify_final_replay() {
9265 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
9266 assert!(
9267 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
9268 && want_pic.u == filtered.u
9269 && want_pic.v == filtered.v,
9270 "the restoration replay moved a chroma plane or the picture size",
9271 );
9272 assert!(
9273 want_pic.y == y,
9274 "the restoration replay is not the decode of the re-coded tile",
9275 );
9276 assert!(
9277 fctx.last_frame_wide_margin
9278 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
9279 == margin,
9280 "the restoration replay's wide-margin luma is not the decode's",
9281 );
9282 }
9283 filtered.y = y;
9284 }
9285 // Nothing captured: the winner came out of a full decode,
9286 // so this one does too.
9287 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
9288 }
9289 *tiles = coded;
9290 lr = want;
9291 }
9292 }
9293 crate::decode::clear_filter_replay();
9294 header.loop_restoration = lr;
9295 let dec_cw = filtered.width.div_ceil(2);
9296 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9297 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
9298 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
9299 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
9300 Ok(())
9301}
9302
9303/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
9304/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
9305/// since every block this crate's inter tile writer codes is 32x32.
9306const SIZE_GROUP_32: usize = 3;
9307
9308/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
9309/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
9310/// stack this encoder builds is ever asked to predict against.
9311const LAST_FRAME: i8 = 1;
9312
9313/// What an inter frame's intra branch spends to name each of the thirteen
9314/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
9315/// context, since an inter frame's intra blocks do not read their
9316/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
9317/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
9318/// state, so it is built once per frame.
9319fn inter_mode_bits() -> [f64; 13] {
9320 std::array::from_fn(|mode| {
9321 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
9322 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
9323 } else {
9324 0.0
9325 };
9326 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
9327 + angle
9328 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
9329 })
9330}
9331
9332/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
9333/// [`mc::predict`] takes, in the units of the plane it predicts into.
9334///
9335/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
9336/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
9337/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
9338/// domain. `luma` picks which.
9339fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
9340 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
9341}
9342
9343/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
9344/// that module): the magnitude an `MV_CLASS_n` component's own bits start
9345/// counting from.
9346fn mv_class_base(class: usize) -> i32 {
9347 if class == 0 { 0 } else { 2i32 << (class + 2) }
9348}
9349
9350/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
9351/// `tile::mv_class_of`.
9352fn mv_class_of(z: i32) -> usize {
9353 let mut class = 0;
9354 while class < 10 && mv_class_base(class + 1) <= z {
9355 class += 1;
9356 }
9357 class
9358}
9359
9360/// What [`crate::tile::write_mv_component`] (private to that module) would
9361/// spend coding one non-zero motion vector component, against the same
9362/// static default CDFs the writer starts a frame from — the same
9363/// static-table approximation [`mode_bits`] costs the luma mode symbol
9364/// through, not the tile writer's own adapting state, which this encoder has
9365/// no way to read without duplicating it block for block.
9366///
9367/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
9368/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
9369/// exists to avoid ever happening.
9370fn mv_component_bits(diff: i32) -> Option<f64> {
9371 let hp_frame = crate::tile::high_precision_mv();
9372 let mag = diff.unsigned_abs() as i32;
9373 let z = mag - 1;
9374 if !hp_frame && z & 1 == 0 {
9375 return None;
9376 }
9377 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
9378 let class = mv_class_of(z);
9379 bits += symbol_bits(&cdf::MV_CLASS, class);
9380 let local = z - mv_class_base(class);
9381 let hp = (local & 1) as usize;
9382 if class == 0 {
9383 let bit = (local >> 3) & 1;
9384 let fr = (local >> 1) & 3;
9385 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
9386 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
9387 // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
9388 // frame, so the pricer charges for it there and only there.
9389 if hp_frame {
9390 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
9391 }
9392 } else {
9393 let d = local >> 3;
9394 let fr = (local >> 1) & 3;
9395 for i in 0..class {
9396 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
9397 }
9398 bits += symbol_bits(&cdf::MV_FR, fr as usize);
9399 if hp_frame {
9400 bits += symbol_bits(&cdf::MV_HP, hp);
9401 }
9402 }
9403 Some(bits)
9404}
9405
9406/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
9407/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
9408/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
9409/// value without the second motion search's wall.
9410fn last2_new_mv() -> bool {
9411 match std::env::var("EC_AV1_LAST2_NEW").ok() {
9412 Some(v) => v != "0",
9413 None => true,
9414 }
9415}
9416
9417/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
9418/// own -- a second motion search per block against that reference's picture,
9419/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
9420/// off in a test build (what the lane measured both arms with).
9421fn extra_ref_new_mv() -> bool {
9422 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
9423 Some(v) if cfg!(test) => v != "0",
9424 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
9425 }
9426}
9427
9428/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
9429/// flat slot plan (`inter_frame_headers_slots`): every reference but
9430/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
9431/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
9432/// frame two back when there is one (otherwise it, too, names the key frame's
9433/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
9434pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
9435 let last = order_hint.wrapping_sub(1) & 0x7f;
9436 let alt = if has_altref {
9437 order_hint.wrapping_sub(2) & 0x7f
9438 } else {
9439 key_hint
9440 };
9441 [last, last, last, key_hint, last, last, alt]
9442}
9443
9444/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
9445/// header bit that lets each block choose between a single and a compound
9446/// reference. Off by default until compound prediction is measured to pay;
9447/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
9448/// runs as), and every block still codes SINGLE, so the only cost is one
9449/// `comp_mode` symbol per inter block.
9450pub(crate) const REFERENCE_SELECT: bool = true;
9451
9452/// [`REFERENCE_SELECT`], with the test-build environment override.
9453pub(crate) fn reference_select() -> bool {
9454 match std::env::var("EC_AV1_COMPOUND").ok() {
9455 Some(v) if cfg!(test) => v != "0",
9456 _ => crate::speed::at(&crate::speed::COMPOUND),
9457 }
9458}
9459
9460/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
9461/// per entry past `start`, `1` to advance and `0` to stop, at most two.
9462fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
9463 let mut bits = 0.0;
9464 let mut idx = start;
9465 while idx < start + 2 && stack.entries.len() > idx + 1 {
9466 let advance = idx < target;
9467 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
9468 if !advance {
9469 break;
9470 }
9471 idx += 1;
9472 }
9473 bits
9474}
9475
9476/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
9477/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
9478/// `assign_mv`), so the same vector costs a different residual from each.
9479fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
9480 let mut best: Option<(f64, u8)> = None;
9481 for idx in 0..3usize {
9482 if idx > 0 && stack.entries.len() <= idx {
9483 break;
9484 }
9485 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
9486 if let Some(b) = mv_residual_bits(mv, base) {
9487 let total = b + drl_bits_for(stack, 0, idx);
9488 if best.is_none_or(|(t, _)| total < t) {
9489 best = Some((total, idx as u8));
9490 }
9491 }
9492 }
9493 best
9494}
9495
9496/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
9497/// zero vector and the stack's own candidates. A neighbour block's vector is
9498/// where this block's motion most often already is, which is what pays for
9499/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
9500/// vs libaom for 0.2 s off a 6 s ladder).
9501fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
9502 let mut seeds = [(0, 0); 4];
9503 let mut n = 1;
9504 for e in stack.entries.iter().take(3) {
9505 seeds[n] = e.mv;
9506 n += 1;
9507 }
9508 (seeds, n)
9509}
9510
9511/// What [`crate::tile::write_mv`] (private to that module) would spend
9512/// coding `mv` as a residual against `pred`: the joint symbol naming which
9513/// components differ, then each differing component. `None` under the same
9514/// condition [`mv_component_bits`] returns `None`.
9515/// How many frames back `ref_frame` sits from the frame being coded, off the
9516/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
9517/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
9518/// what [`crate::motion::search`] scales its starting step by.
9519fn ref_distance(ref_frame: i8) -> u32 {
9520 let (bits, order_hint, hints) = crate::tile::order_hints();
9521 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
9522 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
9523 .unsigned_abs()
9524 .max(1);
9525 if crate::envflags::env_flag!("EC_TRACE_DIST") {
9526 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
9527 }
9528 d
9529}
9530
9531fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
9532 let diff = (mv.0 - pred.0, mv.1 - pred.1);
9533 let joint = match (diff.0 != 0, diff.1 != 0) {
9534 (false, false) => 0,
9535 (false, true) => 1,
9536 (true, false) => 2,
9537 (true, true) => 3,
9538 };
9539 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
9540 for d in [diff.0, diff.1] {
9541 if d != 0 {
9542 bits += mv_component_bits(d)?;
9543 }
9544 }
9545 Some(bits)
9546}
9547
9548/// Rounds `mv` so that its residual against `pred` is one
9549/// [`crate::tile::write_mv_component`] can actually code: each component's
9550/// difference is either zero or has an even magnitude (the eighth-pel bit
9551/// `allow_high_precision_mv` off always infers as one forces the coded
9552/// magnitude odd one step further in, which comes out even here since this
9553/// crate's motion search works in whole units of that same step). Rounding
9554/// down keeps every coded MV — and so every `nearest_mv` a later block's
9555/// stack votes with — built from an even displacement from `(0, 0)`, so the
9556/// invariant holds without this function seeing the whole stack.
9557/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
9558/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
9559/// always), the shape [`set_frame_interp`] has: the witness that has to see
9560/// `mv_hp` symbols coded turns it on through this while holding
9561/// [`crate::speed::knob_write`].
9562static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
9563
9564/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
9565#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
9566pub(crate) fn set_high_precision_mv(on: Option<bool>) {
9567 HP_MV_OVERRIDE.store(on.map_or(u8::MAX, u8::from), std::sync::atomic::Ordering::Relaxed);
9568}
9569
9570/// The qindex below which an inter frame codes `allow_high_precision_mv`
9571/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
9572/// crate's shipped value, i.e. high-precision motion vectors off in every
9573/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
9574pub(crate) const HP_MV_QTHRESH: u8 = 0;
9575
9576/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
9577/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
9578/// always, any number as the threshold) so the BD gate can sweep the policy
9579/// without a rebuild.
9580pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
9581 match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
9582 0 => return false,
9583 1 => return true,
9584 _ => {}
9585 }
9586 static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
9587 let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
9588 Some("all" | "always") => 256,
9589 Some("0" | "off") => 0,
9590 Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
9591 None => u16::from(HP_MV_QTHRESH),
9592 });
9593 u16::from(base_q_idx) < threshold
9594}
9595
9596fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
9597 // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
9598 // residual is codable and there is nothing to round away.
9599 if crate::tile::high_precision_mv() {
9600 return mv;
9601 }
9602 let round = |m: i32, p: i32| {
9603 let diff = m - p;
9604 let mag = diff.unsigned_abs() as i32;
9605 let even = mag - mag % 2;
9606 if even == 0 {
9607 p
9608 } else {
9609 p + even * diff.signum()
9610 }
9611 };
9612 (round(mv.0, pred.0), round(mv.1, pred.1))
9613}
9614
9615/// Predicts one `side`-square block by motion compensation from `reference`
9616/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
9617#[allow(clippy::too_many_arguments)]
9618fn mc_trial(
9619 plane: &Plane,
9620 x: usize,
9621 y: usize,
9622 side: usize,
9623 mv: (i32, i32),
9624 luma: bool,
9625 reference: &[u16],
9626 stride: usize,
9627 ref_width: usize,
9628 ref_height: usize,
9629 skip: bool,
9630 base_q_idx: u8,
9631 deadzone: f64,
9632 set: TxbSet,
9633 fctx: &crate::decode::FrameCtx,
9634) -> Trial {
9635 mc_trial_typed(
9636 plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx,
9637 deadzone, set, TxType::DctDct, fctx,
9638 )
9639}
9640
9641/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
9642#[allow(clippy::too_many_arguments)]
9643fn mc_trial_typed(
9644 plane: &Plane,
9645 x: usize,
9646 y: usize,
9647 side: usize,
9648 mv: (i32, i32),
9649 luma: bool,
9650 reference: &[u16],
9651 stride: usize,
9652 ref_width: usize,
9653 ref_height: usize,
9654 skip: bool,
9655 base_q_idx: u8,
9656 deadzone: f64,
9657 set: TxbSet,
9658 tx_type: TxType,
9659 fctx: &crate::decode::FrameCtx,
9660) -> Trial {
9661 let x_q4 = mv_to_q4(x, mv.1, luma);
9662 let y_q4 = mv_to_q4(y, mv.0, luma);
9663 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
9664 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
9665 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
9666 // lane-av1speed: both buffers are per-candidate scratch on the hottest
9667 // path in the encoder, so they live on the stack -- `side` is at most
9668 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
9669 // per motion-compensated trial otherwise.
9670 let mut prediction16 = [0u16; BLOCK * BLOCK];
9671 let prediction16 = &mut prediction16[..side * side];
9672 mc::predict(
9673 reference,
9674 stride,
9675 ref_width,
9676 ref_height,
9677 x_q4,
9678 y_q4,
9679 side,
9680 side,
9681 prediction16, fctx,
9682 );
9683 let mut prediction = [0u8; BLOCK * BLOCK];
9684 let prediction = &mut prediction[..side * side];
9685 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
9686 *dst = src as u8;
9687 }
9688 plane.code_from_prediction_typed(
9689 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
9690 )
9691}
9692
9693/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
9694/// references predict into the `CONV_BUF` intermediate domain
9695/// ([`mc::predict_compound_intermediate`]) and are blended by
9696/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
9697/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
9698/// block, so the encoder's reconstruction is the decoder's.
9699#[allow(clippy::too_many_arguments)]
9700fn mc_trial_compound(
9701 plane: &Plane,
9702 x: usize,
9703 y: usize,
9704 side: usize,
9705 mvs: ((i32, i32), (i32, i32)),
9706 luma: bool,
9707 ref0: (&[u16], usize, usize, usize),
9708 ref1: (&[u16], usize, usize, usize),
9709 base_q_idx: u8,
9710 deadzone: f64,
9711 set: TxbSet,
9712 fctx: &crate::decode::FrameCtx,
9713) -> Trial {
9714 mc_trial_compound_typed(
9715 plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx,
9716 )
9717}
9718
9719/// [`mc_trial_compound`] coding its residual with a named transform type
9720/// (lane-txset2).
9721#[allow(clippy::too_many_arguments)]
9722fn mc_trial_compound_typed(
9723 plane: &Plane,
9724 x: usize,
9725 y: usize,
9726 side: usize,
9727 (mv0, mv1): ((i32, i32), (i32, i32)),
9728 luma: bool,
9729 ref0: (&[u16], usize, usize, usize),
9730 ref1: (&[u16], usize, usize, usize),
9731 base_q_idx: u8,
9732 deadzone: f64,
9733 set: TxbSet,
9734 tx_type: TxType,
9735 fctx: &crate::decode::FrameCtx,
9736) -> Trial {
9737 let mut inter0 = [0i32; BLOCK * BLOCK];
9738 let mut inter1 = [0i32; BLOCK * BLOCK];
9739 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
9740 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
9741 mc::predict_compound_intermediate(
9742 r.0,
9743 r.1,
9744 r.2,
9745 r.3,
9746 mv_to_q4(x, mv.1, luma),
9747 mv_to_q4(y, mv.0, luma),
9748 mc::REF_NO_SCALE,
9749 side,
9750 side,
9751 fctx.interp_filter.get(),
9752 fctx.interp_filter.get(),
9753 dst, fctx,
9754 );
9755 }
9756 let mut blended16 = [0u16; BLOCK * BLOCK];
9757 let blended16 = &mut blended16[..side * side];
9758 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
9759 let mut prediction = [0u8; BLOCK * BLOCK];
9760 let prediction = &mut prediction[..side * side];
9761 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
9762 *dst = src as u8;
9763 }
9764 plane.code_from_prediction_typed(
9765 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
9766 )
9767}
9768
9769/// Codes one 32x32 block of an inter frame as whichever costs least of: each
9770/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
9771/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
9772/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
9773/// coding a real residual (`skip: false`) whenever one prices out cheaper
9774/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
9775/// missing inter `tx_type` symbol (the desync this function's candidates
9776/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
9777/// fixed.
9778///
9779/// The symbol costs this ranks candidates by use fixed contexts (0) for
9780/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
9781/// contexts for those come from its own neighbour bookkeeping
9782/// (`tile::Neighbours`), which is private to that module and not worth
9783/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
9784/// `drl_mode` contexts come straight from `stack`, which is exact, because
9785/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
9786/// the tile writer derives from the same grid state.
9787#[allow(clippy::too_many_arguments)]
9788/// One prediction of `side` x `side` samples from `reference`, as `u8` --
9789/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
9790/// four times the stack scratch that function sizes for [`BLOCK`].
9791fn predict_u8(
9792 reference: &[u16],
9793 stride: usize,
9794 ref_width: usize,
9795 ref_height: usize,
9796 (x, y): (usize, usize),
9797 side: usize,
9798 mv: (i32, i32),
9799 luma: bool,
9800 fctx: &crate::decode::FrameCtx,
9801) -> Vec<u8> {
9802 let mut prediction = vec![0u16; side * side];
9803 mc::predict(
9804 reference,
9805 stride,
9806 ref_width,
9807 ref_height,
9808 mv_to_q4(x, mv.1, luma),
9809 mv_to_q4(y, mv.0, luma),
9810 side,
9811 side,
9812 &mut prediction,
9813 fctx,
9814 );
9815 prediction.iter().map(|&v| v as u8).collect()
9816}
9817
9818/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
9819/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
9820/// references predict into the `CONV_BUF` intermediate domain and are blended
9821/// at the simple-average split `(8, 8)`, the same path (and so the same
9822/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
9823fn predict_compound_u8(
9824 ref0: (&[u16], usize, usize, usize),
9825 ref1: (&[u16], usize, usize, usize),
9826 (x, y): (usize, usize),
9827 side: usize,
9828 (mv0, mv1): ((i32, i32), (i32, i32)),
9829 luma: bool,
9830 fctx: &crate::decode::FrameCtx,
9831) -> Vec<u8> {
9832 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
9833 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
9834 mc::predict_compound_intermediate(
9835 r.0,
9836 r.1,
9837 r.2,
9838 r.3,
9839 mv_to_q4(x, mv.1, luma),
9840 mv_to_q4(y, mv.0, luma),
9841 mc::REF_NO_SCALE,
9842 side,
9843 side,
9844 fctx.interp_filter.get(),
9845 fctx.interp_filter.get(),
9846 dst, fctx,
9847 );
9848 }
9849 let mut blended = vec![0u16; side * side];
9850 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
9851 blended.iter().map(|&v| v as u8).collect()
9852}
9853
9854/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
9855/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
9856/// one motion vector where the four 64x64 roots below spend four of each.
9857///
9858/// SKIP only (`residual: false`): a 128x128 block's residual is four
9859/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
9860/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
9861/// path for -- offering one here would price a block
9862/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
9863/// the same reason: the compound arm at this size is untested against the
9864/// writer's own `write_compound_block` window.
9865///
9866/// Only a root whose whole 128x128 lies inside the true frame AND inside
9867/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
9868/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
9869/// block would have to be ranked over its inside part alone.
9870///
9871/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
9872/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
9873/// against the four superblocks plus the SPLIT symbol.
9874#[allow(clippy::too_many_arguments)]
9875fn search_root_128(
9876 luma: &mut Plane,
9877 chroma: &mut [Plane; 2],
9878 grid: &crate::mvstack::MiGrid,
9879 (root_r, root_c): (usize, usize),
9880 // The 32x32-block grid this tile's `blocks` vector is indexed on.
9881 (rows, cols): (usize, usize),
9882 // The frame's own mode-info grid, which bounds the root.
9883 (mi_cols, mi_rows): (u32, u32),
9884 search: Search<'_>,
9885 tpl_factors: &Option<Vec<f64>>,
9886 sb_q: Option<&Vec<u8>>,
9887 sb_cols: usize,
9888 tpl_cells_x: usize,
9889 base_q_idx: u8,
9890 // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
9891 // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
9892 dq_res: i32,
9893 reference: &Picture,
9894 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
9895 // built by the caller off the same grid the tile writer rebuilds its
9896 // stack from (empty unless the frame carries `reference_select` and
9897 // [`b128_compound`] is on).
9898 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9899 fctx: &crate::decode::FrameCtx,
9900) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
9901 const SIDE: usize = SUPERBLOCK * 2;
9902 const SIDE_MI: usize = SIDE / 4;
9903 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9904 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9905 if root_r * 2 + 3 >= rows
9906 || root_c * 2 + 3 >= cols
9907 || (mi_row + SIDE_MI) as u32 > mi_rows
9908 || (mi_col + SIDE_MI) as u32 > mi_cols
9909 || x128 + SIDE > luma.true_width
9910 || y128 + SIDE > luma.true_height
9911 {
9912 return None;
9913 }
9914 // One lambda for the whole root, the mean of what its four superblocks
9915 // would each be searched at -- the 128-vs-four comparison weighs one cost
9916 // against four, so both sides have to be priced at the same lambda (the
9917 // same rule the 64 root's own mean-of-sixteen tpl cells follows).
9918 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
9919 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
9920 (None, Some(f)) => {
9921 let mean = (0..16)
9922 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
9923 .sum::<f64>()
9924 / 16.0;
9925 search.lambda * mean
9926 }
9927 (None, None) => search.lambda,
9928 };
9929 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
9930 .iter()
9931 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9932 .sum::<f64>()
9933 / 4.0;
9934 // The qindex this root is really quantized at: the delta_q unit is the
9935 // 128 superblock, so the root's own top-left cell is the one coded
9936 // (lane-b128m), and the residual arm below has to quantize at exactly it.
9937 let root_search = Search {
9938 lambda,
9939 ..match sb_q {
9940 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
9941 None => search,
9942 }
9943 };
9944 let stack = find_mv_stack(
9945 grid,
9946 mi_row,
9947 mi_col,
9948 SIDE_MI,
9949 SIDE_MI,
9950 LAST_FRAME,
9951 mi_cols as usize,
9952 mi_rows as usize,
9953 );
9954 let base = snapshot(luma, chroma, (x128, y128), SIDE);
9955 let found = search_skip_64(
9956 luma,
9957 chroma,
9958 (x128, y128),
9959 (SIDE, SIDE),
9960 &root_search,
9961 false,
9962 reference,
9963 &stack,
9964 compound,
9965 fctx,
9966 );
9967 let (mut cost, mut block) = found?;
9968 if block.inter.is_some_and(|i| i.ref1.is_some()) {
9969 B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9970 }
9971 // lane-b128r: the same prediction with a REAL residual, priced against
9972 // the skip arm the search just committed to the planes (which IS the
9973 // winner's prediction, sample for sample). The block's residual is four
9974 // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
9975 // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
9976 // sides the forward network already reaches, never as one 128-point
9977 // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
9978 //
9979 // The four `txfm_partition` symbols the writer codes for them are not
9980 // priced, exactly as the 64 root does not price its own (their contexts
9981 // are only known at write time); at four symbols a root this is under a
9982 // bit against residuals of hundreds.
9983 if b128_residual() && block.skip {
9984 // Every unit's coded level grid is 32x32 (a 64-point transform codes
9985 // only its top-left corner), packed per plane into one 64-wide grid
9986 // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
9987 // `write_inter_block_128` slices back out in the same chunk order.
9988 let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
9989 let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
9990 let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
9991 for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
9992 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9993 let (cx, cy) = (px / 2, py / 2);
9994 let half = SUPERBLOCK / 2;
9995 let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
9996 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
9997 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
9998 sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
9999 + chroma[0].block_sse(cx, cy, half, &pred_u)
10000 + chroma[1].block_sse(cx, cy, half, &pred_v);
10001 let trials = [
10002 luma.code_from_prediction(
10003 px, py, SUPERBLOCK, &pred_y, false, root_search.base_q_idx,
10004 root_search.deadzone, TxbSet::Luma64,
10005 ),
10006 chroma[0].code_from_prediction(
10007 cx, cy, half, &pred_u, false, root_search.base_q_idx,
10008 root_search.deadzone, TxbSet::Chroma32,
10009 ),
10010 chroma[1].code_from_prediction(
10011 cx, cy, half, &pred_v, false, root_search.base_q_idx,
10012 root_search.deadzone, TxbSet::Chroma32,
10013 ),
10014 ];
10015 for (plane, trial) in trials.iter().enumerate() {
10016 sse_res += trial.sse;
10017 coeff_bits += trial.bits;
10018 for row in 0..32 {
10019 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10020 .copy_from_slice(&trial.levels[row * 32..][..32]);
10021 }
10022 }
10023 chunks.push(((cr, cc), trials));
10024 }
10025 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
10026 // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
10027 // coefficients.
10028 let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
10029 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10030 if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
10031 B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10032 for ((cr, cc), trials) in &chunks {
10033 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10034 let half = SUPERBLOCK / 2;
10035 luma.commit(px, py, SUPERBLOCK, &trials[0]);
10036 chroma[0].commit(px / 2, py / 2, half, &trials[1]);
10037 chroma[1].commit(px / 2, py / 2, half, &trials[2]);
10038 }
10039 cost = res_cost;
10040 block.skip = false;
10041 block.tx_depth = 0;
10042 block.luma_tx_types = Vec::new();
10043 block.luma = coeffs(&packed[0], 64);
10044 block.u = coeffs(&packed[1], 64);
10045 block.v = coeffs(&packed[2], 64);
10046 }
10047 }
10048 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10049 restore(luma, chroma, (x128, y128), SIDE, &base);
10050 // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
10051 // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
10052 // residual arm above codes it like every other block does.
10053 let dq = if block.skip {
10054 0.0
10055 } else {
10056 delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
10057 };
10058 Some((
10059 cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
10060 lambda,
10061 block,
10062 after,
10063 ))
10064}
10065
10066/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
10067/// arm the caller's [`search_skip_64`] just committed to the planes (which
10068/// IS the winner's prediction, sample for sample -- the same rule
10069/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
10070/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
10071/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
10072/// each trial at sides the forward network already reaches, never a
10073/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
10074/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
10075///
10076/// The depth-0 `txfm_partition` symbols the writer codes for the units are
10077/// not priced, exactly as [`search_root_128`] does not price its four (their
10078/// contexts are only known at write time); at two symbols a half this is
10079/// under a bit against residuals of hundreds. On a win (or under the witness
10080/// force) the trials are committed to the planes, `block` is flipped to
10081/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
10082/// slices back out, and the new cost is returned; otherwise `cost` passes
10083/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
10084#[allow(clippy::too_many_arguments)]
10085fn search_rect_residual(
10086 luma: &mut Plane,
10087 chroma: &mut [Plane; 2],
10088 // The piece's own top-left, in luma samples.
10089 (px, py): (usize, usize),
10090 // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
10091 (w, h): (usize, usize),
10092 cost: f64,
10093 lambda: f64,
10094 search: &Search<'_>,
10095 // The piece's own mv stack, for the skip symbol's cost either way.
10096 stack: &crate::mvstack::MvStack,
10097 block: &mut BlockCoeffs,
10098) -> f64 {
10099 /// The 64x64 "mu" chunk side, luma; chroma halves it.
10100 const MU: usize = SUPERBLOCK;
10101 let chunks: [(usize, usize); 2] = match (w, h) {
10102 (128, 64) => [(0, 0), (0, 1)],
10103 (64, 128) => [(0, 0), (1, 0)],
10104 _ => [(0, 0), (0, 0)],
10105 };
10106 let n = if w.max(h) > MU { 2 } else { 1 };
10107 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10108 // only its top-left corner), packed per plane into one 64-wide grid with
10109 // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
10110 // back out in the same chunk order.
10111 let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
10112 let mut sse_skip = 0.0f64;
10113 let mut sse_res = 0.0f64;
10114 let mut coeff_bits = 0.0f64;
10115 let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
10116 for &(cr, cc) in &chunks[..n] {
10117 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10118 let (cx, cy) = (cxx / 2, cyy / 2);
10119 let half = MU / 2;
10120 let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
10121 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10122 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10123 sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
10124 + chroma[0].block_sse(cx, cy, half, &pred_u)
10125 + chroma[1].block_sse(cx, cy, half, &pred_v);
10126 let trials = [
10127 luma.code_from_prediction(
10128 cxx, cyy, MU, &pred_y, false, search.base_q_idx, search.deadzone,
10129 TxbSet::Luma64,
10130 ),
10131 chroma[0].code_from_prediction(
10132 cx, cy, half, &pred_u, false, search.base_q_idx, search.deadzone,
10133 TxbSet::Chroma32,
10134 ),
10135 chroma[1].code_from_prediction(
10136 cx, cy, half, &pred_v, false, search.base_q_idx, search.deadzone,
10137 TxbSet::Chroma32,
10138 ),
10139 ];
10140 for (plane, trial) in trials.iter().enumerate() {
10141 sse_res += trial.sse;
10142 coeff_bits += trial.bits;
10143 for row in 0..32 {
10144 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10145 .copy_from_slice(&trial.levels[row * 32..][..32]);
10146 }
10147 }
10148 trials_per_chunk.push(trials);
10149 }
10150 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
10151 // pays the same syntax with `skip` coded 0 instead of 1, plus its
10152 // coefficients.
10153 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10154 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10155 if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
10156 for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
10157 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10158 let (cx, cy) = (cxx / 2, cyy / 2);
10159 let half = MU / 2;
10160 luma.commit(cxx, cyy, MU, &trials[0]);
10161 chroma[0].commit(cx, cy, half, &trials[1]);
10162 chroma[1].commit(cx, cy, half, &trials[2]);
10163 }
10164 block.skip = false;
10165 block.tx_depth = 0;
10166 block.luma_tx_types = Vec::new();
10167 block.luma = coeffs(&packed[0], 64);
10168 block.u = coeffs(&packed[1], 64);
10169 block.v = coeffs(&packed[2], 64);
10170 B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10171 res_cost
10172 } else {
10173 cost
10174 }
10175}
10176
10177/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
10178/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
10179/// shipped NONE machinery halved. Skip-only by default, single reference or
10180/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
10181/// ([`search_rect_residual`]) -- exactly what
10182/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
10183/// reads at `sb128_rect`.
10184///
10185/// The FIRST half is published into `grid` before the second is searched --
10186/// the writer publishes it too, so a second half searched against the stale
10187/// grid would be priced (and its mv predicted) off a stack the decoder never
10188/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
10189/// both planes are put back before returning; the caller re-applies the
10190/// winner.
10191///
10192/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
10193/// carrying the root's own partition symbol so it ranks against
10194/// [`search_root_128`] and against the four superblocks below.
10195#[allow(clippy::too_many_arguments)]
10196fn search_root_128_rect(
10197 luma: &mut Plane,
10198 chroma: &mut [Plane; 2],
10199 grid: &mut crate::mvstack::MiGrid,
10200 (root_r, root_c): (usize, usize),
10201 (rows, cols): (usize, usize),
10202 (mi_cols, mi_rows): (u32, u32),
10203 search: Search<'_>,
10204 tpl_factors: &Option<Vec<f64>>,
10205 sb_q: Option<&Vec<u8>>,
10206 sb_cols: usize,
10207 tpl_cells_x: usize,
10208 base_q_idx: u8,
10209 // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
10210 dq_res: i32,
10211 reference: &Picture,
10212 // The `LAST` + extra-reference pairs offered at this root; only the
10213 // reference and its picture are read here, since each HALF derives its
10214 // own compound stack at its own rectangular window.
10215 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10216 horz: bool,
10217 fctx: &crate::decode::FrameCtx,
10218) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10219 const SIDE: usize = SUPERBLOCK * 2;
10220 const SIDE_MI: usize = SIDE / 4;
10221 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10222 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10223 if root_r * 2 + 3 >= rows
10224 || root_c * 2 + 3 >= cols
10225 || (mi_row + SIDE_MI) as u32 > mi_rows
10226 || (mi_col + SIDE_MI) as u32 > mi_cols
10227 || x128 + SIDE > luma.true_width
10228 || y128 + SIDE > luma.true_height
10229 {
10230 return None;
10231 }
10232 // The root's own lambda, the mean of its four superblocks' -- the same
10233 // one [`search_root_128`] prices with, so the three root candidates and
10234 // the four-superblock arm are all comparable.
10235 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10236 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10237 (None, Some(f)) => {
10238 let mean = (0..16)
10239 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10240 .sum::<f64>()
10241 / 16.0;
10242 search.lambda * mean
10243 }
10244 (None, None) => search.lambda,
10245 };
10246 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10247 .iter()
10248 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10249 .sum::<f64>()
10250 / 4.0;
10251 let root_search = Search {
10252 lambda,
10253 ..match sb_q {
10254 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10255 None => search,
10256 }
10257 };
10258 let (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) };
10259 let (w_mi, h_mi) = (w / 4, h / 4);
10260 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10261 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10262 let mut cost = 0.0f64;
10263 let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
10264 for i in 0..2usize {
10265 let (mr, mc) = if horz {
10266 (mi_row + i * 16, mi_col)
10267 } else {
10268 (mi_row, mi_col + i * 16)
10269 };
10270 let stack = find_mv_stack(
10271 grid,
10272 mr,
10273 mc,
10274 w_mi,
10275 h_mi,
10276 LAST_FRAME,
10277 mi_cols as usize,
10278 mi_rows as usize,
10279 );
10280 let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10281 .iter()
10282 .map(|&(r, pic, _)| {
10283 (
10284 r,
10285 pic,
10286 crate::mvstack::find_mv_stack_compound(
10287 grid,
10288 mr,
10289 mc,
10290 w_mi,
10291 h_mi,
10292 (LAST_FRAME, r),
10293 mi_cols as usize,
10294 mi_rows as usize,
10295 grid.sign_bias_table(),
10296 &[(0, 0); 7],
10297 None,
10298 ),
10299 )
10300 })
10301 .collect();
10302 let found = search_skip_64(
10303 luma,
10304 chroma,
10305 (mc * 4, mr * 4),
10306 (w, h),
10307 &root_search,
10308 false,
10309 reference,
10310 &stack,
10311 &half_compound,
10312 fctx,
10313 );
10314 match found {
10315 Some((mut c, mut block)) => {
10316 // lane-rectres: the same prediction with a REAL residual,
10317 // priced against the skip arm the search just committed to
10318 // the planes -- two 64x64 mu chunks for a half.
10319 if rectres() && block.skip {
10320 c = search_rect_residual(
10321 luma,
10322 chroma,
10323 (mc * 4, mr * 4),
10324 (w, h),
10325 c,
10326 root_search.lambda,
10327 &root_search,
10328 &stack,
10329 &mut block,
10330 );
10331 }
10332 cost += c;
10333 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10334 halves.push(block);
10335 }
10336 None => {
10337 restore(luma, chroma, (x128, y128), SIDE, &base);
10338 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10339 return None;
10340 }
10341 }
10342 }
10343 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10344 restore(luma, chroma, (x128, y128), SIDE, &base);
10345 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10346 let symbol = if horz { 1 } else { 2 };
10347 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
10348 // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
10349 // codes the delta_q group whether it is skipped or not
10350 // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
10351 // half is at a non-origin mi and codes none.
10352 let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
10353 Some((
10354 cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
10355 lambda,
10356 [b0, b1],
10357 after,
10358 ))
10359}
10360
10361/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
10362/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
10363/// decoder's own). Each piece is priced through the same `search_skip_64`
10364/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
10365/// into `grid` before the next is searched -- the writer publishes it too, so
10366/// a later piece searched against a stale grid would be priced (and its mv
10367/// predicted) off a stack the decoder never derives (class
10368/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
10369/// are put back before returning; the caller re-applies the winner.
10370///
10371/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
10372/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
10373/// libaom's own AB shapes earn their keep.
10374///
10375/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
10376/// already carrying the root's own partition symbol so it ranks against the
10377/// other root candidates and against the four superblocks below.
10378#[allow(clippy::too_many_arguments)]
10379fn search_root_128_ab(
10380 luma: &mut Plane,
10381 chroma: &mut [Plane; 2],
10382 grid: &mut crate::mvstack::MiGrid,
10383 (root_r, root_c): (usize, usize),
10384 (rows, cols): (usize, usize),
10385 (mi_cols, mi_rows): (u32, u32),
10386 search: Search<'_>,
10387 tpl_factors: &Option<Vec<f64>>,
10388 sb_q: Option<&Vec<u8>>,
10389 sb_cols: usize,
10390 tpl_cells_x: usize,
10391 base_q_idx: u8,
10392 reference: &Picture,
10393 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10394 // The partition symbol, 4..=7.
10395 symbol: usize,
10396 fctx: &crate::decode::FrameCtx,
10397) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10398 const SIDE: usize = SUPERBLOCK * 2;
10399 const SIDE_MI: usize = SIDE / 4;
10400 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10401 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10402 if root_r * 2 + 3 >= rows
10403 || root_c * 2 + 3 >= cols
10404 || (mi_row + SIDE_MI) as u32 > mi_rows
10405 || (mi_col + SIDE_MI) as u32 > mi_cols
10406 || x128 + SIDE > luma.true_width
10407 || y128 + SIDE > luma.true_height
10408 {
10409 return None;
10410 }
10411 // The root's own lambda, the mean of its four superblocks' -- the same one
10412 // [`search_root_128`] prices with, so every root candidate and the
10413 // four-superblock arm are comparable.
10414 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10415 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10416 (None, Some(f)) => {
10417 let mean = (0..16)
10418 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10419 .sum::<f64>()
10420 / 16.0;
10421 search.lambda * mean
10422 }
10423 (None, None) => search.lambda,
10424 };
10425 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10426 .iter()
10427 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10428 .sum::<f64>()
10429 / 4.0;
10430 let root_search = Search {
10431 lambda,
10432 ..match sb_q {
10433 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10434 None => search,
10435 }
10436 };
10437 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10438 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10439 let mut cost = 0.0f64;
10440 let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
10441 for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
10442 let (w_mi, h_mi) = (w / 4, h / 4);
10443 let stack = find_mv_stack(
10444 grid,
10445 mr,
10446 mc,
10447 w_mi,
10448 h_mi,
10449 LAST_FRAME,
10450 mi_cols as usize,
10451 mi_rows as usize,
10452 );
10453 let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10454 .iter()
10455 .map(|&(r, pic, _)| {
10456 (
10457 r,
10458 pic,
10459 crate::mvstack::find_mv_stack_compound(
10460 grid,
10461 mr,
10462 mc,
10463 w_mi,
10464 h_mi,
10465 (LAST_FRAME, r),
10466 mi_cols as usize,
10467 mi_rows as usize,
10468 grid.sign_bias_table(),
10469 &[(0, 0); 7],
10470 None,
10471 ),
10472 )
10473 })
10474 .collect();
10475 let found = search_skip_64(
10476 luma,
10477 chroma,
10478 (mc * 4, mr * 4),
10479 (w, h),
10480 &root_search,
10481 false,
10482 reference,
10483 &stack,
10484 &piece_compound,
10485 fctx,
10486 );
10487 match found {
10488 Some((mut c, mut block)) => {
10489 // lane-rectres: the same prediction with a REAL residual,
10490 // priced against the skip arm the search just committed to
10491 // the planes -- one mu chunk for a 64x64 square, two for a
10492 // half. The 64x64 squares are where libaom's own AB shapes
10493 // earn their keep.
10494 if rectres() && block.skip {
10495 c = search_rect_residual(
10496 luma,
10497 chroma,
10498 (mc * 4, mr * 4),
10499 (w, h),
10500 c,
10501 root_search.lambda,
10502 &root_search,
10503 &stack,
10504 &mut block,
10505 );
10506 }
10507 cost += c;
10508 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10509 pieces.push(block);
10510 }
10511 None => {
10512 restore(luma, chroma, (x128, y128), SIDE, &base);
10513 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10514 return None;
10515 }
10516 }
10517 }
10518 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10519 restore(luma, chroma, (x128, y128), SIDE, &base);
10520 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10521 let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
10522 Some((
10523 cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
10524 lambda,
10525 [b0, b1, b2],
10526 after,
10527 ))
10528}
10529
10530/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
10531/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
10532/// SKIP, priced through the same `symbol_bits` path every other candidate
10533/// uses. The winner's prediction is committed to the planes (it IS the
10534/// reconstruction -- a skip block has no residual); the caller restores them
10535/// if the four quadrants come out cheaper.
10536///
10537/// `None` when no candidate could be coded at all (a `NEWMV` residual the
10538/// writer cannot name is simply not offered, and the other modes always are,
10539/// so this only happens if every candidate is refused).
10540fn search_skip_64(
10541 luma: &mut Plane,
10542 chroma: &mut [Plane; 2],
10543 (x, y): (usize, usize),
10544 // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
10545 // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
10546 // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
10547 // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
10548 // side (one square when it is square, two otherwise), and the residual
10549 // arm is only ever asked for at 64 -- a 128 block's residual is four
10550 // TX_64X64 units the writer has no path for.
10551 (bw, bh): (usize, usize),
10552 search: &Search,
10553 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
10554 // screen content -- see that function's doc).
10555 residual: bool,
10556 reference: &Picture,
10557 stack: &MvStack,
10558 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
10559 // superblock's 16x16-mi window, built off the same grid the tile writer
10560 // rebuilds it from (empty unless the frame carries `reference_select`).
10561 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10562 fctx: &crate::decode::FrameCtx,
10563) -> Option<(f64, BlockCoeffs)> {
10564 debug_assert!(
10565 (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
10566 "only a 64 root has a residual arm"
10567 );
10568 // The square units every trial below is taken on: the block itself when
10569 // it is square, its two halves otherwise. Luma first (in raster order),
10570 // then each chroma plane over the same tiling at half the side -- which is
10571 // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
10572 let sq = bw.min(bh);
10573 let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
10574 .flat_map(|plane| {
10575 let (ox, oy, s) = if plane == 0 { (x, y, sq) } else { (x / 2, y / 2, sq / 2) };
10576 (0..bh / sq).flat_map(move |j| {
10577 (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
10578 })
10579 })
10580 .collect();
10581 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
10582 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
10583 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
10584 // What every candidate pays whatever its vector: `skip` coded 1, then
10585 // `is_inter` coded 1, then the LAST chain above.
10586 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
10587 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
10588 ref1: None,
10589 mv1: (0, 0),
10590 ref_frame: crate::mvstack::LAST_FRAME,
10591 mode,
10592 mv,
10593 ref_mv_idx,
10594 };
10595 let mut cands: Vec<(f64, InterInfo)> = vec![
10596 (
10597 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
10598 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
10599 ),
10600 (
10601 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
10602 info_of(InterMode::GlobalMv, (0, 0), 0),
10603 ),
10604 ];
10605 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
10606 for idx in 1..=2usize {
10607 if let Some(e) = stack.entries.get(idx) {
10608 cands.push((
10609 near_bits + drl_bits_for(stack, 1, idx),
10610 info_of(InterMode::NearMv, e.mv, idx as u8),
10611 ));
10612 }
10613 }
10614 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
10615 // candidate below to pair with the second reference's NEAREST half.
10616 let mut last_new_mv: Option<(i32, i32)> = None;
10617 if leaf_new_mv() {
10618 let source_block = luma.source_block_rect(x, y, bw, bh);
10619 let (seeds, seed_n) = mv_seeds(stack);
10620 let found = motion::search(
10621 &reference.y,
10622 reference.width,
10623 luma.true_width,
10624 luma.true_height,
10625 &source_block,
10626 x,
10627 y,
10628 bw,
10629 bh,
10630 stack.pred_mv,
10631 &seeds[..seed_n],
10632 search.lambda,
10633 fctx,
10634 1,
10635 );
10636 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
10637 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
10638 last_new_mv = Some(mv);
10639 cands.push((
10640 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
10641 info_of(InterMode::NewMv, mv, ref_mv_idx),
10642 ));
10643 }
10644 }
10645
10646 let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
10647 for (bits, info) in cands {
10648 let trials: Vec<Trial> = units
10649 .iter()
10650 .map(|&(plane, px, py, s, is_luma)| {
10651 let (samples, stride, w, h) = match plane {
10652 0 => (&reference.y, reference.width, luma.true_width, luma.true_height),
10653 1 => (
10654 &reference.u,
10655 reference.width / 2,
10656 chroma[0].true_width,
10657 chroma[0].true_height,
10658 ),
10659 _ => (
10660 &reference.v,
10661 reference.width / 2,
10662 chroma[1].true_width,
10663 chroma[1].true_height,
10664 ),
10665 };
10666 let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
10667 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
10668 // `skip` true: the trial is the prediction itself plus its SSE,
10669 // so no transform of any size is involved (the reason a 64x64
10670 // root can be coded at all before a forward TX_64X64 exists).
10671 target.code_from_prediction(
10672 px,
10673 py,
10674 s,
10675 &prediction,
10676 true,
10677 search.base_q_idx,
10678 search.deadzone,
10679 TxbSet::Luma32Inter,
10680 )
10681 })
10682 .collect();
10683 let cost =
10684 trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
10685 if best.as_ref().is_none_or(|b| cost < b.0) {
10686 best = Some((cost, fixed + bits, info, trials));
10687 }
10688 }
10689
10690 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
10691 // superblock can form without a second motion search ([`b64_compound`]),
10692 // priced through the same `symbol_bits` path -- `fixed` minus the single
10693 // reference's tree, plus the pair tree and the compound mode.
10694 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
10695 let (ref1, g) = (*ref1, *g);
10696 // The whole `comp_mode` + reference-pair tree at the writer's own
10697 // contexts, for THIS pair (lane-ctx).
10698 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
10699 let mode_ctx =
10700 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
10701 let mode_bits_of =
10702 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
10703 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
10704 ref1: Some(ref1),
10705 mv1: mvs.1,
10706 ref_frame: crate::mvstack::LAST_FRAME,
10707 mode,
10708 mv: mvs.0,
10709 ref_mv_idx: 0,
10710 };
10711 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
10712 (
10713 cstack.nearest_mv,
10714 mode_bits_of(0),
10715 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
10716 ),
10717 (
10718 ((0, 0), (0, 0)),
10719 mode_bits_of(6),
10720 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
10721 ),
10722 ];
10723 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
10724 // above, its residual priced against compound stack entry 0 -- what
10725 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
10726 let cbase = cstack
10727 .entries
10728 .first()
10729 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
10730 if let Some(new_mv) = last_new_mv
10731 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
10732 {
10733 let mvs = (new_mv, cstack.nearest_mv.1);
10734 ccands.push((
10735 mvs,
10736 mode_bits_of(3) + b0,
10737 compound_info(InterMode::NewNearestMv, mvs),
10738 ));
10739 }
10740 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
10741 ccands.dedup_by_key(|c| c.0);
10742 for (mvs, bits, info) in ccands {
10743 let trials: Vec<Trial> = units
10744 .iter()
10745 .map(|&(plane, px, py, s, is_luma)| {
10746 let (r0, r1) = match plane {
10747 0 => (
10748 (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height),
10749 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10750 ),
10751 1 => (
10752 (
10753 reference.u.as_slice(),
10754 reference.width / 2,
10755 chroma[0].true_width,
10756 chroma[0].true_height,
10757 ),
10758 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
10759 ),
10760 _ => (
10761 (
10762 reference.v.as_slice(),
10763 reference.width / 2,
10764 chroma[1].true_width,
10765 chroma[1].true_height,
10766 ),
10767 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
10768 ),
10769 };
10770 let prediction =
10771 predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
10772 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
10773 target.code_from_prediction(
10774 px,
10775 py,
10776 s,
10777 &prediction,
10778 true,
10779 search.base_q_idx,
10780 search.deadzone,
10781 TxbSet::Luma32Inter,
10782 )
10783 })
10784 .collect();
10785 let syntax = fixed - ref_bits + bits;
10786 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
10787 if best.as_ref().is_none_or(|b| cost < b.0) {
10788 best = Some((cost, syntax, info, trials));
10789 }
10790 }
10791 }
10792
10793 let (skip_cost, syntax, info, skip_trials) = best?;
10794
10795 // The winner's prediction coded with a REAL residual (lane-tx64): one
10796 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
10797 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
10798 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
10799 // the skip arm already chose is re-coded: the prediction with the lowest
10800 // SSE is also the cheapest residual to code, and a second 64x64 motion
10801 // search per superblock is the wall this root was taken to SAVE.
10802 //
10803 // Priced against the skip arm through the same `symbol_bits` path, so the
10804 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
10805 // arm charges 0 instead and adds its three planes' coefficient bits.
10806 let mut chosen = (skip_cost, true, skip_trials);
10807 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
10808 // into the plane, so the tail below does not commit over its units.
10809 let mut luma_committed = false;
10810 // The residual arm's luma levels and the `txfm_split` depth the writer
10811 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
10812 // four TX_32X32 units in 64x64 ones.
10813 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
10814 if residual {
10815 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
10816 // Square by construction (the `debug_assert` above), so `units` is
10817 // one entry per plane and `chosen.2[plane]` is that plane's trial.
10818 let residual_trials = [0usize, 1, 2].map(|plane| {
10819 let (target, px, py, s) = if plane == 0 {
10820 (&*luma, x, y, bw)
10821 } else {
10822 (&chroma[plane - 1], x / 2, y / 2, bw / 2)
10823 };
10824 target.code_from_prediction(
10825 px,
10826 py,
10827 s,
10828 &chosen.2[plane].reconstruction,
10829 false,
10830 search.base_q_idx,
10831 search.deadzone,
10832 sets[plane],
10833 )
10834 });
10835 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10836 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
10837 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
10838 // four TX_32X32 units of `txfm_split = 1`, taken by the same
10839 // `commit_inter_luma` every other inter block's is (it commits the
10840 // winner and hands back the cost it took off the flat arm).
10841 let (levels, depth, gain, tx_types) = if b64_var_tx() {
10842 let second = info.ref1.and_then(|r1| {
10843 compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| {
10844 (
10845 info.mv1,
10846 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10847 )
10848 })
10849 });
10850 luma_committed = true;
10851 commit_inter_luma(
10852 luma,
10853 (x, y),
10854 bw,
10855 info.mv,
10856 (&reference.y, reference.width, luma.true_width, luma.true_height),
10857 search,
10858 &residual_trials[0],
10859 false,
10860 second,
10861 fctx,
10862 )
10863 } else {
10864 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
10865 };
10866 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
10867 + search.lambda * (syntax + unskip + coeff_bits)
10868 + gain;
10869 if cost < skip_cost {
10870 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10871 if depth == 1 {
10872 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10873 }
10874 luma_levels = Some((levels, depth, tx_types));
10875 chosen = (cost, false, residual_trials.to_vec());
10876 }
10877 }
10878
10879 let (cost, skip, trials) = chosen;
10880 // `commit_inter_luma` already wrote the residual arm's luma (its four
10881 // split units are not one 64-sided trial); a skip winner overwrites it.
10882 for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
10883 match plane {
10884 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
10885 0 => {}
10886 _ => chroma[plane - 1].commit(px, py, s, trial),
10887 }
10888 }
10889 Some((
10890 cost,
10891 BlockCoeffs {
10892 skip,
10893 inter: Some(info),
10894 // The chroma grids are whole TX_32X32; the luma one is the
10895 // 64-point transform's coded 32x32 corner at depth 0 and the
10896 // whole 64-sided block at depth 1 (lane-b64b).
10897 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
10898 luma_tx_types: match (skip, &luma_levels) {
10899 (false, Some((_, _, types))) => types.clone(),
10900 _ => Vec::new(),
10901 },
10902 luma: match (skip, &luma_levels) {
10903 (true, _) => Vec::new(),
10904 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
10905 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
10906 (false, None) => coeffs(&trials[0].levels, BLOCK),
10907 },
10908 u: if skip { Vec::new() } else { coeffs(&trials[1].levels, bw / 2) },
10909 v: if skip { Vec::new() } else { coeffs(&trials[2].levels, bw / 2) },
10910 ..BlockCoeffs::default()
10911 },
10912 ))
10913}
10914
10915fn search_inter_block(
10916 luma: &mut Plane,
10917 chroma: &mut [Plane; 2],
10918 (x, y): (usize, usize),
10919 search: &Search,
10920 mode_bits: &[f64; 13],
10921 reference: &Picture,
10922 stack: &MvStack,
10923 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
10924 // for the whole GOP, with the stack this block derives against it. Only
10925 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
10926 // second motion search would double the wall of the stage that already
10927 // owns most of it.
10928 extra: &[(i8, &Picture, &MvStack)],
10929 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
10930 // the caller off the same MI grid the tile writer will (empty unless the
10931 // frame carries `reference_select`).
10932 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10933 // lane-av1obmc: the mi grid this search's neighbours were published into
10934 // (`record_mi`) and this block's own place in it -- what the OBMC
10935 // candidate's eligibility walk and neighbour plan read, the same state
10936 // the tile writer will read when it codes the `motion_mode` symbol.
10937 grid: &MiGrid,
10938 (mi_row, mi_col): (usize, usize),
10939 (mi_rows, mi_cols): (usize, usize),
10940 fctx: &crate::decode::FrameCtx,
10941) -> (BlockCoeffs, f64) {
10942 // `luma_set` is the INTRA candidates' table; the two inter candidates
10943 // below price their coefficients through `TxbSet::Luma32Inter`, which is
10944 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
10945 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
10946 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
10947 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
10948
10949 // skip / intra_inter symbol costs at a fixed context -- see this
10950 // function's doc comment.
10951 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
10952 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
10953
10954 struct Candidate {
10955 cost: f64,
10956 luma: Trial,
10957 u: Trial,
10958 v: Trial,
10959 mode: u8,
10960 skip: bool,
10961 inter: Option<InterInfo>,
10962 /// The mode/mv syntax this candidate pays for, apart from its
10963 /// residual -- what the OBMC candidate below has to re-pay when it
10964 /// re-prices the winner's prediction.
10965 mode_bits: f64,
10966 }
10967 let mut best: Option<Candidate> = None;
10968 let mut consider = |candidate: Candidate| {
10969 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
10970 best = Some(candidate);
10971 }
10972 };
10973
10974 // The chroma trial an intra candidate prices does not depend on `mode`
10975 // at all -- both planes always code `DC_PRED` here (a coding choice this
10976 // search inherited, not this loop's to second-guess) at the same `reach:
10977 // Reach::none()` -- so it is the same call with the same inputs on every
10978 // one of the thirteen iterations below; run it once and reuse the result
10979 // rather than repeat an already-priced transform/quantize/entropy call
10980 // twelve times for nothing (bit-identical: the value each iteration
10981 // reads back is exactly what it used to recompute).
10982 let u_trial = chroma[0].trial(
10983 At {
10984 x: x / 2,
10985 y: y / 2,
10986 side: BLOCK / 2,
10987 reach: Reach::none(),
10988 set: chroma_set,
10989 },
10990 DC_PRED,
10991 0,
10992 search.base_q_idx,
10993 search.deadzone, fctx,
10994 );
10995 let v_trial = chroma[1].trial(
10996 At {
10997 x: x / 2,
10998 y: y / 2,
10999 side: BLOCK / 2,
11000 reach: Reach::none(),
11001 set: chroma_set,
11002 },
11003 DC_PRED,
11004 0,
11005 search.base_q_idx,
11006 search.deadzone, fctx,
11007 );
11008
11009 let intra_modes: Vec<u8> = match search.top_k {
11010 Some(k) if k < search.modes.len() => {
11011 let scored = luma.intra_scores(
11012 At {
11013 x,
11014 y,
11015 side: BLOCK,
11016 reach,
11017 set: luma_set,
11018 },
11019 search.modes,
11020 mode_bits,
11021 search.lambda, fctx,
11022 );
11023 prune_by_sad(search.modes, scored, k)
11024 }
11025 _ => search.modes.to_vec(),
11026 };
11027 census_add(5, 1);
11028 census_add(6, if search.arf_leaf_intra { intra_modes.len() } else { 0 });
11029 // lane-arfmode: arm 1 drops the whole-32 block's intra candidates at the
11030 // top ARF too -- the probe proved the ARF's intra AREA lives HERE, not at
11031 // the leaves (film A arm 1 vs control byte-identical with the leaf gate
11032 // alone), so "the 32x32 whole keeps intra as the scene-cut hatch" was a
11033 // hatch nothing else was using. Counted once per block.
11034 if search.arf_leaf_intra {
11035 for &mode in &intra_modes {
11036 let luma_trial = luma.trial(
11037 At {
11038 x,
11039 y,
11040 side: BLOCK,
11041 reach,
11042 set: luma_set,
11043 },
11044 mode,
11045 0,
11046 search.base_q_idx,
11047 search.deadzone, fctx,
11048 );
11049 let u = u_trial.clone();
11050 let v = v_trial.clone();
11051 let cost = luma_trial.sse
11052 + u.sse
11053 + v.sse
11054 + search.lambda
11055 * (luma_trial.bits
11056 + u.bits
11057 + v.bits
11058 + mode_bits[usize::from(mode)]
11059 + skip_bits(false)
11060 + intra_inter_bits(false));
11061 consider(Candidate {
11062 cost,
11063 luma: luma_trial,
11064 u,
11065 v,
11066 mode,
11067 skip: false,
11068 inter: None,
11069 mode_bits: mode_bits[usize::from(mode)],
11070 });
11071 }
11072 } else {
11073 arfmode_hit(0);
11074 }
11075
11076 // The reference frame buffer a spec decoder holds is exactly the true
11077 // (unpadded) coded extent -- a superblock whose partition stops early at
11078 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
11079 // beyond it, so those samples are never part of the decoded picture.
11080 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
11081 // reference sample position clamp), not to this crate's own
11082 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
11083 // here would let a fractional-pel read past the true edge pick up this
11084 // encoder's own uncoded padding instead of the true edge's replicated
11085 // value a decoder computes.
11086 let ref_luma = (
11087 &reference.y,
11088 reference.width,
11089 luma.true_width,
11090 luma.true_height,
11091 );
11092 let ref_u = (
11093 &reference.u,
11094 reference.width / 2,
11095 chroma[0].true_width,
11096 chroma[0].true_height,
11097 );
11098 let ref_v = (
11099 &reference.v,
11100 reference.width / 2,
11101 chroma[1].true_width,
11102 chroma[1].true_height,
11103 );
11104 // Every single-reference mode the writer can code (spec 5.11.24's symbol
11105 // chain, mirrored by `tile::write_inter_mode`), priced with the static
11106 // CDFs at this block's own stack contexts. A candidate is a motion
11107 // vector plus the cheapest syntax that reaches it, so two modes landing
11108 // on the same vector share one set of trials: the added modes cost
11109 // mode-bit arithmetic, not another motion compensation.
11110 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11111 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11112 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
11113 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
11114 // the loop cannot reach is never offered below -- every candidate's
11115 // index is one this same loop walks to.
11116 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
11117 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11118 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
11119 (
11120 stack.nearest_mv,
11121 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11122 InterInfo {
11123 ref1: None,
11124 mv1: (0, 0),
11125 ref_frame: crate::mvstack::LAST_FRAME,
11126 mode: InterMode::NearestMv,
11127 mv: stack.nearest_mv,
11128 ref_mv_idx: 0,
11129 },
11130 ),
11131 // GLOBALMV is the identity model's zero vector -- this encoder writes
11132 // no `gm_params` -- and the cheapest syntax of the four on the static
11133 // content where that vector is also the right one.
11134 (
11135 (0, 0),
11136 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11137 InterInfo {
11138 ref1: None,
11139 mv1: (0, 0),
11140 ref_frame: crate::mvstack::LAST_FRAME,
11141 mode: InterMode::GlobalMv,
11142 mv: (0, 0),
11143 ref_mv_idx: 0,
11144 },
11145 ),
11146 ];
11147 let near_bits =
11148 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11149 for idx in 1..=2usize {
11150 if let Some(e) = stack.entries.get(idx) {
11151 cands.push((
11152 e.mv,
11153 near_bits + drl_bits(1, idx),
11154 InterInfo {
11155 ref1: None,
11156 mv1: (0, 0),
11157 ref_frame: crate::mvstack::LAST_FRAME,
11158 mode: InterMode::NearMv,
11159 mv: e.mv,
11160 ref_mv_idx: idx as u8,
11161 },
11162 ));
11163 }
11164 }
11165
11166 let source_block = luma.source_block(x, y, BLOCK);
11167 let (seeds, seed_n) = mv_seeds(stack);
11168 #[cfg(test)]
11169 let t = stage_start();
11170 let found = motion::search(
11171 ref_luma.0,
11172 ref_luma.1,
11173 ref_luma.2,
11174 ref_luma.3,
11175 &source_block,
11176 x,
11177 y,
11178 BLOCK,
11179 BLOCK,
11180 stack.pred_mv,
11181 &seeds[..seed_n],
11182 search.lambda, fctx,
11183 1,
11184 );
11185 #[cfg(test)]
11186 stage_since(0, t);
11187 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
11188 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
11189 // costs, for the census below (`None` when the writer cannot name it).
11190 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
11191 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
11192 // the same vector costs a different residual from each: take the index
11193 // whose residual plus DRL bits is cheapest, not entry 0 by default.
11194 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
11195 newmv_syntax = Some((mv, bits));
11196 cands.push((
11197 mv,
11198 last_ref_bits
11199 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
11200 + bits
11201 + mv_rate_surcharge(bits),
11202 InterInfo {
11203 ref1: None,
11204 mv1: (0, 0),
11205 ref_frame: crate::mvstack::LAST_FRAME,
11206 mode: InterMode::NewMv,
11207 mv,
11208 ref_mv_idx,
11209 },
11210 ));
11211 }
11212
11213 // Each extra reference's own `NEWMV` vector, for the compound
11214 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
11215 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
11216 for &(ref_frame, g, gstack) in extra {
11217 let g_ref_bits = single_ref_bits(ref_frame, gstack);
11218 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
11219 cands.push((
11220 gstack.nearest_mv,
11221 g_ref_bits
11222 + g_not_new
11223 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
11224 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
11225 InterInfo {
11226 ref1: None,
11227 mv1: (0, 0),
11228 ref_frame,
11229 mode: InterMode::NearestMv,
11230 mv: gstack.nearest_mv,
11231 ref_mv_idx: 0,
11232 },
11233 ));
11234 cands.push((
11235 (0, 0),
11236 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
11237 InterInfo {
11238 ref1: None,
11239 mv1: (0, 0),
11240 ref_frame,
11241 mode: InterMode::GlobalMv,
11242 mv: (0, 0),
11243 ref_mv_idx: 0,
11244 },
11245 ));
11246 // A motion search of this reference's own: without it, GOLDEN/ALTREF
11247 // can only be coded at a vector some neighbour already found, which
11248 // is why they carried a third of the inter blocks at their two
11249 // search-free modes alone.
11250 // The search is skipped when this reference's own NEARESTMV already
11251 // prices out `margin` times better than LAST's best vector does --
11252 // one candidate evaluation (`motion::cost_at`) standing in for a
11253 // whole search of ~50.
11254 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
11255 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
11256 // neighbour already found, which is how GOLDEN/ALTREF were offered
11257 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
11258 // own value from the second motion search's wall.
11259 let searched = extra_ref_new_mv()
11260 && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
11261 let margin = extra_new_skip_margin();
11262 if searched {
11263 newmv_census_global(0);
11264 }
11265 let skip_search = searched
11266 && margin > 0.0
11267 && motion::cost_at(
11268 &g.y,
11269 g.width,
11270 luma.true_width,
11271 luma.true_height,
11272 &source_block,
11273 x,
11274 y,
11275 BLOCK,
11276 BLOCK,
11277 gstack.nearest_mv,
11278 gstack.pred_mv,
11279 search.lambda,
11280 fctx,
11281 ) * margin
11282 <= found.cost;
11283 if skip_search {
11284 newmv_census_global(1);
11285 }
11286 if searched && !skip_search {
11287 let (gseeds, gn) = mv_seeds(gstack);
11288 #[cfg(test)]
11289 let t = stage_start();
11290 let gfound = motion::search(
11291 &g.y,
11292 g.width,
11293 luma.true_width,
11294 luma.true_height,
11295 &source_block,
11296 x,
11297 y,
11298 BLOCK,
11299 BLOCK,
11300 gstack.pred_mv,
11301 &gseeds[..gn],
11302 search.lambda, fctx,
11303 ref_distance(ref_frame),
11304 );
11305 #[cfg(test)]
11306 stage_since(0, t);
11307 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
11308 extra_new_mvs.push((ref_frame, gmv));
11309 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
11310 cands.push((
11311 gmv,
11312 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
11313 InterInfo {
11314 ref1: None,
11315 mv1: (0, 0),
11316 ref_frame,
11317 mode: InterMode::NewMv,
11318 mv: gmv,
11319 ref_mv_idx,
11320 },
11321 ));
11322 }
11323 }
11324 }
11325
11326 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
11327 // trial set each: both references predict the block and the two
11328 // predictions are averaged, which is what pays on content where neither
11329 // reference alone is right. Priced with the same static-CDF approximation
11330 // the single-reference candidates use, plus the compound-only symbols
11331 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
11332 // The two compound-mode arms, each measured alone on the BD gate before
11333 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
11334 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
11335 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
11336 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
11337 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
11338 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
11339 // the keep rule. Still behind the knob.
11340 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
11341 let half_new = true;
11342 for (ref1, g, cstack) in compound {
11343 let (ref1, g) = (*ref1, *g);
11344 // The whole `comp_mode` + reference-pair tree at the writer's own
11345 // contexts, for THIS pair (lane-ctx).
11346 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
11347 let mode_ctx =
11348 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
11349 let mode_bits_of =
11350 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
11351 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
11352 (
11353 cstack.nearest_mv,
11354 mode_bits_of(0),
11355 InterInfo {
11356 ref_frame: crate::mvstack::LAST_FRAME,
11357 mode: InterMode::NearestNearestMv,
11358 mv: cstack.nearest_mv.0,
11359 mv1: cstack.nearest_mv.1,
11360 ref1: Some(ref1),
11361 ref_mv_idx: 0,
11362 },
11363 ),
11364 (
11365 ((0, 0), (0, 0)),
11366 mode_bits_of(6),
11367 InterInfo {
11368 ref_frame: crate::mvstack::LAST_FRAME,
11369 mode: InterMode::GlobalGlobalMv,
11370 mv: (0, 0),
11371 mv1: (0, 0),
11372 ref1: Some(ref1),
11373 ref_mv_idx: 0,
11374 },
11375 ),
11376 ];
11377 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
11378 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
11379 // the stack is deep enough for that walk to read one.
11380 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
11381 let drl = if cstack.entries.len() > 2 {
11382 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
11383 } else {
11384 0.0
11385 };
11386 ccands.push((
11387 (e.mv0, e.mv1),
11388 mode_bits_of(1) + drl,
11389 InterInfo {
11390 ref_frame: crate::mvstack::LAST_FRAME,
11391 mode: InterMode::NearNearMv,
11392 mv: e.mv0,
11393 mv1: e.mv1,
11394 ref1: Some(ref1),
11395 ref_mv_idx: 0,
11396 },
11397 ));
11398 }
11399 // The half-new modes and `NEW_NEWMV`, all seeded from the two
11400 // single-reference searches this block already ran -- no joint search
11401 // of its own. Every residual is priced against stack entry 0, which
11402 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
11403 let cbase = cstack
11404 .entries
11405 .first()
11406 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
11407 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
11408 ccands.push((
11409 (mv, cstack.nearest_mv.1),
11410 mode_bits_of(3) + b0,
11411 InterInfo {
11412 ref_frame: crate::mvstack::LAST_FRAME,
11413 mode: InterMode::NewNearestMv,
11414 mv,
11415 mv1: cstack.nearest_mv.1,
11416 ref1: Some(ref1),
11417 ref_mv_idx: 0,
11418 },
11419 ));
11420 }
11421 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
11422 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
11423 ccands.push((
11424 (cstack.nearest_mv.0, mv1),
11425 mode_bits_of(2) + b1,
11426 InterInfo {
11427 ref_frame: crate::mvstack::LAST_FRAME,
11428 mode: InterMode::NearestNewMv,
11429 mv: cstack.nearest_mv.0,
11430 mv1,
11431 ref1: Some(ref1),
11432 ref_mv_idx: 0,
11433 },
11434 ));
11435 }
11436 let base = cbase;
11437 if let (Some(b0), Some(b1)) = (
11438 mv_residual_bits(mv, base.0),
11439 mv_residual_bits(mv1, base.1),
11440 ) {
11441 ccands.push((
11442 (mv, mv1),
11443 mode_bits_of(7) + b0 + b1,
11444 InterInfo {
11445 ref_frame: crate::mvstack::LAST_FRAME,
11446 mode: InterMode::NewNewMv,
11447 mv,
11448 mv1,
11449 ref1: Some(ref1),
11450 ref_mv_idx: 0,
11451 },
11452 ));
11453 }
11454 }
11455 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
11456 ccands.dedup_by_key(|c| c.0);
11457 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
11458 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
11459 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
11460 for (mvs, bits, info) in ccands {
11461 let luma_trial = mc_trial_compound(
11462 luma, x, y, BLOCK, mvs, true,
11463 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
11464 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
11465 );
11466 let u = mc_trial_compound(
11467 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
11468 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
11469 search.base_q_idx, search.deadzone, chroma_set, fctx,
11470 );
11471 let v = mc_trial_compound(
11472 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
11473 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
11474 search.base_q_idx, search.deadzone, chroma_set, fctx,
11475 );
11476 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11477 && u.levels.iter().all(|&l| l == 0)
11478 && v.levels.iter().all(|&l| l == 0);
11479 let cost = luma_trial.sse
11480 + u.sse
11481 + v.sse
11482 + search.lambda
11483 * (skip_bits(skip)
11484 + intra_inter_bits(true)
11485 + bits
11486 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
11487 consider(Candidate {
11488 cost,
11489 luma: luma_trial,
11490 u,
11491 v,
11492 mode: DC_PRED,
11493 skip,
11494 mode_bits: bits,
11495 inter: Some(info),
11496 });
11497 }
11498 }
11499
11500 // One trial set per distinct (reference, vector) pair: sort, cheapest
11501 // syntax first, and drop the rest of each pair's run.
11502 cands.sort_by(|a, b| {
11503 (a.2.ref_frame, a.0)
11504 .cmp(&(b.2.ref_frame, b.0))
11505 .then(a.1.total_cmp(&b.1))
11506 });
11507 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
11508 census_add(7, cands.len());
11509 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
11510 // this block reaches WITHOUT it, taken inside the one loop that prices
11511 // them all (a second pricing pass would be a second oracle).
11512 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
11513 {
11514 for (mv, mode_bits_inter, info) in cands {
11515 let (ref_luma, ref_u, ref_v) = match extra
11516 .iter()
11517 .find(|(r, _, _)| *r == info.ref_frame)
11518 {
11519 Some(&(_, g, _)) => (
11520 (&g.y, g.width, luma.true_width, luma.true_height),
11521 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
11522 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
11523 ),
11524 None => (ref_luma, ref_u, ref_v),
11525 };
11526 let luma_trial = mc_trial(
11527 luma,
11528 x,
11529 y,
11530 BLOCK,
11531 mv,
11532 true,
11533 ref_luma.0,
11534 ref_luma.1,
11535 ref_luma.2,
11536 ref_luma.3,
11537 false,
11538 search.base_q_idx,
11539 search.deadzone,
11540 TxbSet::Luma32Inter, fctx,
11541 );
11542 let u = mc_trial(
11543 &chroma[0],
11544 x / 2,
11545 y / 2,
11546 BLOCK / 2,
11547 mv,
11548 false,
11549 ref_u.0,
11550 ref_u.1,
11551 ref_u.2,
11552 ref_u.3,
11553 false,
11554 search.base_q_idx,
11555 search.deadzone,
11556 chroma_set, fctx,
11557 );
11558 let v = mc_trial(
11559 &chroma[1],
11560 x / 2,
11561 y / 2,
11562 BLOCK / 2,
11563 mv,
11564 false,
11565 ref_v.0,
11566 ref_v.1,
11567 ref_v.2,
11568 ref_v.3,
11569 false,
11570 search.base_q_idx,
11571 search.deadzone,
11572 chroma_set, fctx,
11573 );
11574 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11575 && u.levels.iter().all(|&l| l == 0)
11576 && v.levels.iter().all(|&l| l == 0);
11577 let cost = luma_trial.sse
11578 + u.sse
11579 + v.sse
11580 + search.lambda
11581 * (skip_bits(skip)
11582 + intra_inter_bits(true)
11583 + mode_bits_inter
11584 + if skip {
11585 0.0
11586 } else {
11587 luma_trial.bits + u.bits + v.bits
11588 });
11589 consider(Candidate {
11590 cost,
11591 luma: luma_trial,
11592 u,
11593 v,
11594 mode: DC_PRED,
11595 skip,
11596 mode_bits: mode_bits_inter,
11597 inter: Some(info),
11598 });
11599 if newmv_census_on() {
11600 if info.mode == InterMode::NewMv
11601 && info.ref1.is_none()
11602 && info.ref_frame == crate::mvstack::LAST_FRAME
11603 {
11604 new_cost = cost;
11605 } else {
11606 other_cost = other_cost.min(cost);
11607 }
11608 }
11609 }
11610 }
11611 if let Some((new_mv, bits)) = newmv_syntax {
11612 newmv_census_block(BLOCK, true, new_cost, other_cost, new_mv, stack.nearest_mv, bits);
11613 } else {
11614 newmv_census_block(BLOCK, false, f64::INFINITY, other_cost, mv, stack.nearest_mv, 0.0);
11615 }
11616
11617 let best = best.expect("the search offers at least the intra modes");
11618 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
11619 // offered to the SINGLE-REFERENCE winner only -- libaom's
11620 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
11621 // compound block, so the writer codes no symbol for one. The prediction
11622 // is built by the DECODER's own plan and blend
11623 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
11624 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
11625 // this search's `grid` already carries, so what is priced here is what a
11626 // decoder reconstructs -- never a second implementation of the blend.
11627 //
11628 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
11629 // on). Native crop BD, the standing recipe, with it on against the same
11630 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
11631 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
11632 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
11633 // one UP -- the keep rule wants two down and one flat, so it stays off.
11634 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
11635 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
11636 // things bound it and are the upgrade path: only the 32x32 winner is
11637 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
11638 // that is where libaom cashes most of its OBMC gain), and the symbol/
11639 // residual price here is the static-CDF estimate.
11640 let mut best = best;
11641 let mut motion_won = 0u8;
11642 if let Some(info) = best.inter.filter(|i| {
11643 i.ref1.is_none()
11644 && (crate::envflags::env_flag!("EC_AV1_OBMC")
11645 || warp_on())
11646 }) {
11647 let mut refs: [Option<&Picture>; 8] = [None; 8];
11648 refs[LAST_FRAME as usize] = Some(reference);
11649 for &(r, p, _) in extra {
11650 refs[r as usize] = Some(p);
11651 }
11652 // This block's OWN reference planes: the single-reference winner may
11653 // be one of the extra references, not LAST.
11654 let planes: [(&[u16], usize, usize, usize); 3] =
11655 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11656 Some(&(_, g, _)) => [
11657 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11658 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11659 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11660 ],
11661 None => [
11662 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
11663 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
11664 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
11665 ],
11666 };
11667 // The alphabet `tile::write_motion_mode` will code this block's
11668 // symbol against, mirrored term for term (libaom
11669 // `motion_mode_allowed`).
11670 let warp_alphabet = warp_on()
11671 && crate::decode::num_proj_ref(
11672 grid,
11673 mi_row,
11674 mi_col,
11675 8,
11676 8,
11677 mi_cols,
11678 mi_rows,
11679 info.ref_frame,
11680 fctx,
11681 ) >= 1;
11682 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
11683 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
11684 if crate::envflags::env_flag!("EC_AV1_OBMC") {
11685 if let Some(pred) = obmc_prediction(
11686 grid,
11687 (mi_row, mi_col),
11688 (mi_rows, mi_cols),
11689 (x, y),
11690 BLOCK,
11691 info.mv,
11692 &refs,
11693 planes,
11694 reference.width,
11695 fctx,
11696 ) {
11697 candidates.push((1, pred));
11698 }
11699 }
11700 if warp_alphabet {
11701 if let Some(pred) = warp_prediction(
11702 grid,
11703 (mi_row, mi_col),
11704 (mi_rows, mi_cols),
11705 (x, y),
11706 BLOCK,
11707 info.mv,
11708 info.ref_frame,
11709 planes,
11710 fctx,
11711 ) {
11712 candidates.push((2, pred));
11713 }
11714 }
11715 for (motion, pred) in candidates {
11716 let luma_trial = luma.code_from_prediction(
11717 x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
11718 TxbSet::Luma32Inter,
11719 );
11720 let u = chroma[0].code_from_prediction(
11721 x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
11722 chroma_set,
11723 );
11724 let v = chroma[1].code_from_prediction(
11725 x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
11726 chroma_set,
11727 );
11728 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11729 && u.levels.iter().all(|&l| l == 0)
11730 && v.levels.iter().all(|&l| l == 0);
11731 let cost = luma_trial.sse
11732 + u.sse
11733 + v.sse
11734 + search.lambda
11735 * (skip_bits(skip)
11736 + intra_inter_bits(true)
11737 + best.mode_bits
11738 + mm(motion)
11739 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
11740 if cost < best.cost + search.lambda * mm(motion_won) {
11741 motion_won = motion;
11742 best = Candidate {
11743 cost,
11744 luma: luma_trial,
11745 u,
11746 v,
11747 mode: DC_PRED,
11748 skip,
11749 mode_bits: best.mode_bits,
11750 inter: best.inter,
11751 };
11752 }
11753 }
11754 }
11755 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
11756 // default OFF): the four 16x16 units of `commit_inter_luma` against the
11757 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
11758 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
11759 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
11760 // it, and it is worse again on the deciding native table: film 1080p
11761 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
11762 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
11763 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
11764 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
11765 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
11766 // +28.4/+47.4/-4.0 -- the native table decides.)
11767 //
11768 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
11769 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
11770 // either, and the census names the row: the split units' own set
11771 // `Luma16Inter` is priced within 1.4% of what it is written at in every
11772 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
11773 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
11774 // so a perfect pricer would split even more, and more splitting is what
11775 // measured worse. The four extra txb_skip/eob symbols simply cost more
11776 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
11777 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
11778 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
11779 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
11780 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
11781 // plain translation, which is not the prediction it was priced from.
11782 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
11783 Some(info) => {
11784 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11785 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11786 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
11787 };
11788 let second = info.ref1.and_then(|r| {
11789 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
11790 (
11791 info.mv1,
11792 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11793 )
11794 })
11795 });
11796 match info.ref1.is_some() && second.is_none() {
11797 true => {
11798 luma.commit(x, y, BLOCK, &best.luma);
11799 (best.luma.levels.clone(), 0, 0.0, Vec::new())
11800 }
11801 false => commit_inter_luma(
11802 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,
11803 fctx,
11804 ),
11805 }
11806 }
11807 None => {
11808 luma.commit(x, y, BLOCK, &best.luma);
11809 (best.luma.levels.clone(), 0, 0.0, Vec::new())
11810 }
11811 };
11812 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
11813 let [bu, bv] = match (best.inter.filter(|_| motion_won == 0), luma_tx_types.first().copied()) {
11814 (Some(info), Some(t)) => {
11815 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11816 Some(&(_, g, _)) => (
11817 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11818 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11819 ),
11820 None => (
11821 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
11822 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
11823 ),
11824 };
11825 let sec = info.ref1.and_then(|r| {
11826 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
11827 (
11828 info.mv1,
11829 [
11830 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11831 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11832 ],
11833 )
11834 })
11835 });
11836 recode_inter_chroma(
11837 chroma, (x, y), BLOCK, info.mv, [ou, ov], sec, search, chroma_set, t, fctx,
11838 )
11839 .unwrap_or([best.u, best.v])
11840 }
11841 _ => [best.u, best.v],
11842 };
11843 let best = Candidate { u: bu, v: bv, ..best };
11844 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
11845 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
11846 (
11847 BlockCoeffs {
11848 luma_tx_types,
11849 angle_delta_y: 0,
11850 cfl_alphas: None,
11851 filter_intra: None,
11852 luma: coeffs(&levels, BLOCK),
11853 u: coeffs(&best.u.levels, BLOCK / 2),
11854 v: coeffs(&best.v.levels, BLOCK / 2),
11855 mode: best.mode,
11856 uv_mode: DC_PRED,
11857 skip: best.skip,
11858 inter: best.inter,
11859 motion_mode: motion_won,
11860 eight: None,
11861 dv: None,
11862 palette: None,
11863 palette_uv: None,
11864 tx_depth,
11865 },
11866 best.cost + dcost,
11867 )
11868}
11869
11870/// lane-av1tpl: the strength `k` of the temporal lambda weighting
11871/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
11872/// is what every measurement before this lane was taken on. Swept by
11873/// `EC_AV1_TPL=<k>`.
11874///
11875/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
11876/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
11877/// baseline exactly, which is the control the rest of the table is read
11878/// against:
11879///
11880/// | k | film 1080p | film 2160p | screen |
11881/// |---|---|---|---|
11882/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
11883/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
11884/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
11885/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
11886/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
11887///
11888/// 0.5 is the only arm that is at least flat on every row and down on five of
11889/// the six columns, so it ships as the default. The lookahead pass that feeds
11890/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
11891const TPL_STRENGTH: f64 = 0.5;
11892
11893/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
11894/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
11895/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
11896/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
11897///
11898/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
11899/// nothing to vary the quantizer BY and codes no delta syntax at all.
11900fn deltaq_res_log2() -> Option<u8> {
11901 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
11902 u8::MAX => {}
11903 4 => return None,
11904 r => return Some(r),
11905 }
11906 match crate::envflags::var("EC_AV1_DELTAQ").ok().as_deref().map(str::trim) {
11907 Some("0") => None,
11908 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
11909 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
11910 }
11911}
11912
11913/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
11914/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
11915/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
11916/// speed presets take, because the streams every other test pins move under
11917/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
11918static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 =
11919 std::sync::atomic::AtomicU8::new(u8::MAX);
11920
11921/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
11922#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
11923pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
11924 DELTAQ_OVERRIDE.store(
11925 res_log2.unwrap_or(u8::MAX),
11926 std::sync::atomic::Ordering::Relaxed,
11927 );
11928}
11929
11930/// How much of the derived qindex step is actually taken
11931/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
11932fn deltaq_k() -> f64 {
11933 crate::envflags::var("EC_AV1_DELTAQ_K")
11934 .ok()
11935 .and_then(|v| v.trim().parse::<f64>().ok())
11936 .filter(|k| k.is_finite() && *k >= 0.0)
11937 .unwrap_or(1.0)
11938}
11939
11940/// The largest qindex the map may move a superblock by, either way
11941/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
11942/// deltaq around a quarter of the base qindex).
11943fn deltaq_clamp() -> i32 {
11944 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
11945 .ok()
11946 .and_then(|v| v.trim().parse::<i32>().ok())
11947 .filter(|c| (0..=63).contains(c))
11948 .unwrap_or(16)
11949}
11950
11951/// The qindex a lambda factor `f` asks for, derived rather than fitted.
11952///
11953/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
11954/// square of the quantizer step (`encode_inter_frame`'s own
11955/// `lambda = .. * step * step`), so the step this superblock wants is
11956/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
11957/// step ratio is inverted through the table itself -- the index whose `ac_q`
11958/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
11959/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
11960/// bounds it, and the answer is snapped onto the `res` grid so that every
11961/// superblock's qindex is congruent to `base` and the coded delta is a whole
11962/// number of steps.
11963fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
11964 let base_ac = f64::from(ac_q(8, i32::from(base)));
11965 let target = base_ac * f.max(1e-6).sqrt();
11966 let exact = (1..=255)
11967 .min_by(|&a, &b| {
11968 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
11969 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
11970 })
11971 .expect("the qindex range is not empty")
11972 - i32::from(base);
11973 let want = (exact as f64 * k).round() as i32;
11974 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
11975 // and need not be a whole number of steps, and clamping afterwards would
11976 // hand back a qindex that is not congruent to `base`.
11977 let max_steps = clamp / res;
11978 let steps = (want as f64 / f64::from(res)).round() as i32;
11979 let delta = steps.clamp(-max_steps, max_steps) * res;
11980 (i32::from(base) + delta).clamp(1, 255) as u8
11981}
11982
11983/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
11984/// objective would, from the SAME tpl dependence ratio our own map already
11985/// carries (`EC_AV1_DQ_TPL=1`).
11986///
11987/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
11988/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
11989/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
11990/// same expression at frame scope) by it, and asks
11991/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
11992/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
11993/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
11994/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
11995/// libaom reads `r0`. The offset is clamped to libaom's own
11996/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
11997/// twice the +-16 qindex [`deltaq_for_factor`] allows.
11998///
11999/// Two things differ from [`deltaq_for_factor`] and both are the point of the
12000/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
12001/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
12002/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
12003/// much stronger for the same map. `strength` scales the offset.
12004fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
12005 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
12006 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
12007 let exact = (1..=255)
12008 .min_by(|&a, &b| {
12009 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
12010 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
12011 })
12012 .expect("the qindex range is not empty")
12013 - i32::from(base);
12014 let want = exact as f64 * strength;
12015 // Snapped onto the `res` grid first, so the coded delta is a whole number
12016 // of steps, then bounded by libaom's own `res * 9 - 1`.
12017 let max_steps = (res * 9 - 1) / res;
12018 let steps = (want / f64::from(res)).round() as i32;
12019 let delta = steps.clamp(-max_steps, max_steps) * res;
12020 (i32::from(base) + delta).clamp(1, 255) as u8
12021}
12022
12023/// The frame-level `r0` libaom's objective divides by: the log-mean of
12024/// `1 + r` over the frame's cells, minus 1.
12025fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
12026 if ratio.is_empty() {
12027 return 0.0;
12028 }
12029 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
12030 m.exp() - 1.0
12031}
12032
12033/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
12034/// [`deltaq_for_factor`] derivation.
12035///
12036/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
12037/// the strength (default 1.0 = libaom's own offset when the flag armed it);
12038/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
12039fn dq_tpl_strength(level: DqLevel) -> Option<f64> {
12040 let m = dq_level_k()[level as usize];
12041 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
12042 .ok()
12043 .and_then(|v| v.trim().parse::<f64>().ok())
12044 .filter(|k| k.is_finite() && *k >= 0.0);
12045 let base = match crate::envflags::var("EC_AV1_DQ_TPL").ok().as_deref().map(str::trim) {
12046 Some("0") => return None,
12047 Some(_) => Some(env_k.unwrap_or(1.0)),
12048 None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))),
12049 };
12050 base.map(|k| k * m).filter(|k| *k > 0.0)
12051}
12052
12053/// lane-arfq: which pyramid level the frame asking for a
12054/// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it
12055/// codes no `delta_q` syntax at all (the whole lever lives in
12056/// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the
12057/// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job.
12058#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12059pub(crate) enum DqLevel {
12060 /// The mini-GOP's own hidden `ALTREF`, which every other frame of the
12061 /// group predicts from (directly or through the mid level).
12062 TopArf = 0,
12063 /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it.
12064 MidArf = 1,
12065 /// A shown leaf -- and every frame of the flat, non-pyramid path.
12066 Leaf = 2,
12067}
12068
12069/// The per-level multiplier on the [`dq_tpl_strength`] the preset carries:
12070/// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else
12071/// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes
12072/// no `delta_q` (see [`DqLevel`]).
12073fn dq_level_k() -> [f64; 3] {
12074 dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref())
12075}
12076
12077/// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an
12078/// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry.
12079fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] {
12080 let mut k = crate::speed::DQ_LEVEL_K;
12081 if let Some(spec) = spec {
12082 for (slot, field) in k.iter_mut().zip(spec.split(':')) {
12083 if let Some(v) =
12084 field.trim().parse::<f64>().ok().filter(|v: &f64| v.is_finite() && *v >= 0.0)
12085 {
12086 *slot = v;
12087 }
12088 }
12089 }
12090 k
12091}
12092
12093/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
12094/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
12095/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
12096/// the same tpl map -- and which of the two the frame actually coded.
12097fn dq_census() -> bool {
12098 crate::envflags::var("EC_AV1_DQ_CENSUS").ok().as_deref().map(str::trim) == Some("1")
12099}
12100
12101/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
12102fn dq_summary(offsets: &[i32]) -> String {
12103 let n = offsets.len().max(1);
12104 let (lo, hi) = offsets.iter().fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
12105 let nz = offsets.iter().filter(|&&o| o != 0).count();
12106 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
12107 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
12108 let mut levels: Vec<i32> = offsets.to_vec();
12109 levels.sort_unstable();
12110 levels.dedup();
12111 format!(
12112 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
12113 offsets.len(),
12114 levels.len()
12115 )
12116}
12117
12118/// How many DISTINCT per-superblock quantizer levels the last inter frame's
12119/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
12120/// (class `gate-blind-to-feature`: every exactness assert below passes on a
12121/// grid that is one flat value, i.e. on no delta_q at all). Process-global
12122/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
12123/// keeps the LARGEST count seen since the last read.
12124static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12125
12126/// [`DELTAQ_LEVELS`], reset to 0.
12127#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
12128pub(crate) fn take_deltaq_levels() -> usize {
12129 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
12130}
12131
12132/// This superblock's search state: the quantizer it is coded at, and the
12133/// lambda that quantizer implies. RD lambda goes as the square of the step,
12134/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
12135/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
12136/// before lane-deltaq).
12137fn sb_q_search<'m>(
12138 sb_q: &[u8],
12139 sb_cols: usize,
12140 base_q_idx: u8,
12141 (sb_r, sb_c): (usize, usize),
12142 base: Search<'m>,
12143) -> Search<'m> {
12144 let q = sb_q[sb_r * sb_cols + sb_c];
12145 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
12146 Search { base_q_idx: q, lambda: base.lambda * ratio * ratio, ..base }
12147}
12148
12149fn tpl_strength() -> f64 {
12150 std::env::var("EC_AV1_TPL")
12151 .ok()
12152 .and_then(|v| v.parse::<f64>().ok())
12153 .filter(|k| k.is_finite() && *k >= 0.0)
12154 .unwrap_or(TPL_STRENGTH)
12155}
12156
12157/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
12158/// the frame being coded. 1 turns the weighting off; 2 is the shipped
12159/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
12160/// [`tpl_propagating`], which is the map that can actually use them and is
12161/// the default since lane-av1tpl3, so the default window is 8. Swept by
12162/// `EC_AV1_TPL_D=<d>`.
12163///
12164/// The streaming facade holds `depth - 1` pictures back so it feeds
12165/// `encode_inter_frame` the same window `encode_sequence` does; both read
12166/// THIS function, so the two paths cannot disagree about the window.
12167pub(crate) const TPL_DEPTH: usize = 8;
12168
12169/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
12170/// 0.5 is libaom's own square-root compression of its dependence ratio.
12171const TPL_POWER: f64 = 0.5;
12172
12173/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
12174/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
12175///
12176/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
12177/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
12178/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
12179///
12180/// | k | D | p | film 1080p | film 2160p | screen |
12181/// |---|---|---|---|---|---|
12182/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
12183/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
12184/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
12185/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
12186/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
12187/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
12188/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
12189/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
12190/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
12191/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
12192/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
12193/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
12194///
12195/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
12196/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
12197/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
12198/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
12199/// 0.1..0.4 UP on film 2160p, so it shipped off.
12200///
12201/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
12202/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
12203/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
12204/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
12205/// wherever the window leans on a flat bar, which is exactly where coding is
12206/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
12207/// (libaom's own granularity) puts a busy cell's denominator next to the flat
12208/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
12209/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
12210/// the same native gate (baseline = the shipped one-frame map):
12211///
12212/// | arm | film 1080p | film 2160p | screen |
12213/// |---|---|---|---|
12214/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
12215/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
12216/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
12217/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
12218/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
12219/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
12220/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
12221/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
12222/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
12223/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
12224///
12225/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
12226/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
12227/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
12228/// floor is a real effect on the ratio and never a win once the aggregation
12229/// is in -- the aggregation is the same fix, done where libaom does it.
12230fn tpl_propagating() -> bool {
12231 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
12232}
12233
12234pub(crate) fn tpl_depth() -> usize {
12235 std::env::var("EC_AV1_TPL_D")
12236 .ok()
12237 .and_then(|v| v.parse::<usize>().ok())
12238 .filter(|d| *d >= 1)
12239 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
12240 .max(1)
12241}
12242
12243/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
12244/// process, so the gate can price it against the encode it rides on.
12245static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
12246
12247/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
12248/// the winning displacement and its SAD.
12249///
12250/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
12251/// the left/above winners, first-best tie-break. Built once on the frame's
12252/// own thread and read-only afterwards, so it cannot make a tile's bytes
12253/// depend on the thread count.
12254fn tpl_coarse_pass(
12255 cur: &[u8],
12256 next: &[u8],
12257 width: usize,
12258 height: usize,
12259) -> Vec<((i32, i32), u32)> {
12260 let (cells_x, cells_y) = (width / 16, height / 16);
12261 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
12262 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
12263 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
12264 return u32::MAX;
12265 }
12266 let (sx, sy) = (sx as usize, sy as usize);
12267 let mut sum = 0u32;
12268 for r in 0..16 {
12269 let a = &next[(by + r) * width + bx..][..16];
12270 let b = &cur[(sy + r) * width + sx..][..16];
12271 sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>();
12272 }
12273 sum
12274 };
12275 let mut out = Vec::with_capacity(cells_x * cells_y);
12276 let mut above = vec![(0i32, 0i32); cells_x];
12277 for cy in 0..cells_y {
12278 let mut left = (0i32, 0i32);
12279 for cx in 0..cells_x {
12280 let (bx, by) = (cx * 16, cy * 16);
12281 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
12282 for cand in [left, above[cx]] {
12283 if cand != (0, 0) {
12284 let s = sad(bx, by, cand);
12285 if s < best.0 {
12286 best = (s, cand);
12287 }
12288 }
12289 }
12290 for step in [8i32, 4, 2, 1] {
12291 let centre = best.1;
12292 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
12293 let mv = (centre.0 + dx, centre.1 + dy);
12294 if mv.0.abs() > 32 || mv.1.abs() > 32 {
12295 continue;
12296 }
12297 let s = sad(bx, by, mv);
12298 if s < best.0 {
12299 best = (s, mv);
12300 }
12301 }
12302 }
12303 left = best.1;
12304 above[cx] = best.1;
12305 out.push((best.1, best.0));
12306 }
12307 }
12308 out
12309}
12310
12311/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
12312/// transform: here, the mean absolute deviation of the cell from its own DC.
12313/// It is the denominator every propagated cost is read against, so only its
12314/// SHAPE across the frame matters, not its scale.
12315fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
12316 let (cells_x, cells_y) = (width / 16, height / 16);
12317 let mut out = Vec::with_capacity(cells_x * cells_y);
12318 for cy in 0..cells_y {
12319 for cx in 0..cells_x {
12320 let (bx, by) = (cx * 16, cy * 16);
12321 let mut sum = 0u32;
12322 for r in 0..16 {
12323 sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>();
12324 }
12325 let dc = ((sum + 128) / 256) as u8;
12326 let mut cost = 0u32;
12327 for r in 0..16 {
12328 cost += frame[(by + r) * width + bx..][..16]
12329 .iter()
12330 .map(|&p| u32::from(p.abs_diff(dc)))
12331 .sum::<u32>();
12332 }
12333 out.push(cost);
12334 }
12335 }
12336 out
12337}
12338
12339/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
12340/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
12341/// splats its own area, at its winning displacement, onto the (at most four)
12342/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
12343fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
12344 let start = std::time::Instant::now();
12345 let (cells_x, cells_y) = (width / 16, height / 16);
12346 let pass = tpl_coarse_pass(cur, next, width, height);
12347 let mut area = vec![0.0f64; cells_x * cells_y];
12348 for cy in 0..cells_y {
12349 for cx in 0..cells_x {
12350 let (mv, _) = pass[cy * cells_x + cx];
12351 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
12352 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
12353 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
12354 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
12355 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
12356 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
12357 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
12358 }
12359 }
12360 }
12361 }
12362 TPL_NANOS.fetch_add(
12363 start.elapsed().as_nanos() as u64,
12364 std::sync::atomic::Ordering::Relaxed,
12365 );
12366 area
12367}
12368
12369/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
12370/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
12371/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
12372/// Decreasing in referenced-ness (a block the next frame leans on is coded
12373/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
12374/// total lambda scale is only redistributed, never moved -- a global move is
12375/// the thing lane-av1lambda already measured inert.
12376fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
12377 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
12378 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
12379 let mut out = Vec::with_capacity(sb_cols * sb_rows);
12380 for sr in 0..sb_rows {
12381 for sc in 0..sb_cols {
12382 let mut sum = 0.0;
12383 for r in 0..4 {
12384 for c in 0..4 {
12385 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
12386 }
12387 }
12388 let w_rel = sum / 16.0 / mean;
12389 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
12390 }
12391 }
12392 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
12393 let mut hist = [0usize; 8];
12394 for w in map {
12395 hist[((w / mean * 2.0) as usize).min(7)] += 1;
12396 }
12397 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
12398 eprintln!(
12399 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
12400 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
12401 map.len(),
12402 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
12403 );
12404 }
12405 out
12406}
12407
12408/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
12409/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
12410/// much of the WHOLE lookahead window leans on that cell.
12411///
12412/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
12413/// coarse pass gives a displacement and an inter cost; a cell's own
12414/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
12415/// cell well saves the frames that predict from it -- and it is splatted,
12416/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
12417/// displacement lands on. Walking `f` from the far end of the window back to
12418/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
12419/// area map could not do at all.
12420///
12421/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
12422/// factor over the frame is exactly 1: a cell the window leans on is coded
12423/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
12424/// scale only moves around, never up or down -- a global move is what
12425/// lane-av1lambda already measured inert.
12426/// Returns the per-cell lambda factors AND the per-cell dependence ratio
12427/// `mc_dep / intra` they were derived from -- the second half is what
12428/// [`deltaq_libaom`] needs, since the factor alone has been through a
12429/// mean normalisation the raw ratio cannot be recovered across.
12430fn tpl_lambda_factors(
12431 frames: &[&[u8]],
12432 width: usize,
12433 height: usize,
12434 k: f64,
12435) -> (Vec<f64>, Vec<f64>) {
12436 let start = std::time::Instant::now();
12437 let (cells_x, cells_y) = (width / 16, height / 16);
12438 let cells = cells_x * cells_y;
12439 let levels = frames.len();
12440 let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect();
12441 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
12442 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
12443 .collect();
12444 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
12445 for f in (1..levels).rev() {
12446 for cy in 0..cells_y {
12447 for cx in 0..cells_x {
12448 let ci = cy * cells_x + cx;
12449 let (mv, inter) = passes[f - 1][ci];
12450 let saved = f64::from(intra[f][ci].saturating_sub(inter));
12451 let propagate = saved + mc_dep[f][ci];
12452 if propagate <= 0.0 {
12453 continue;
12454 }
12455 // The 16x16 window of the PREVIOUS frame this cell predicted
12456 // from, spread over the cells it overlaps.
12457 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
12458 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
12459 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
12460 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
12461 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
12462 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
12463 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
12464 }
12465 }
12466 }
12467 }
12468 }
12469 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
12470 // tail (a nearly flat cell the window leans on has a tiny denominator),
12471 // and at p = 1 that tail slams into the clamp. libaom reads its own
12472 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
12473 // sweeps the exponent, 1 being the raw ratio.
12474 let power = std::env::var("EC_AV1_TPL_P")
12475 .ok()
12476 .and_then(|v| v.parse::<f64>().ok())
12477 .filter(|p| p.is_finite() && *p > 0.0)
12478 .unwrap_or(TPL_POWER);
12479 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
12480 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
12481 // `0` to take either back out); `FLOOR` defaults to off.
12482 //
12483 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
12484 // frame's own mean intra cost. A cell of flat content has a near-zero
12485 // MAD, so its ratio explodes exactly where coding is cheap.
12486 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
12487 // and mc_dep are summed over the 64x64 superblock first -- libaom's
12488 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
12489 // per-16x16 numbers), which is also what makes the ratio survive one
12490 // flat cell next to a busy one.
12491 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
12492 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
12493 // harder than the `p` exponent alone can.
12494 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
12495 .ok()
12496 .and_then(|v| v.parse::<f64>().ok())
12497 .filter(|f| f.is_finite() && *f >= 0.0)
12498 .unwrap_or(0.0);
12499 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
12500 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
12501 let intra_mean =
12502 intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
12503 let floor = floor_frac * intra_mean;
12504 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
12505 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
12506 // every cell under it. The edge groups are partial and summed as they are.
12507 let ratio: Vec<f64> = if sb_agg {
12508 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
12509 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
12510 for cy in 0..cells_y {
12511 for cx in 0..cells_x {
12512 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
12513 e.0 += mc_dep[0][cy * cells_x + cx];
12514 e.1 += denom(cy * cells_x + cx);
12515 }
12516 }
12517 (0..cells)
12518 .map(|c| {
12519 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
12520 dep / den.max(1.0)
12521 })
12522 .collect()
12523 } else {
12524 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
12525 };
12526 let mut out: Vec<f64> = ratio
12527 .iter()
12528 .map(|&r| {
12529 let r = if log_beta { (1.0 + r).log2() } else { r };
12530 (1.0 + k * r).powf(-power)
12531 })
12532 .collect();
12533 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
12534 for f in &mut out {
12535 *f = (*f / mean).clamp(0.25, 4.0);
12536 }
12537 TPL_NANOS.fetch_add(
12538 start.elapsed().as_nanos() as u64,
12539 std::sync::atomic::Ordering::Relaxed,
12540 );
12541 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
12542 let mut hist = [0usize; 8];
12543 for &f in &out {
12544 hist[((f * 4.0) as usize).min(7)] += 1;
12545 }
12546 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
12547 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
12548 eprintln!(
12549 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
12550 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
12551 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
12552 );
12553 }
12554 (out, ratio)
12555}
12556
12557/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
12558/// references name, which slot it refreshes, whether it is shown when it is
12559/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
12560/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
12561/// 0/2 alternation, every frame shown, every reference in the past).
12562///
12563/// The sign bias is carried rather than derived here because only the caller
12564/// knows what order hint each slot holds; it is armed onto the tile writer
12565/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
12566/// the writer scans the same stacks the decoder will.
12567#[derive(Debug, Clone, Copy)]
12568pub(crate) struct PyramidFrame {
12569 /// The slot `LAST_FRAME` (and every reference this encoder does not name
12570 /// apart) reads.
12571 pub last_slot: u8,
12572 /// The single slot `refresh_frame_flags` sets.
12573 pub self_slot: u8,
12574 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
12575 /// pyramid, which is what makes `sign_bias`'s last entry true.
12576 pub altref_slot: u8,
12577 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
12578 /// picture (the leaf chain alternates its refresh between two slots, so
12579 /// the frame before `LAST` is still intact). `None` leaves
12580 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
12581 /// wrote before, and the caller then passes no `last2` picture either.
12582 pub last2_slot: Option<u8>,
12583 /// `show_frame`: false for a hidden frame, output later by a
12584 /// `show_existing_frame` header.
12585 pub show_frame: bool,
12586 /// lane-arfq: which level's `delta_q` strength this frame reads
12587 /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid
12588 /// one share `Level::Arf` and differ only by their q offset.
12589 pub dq_level: DqLevel,
12590 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
12591 pub sign_bias: crate::mvstack::SignBiasTable,
12592}
12593
12594/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
12595/// `temporal_filter` in the small: every 16x16 luma block of `src` is
12596/// motion-compensated from each picture of `window` (the group's own display
12597/// neighbours, nearest first) and averaged in with weight
12598/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
12599/// nothing and one that matches well cancels the grain the block's residual
12600/// would otherwise have to code.
12601///
12602/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
12603/// rides the luma block's own vector (halved), which is what libaom does at
12604/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
12605/// grid tiles it exactly.
12606///
12607/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
12608/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
12609/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
12610/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
12611/// quality the ARF is coded at, so the substitution itself costs little.
12612// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and
12613// `ARF_TF_WIN_FUT` future ones); this takes every picture in it.
12614pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
12615 const SIDE: usize = 16;
12616 let neighbours: Vec<&Picture> = window
12617 .iter()
12618 .filter(|p| p.width == src.width && p.height == src.height)
12619 .collect();
12620 if neighbours.is_empty() || strength <= 0.0 {
12621 return src.clone();
12622 }
12623 let mut out = src.clone();
12624 // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
12625 // `None` when the displaced block leaves the picture.
12626 let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
12627 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
12628 if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
12629 return None;
12630 }
12631 let (sy, sx) = (sy as usize, sx as usize);
12632 let mut acc = 0u64;
12633 for row in 0..SIDE {
12634 let c = &src.y[(by + row) * src.width + bx..][..SIDE];
12635 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
12636 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
12637 }
12638 Some((acc, (sy, sx)))
12639 };
12640 // The log-step diamond `arf_pred_census` priced this with.
12641 let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
12642 let mut best = sad(r, bx, by, (0, 0))?;
12643 let mut centre = (0isize, 0isize);
12644 let mut step = 16isize;
12645 while step >= 1 {
12646 let from = centre;
12647 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
12648 let mv = (from.0 + dy * step, from.1 + dx * step);
12649 if let Some(s) = sad(r, bx, by, mv) {
12650 if s.0 < best.0 {
12651 best = s;
12652 centre = mv;
12653 }
12654 }
12655 }
12656 step /= 2;
12657 }
12658 Some(best.1)
12659 };
12660 let (cw, ch) = (src.width / 2, src.height / 2);
12661 for by in (0..src.height).step_by(SIDE) {
12662 for bx in (0..src.width).step_by(SIDE) {
12663 if by + SIDE > src.height || bx + SIDE > src.width {
12664 continue;
12665 }
12666 let mut y_acc = vec![0f64; SIDE * SIDE];
12667 let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
12668 let mut wsum = 1.0f64;
12669 // Chroma keeps its OWN weight sum: an edge block whose halved
12670 // vector leaves the chroma plane contributes to luma only, and
12671 // dividing chroma by the luma sum would darken it (class
12672 // `metric blind to a plane`, on the encoder side).
12673 let mut cwsum = 1.0f64;
12674 for row in 0..SIDE {
12675 for col in 0..SIDE {
12676 y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
12677 }
12678 }
12679 for row in 0..SIDE / 2 {
12680 for col in 0..SIDE / 2 {
12681 let i = (by / 2 + row) * cw + bx / 2 + col;
12682 c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
12683 c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
12684 }
12685 }
12686 for r in &neighbours {
12687 let Some((sy, sx)) = search(r, bx, by) else { continue };
12688 let mut sse = 0f64;
12689 for row in 0..SIDE {
12690 for col in 0..SIDE {
12691 let d = f64::from(src.y[(by + row) * src.width + bx + col])
12692 - f64::from(r.y[(sy + row) * r.width + sx + col]);
12693 sse += d * d;
12694 }
12695 }
12696 let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
12697 for row in 0..SIDE {
12698 for col in 0..SIDE {
12699 y_acc[row * SIDE + col] +=
12700 w * f64::from(r.y[(sy + row) * r.width + sx + col]);
12701 }
12702 }
12703 // Chroma reads the luma vector halved; a block on the picture
12704 // edge whose halved vector would leave the chroma plane is
12705 // left to luma alone rather than clamped to a different
12706 // displacement than the luma it must stay registered with.
12707 let (cy, cx) = (sy / 2, sx / 2);
12708 if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
12709 for row in 0..SIDE / 2 {
12710 for col in 0..SIDE / 2 {
12711 let i = (cy + row) * cw + cx + col;
12712 c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
12713 c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
12714 }
12715 }
12716 cwsum += w;
12717 }
12718 wsum += w;
12719 }
12720 for row in 0..SIDE {
12721 for col in 0..SIDE {
12722 out.y[(by + row) * src.width + bx + col] =
12723 (y_acc[row * SIDE + col] / wsum).round() as u16;
12724 }
12725 }
12726 for row in 0..SIDE / 2 {
12727 for col in 0..SIDE / 2 {
12728 let i = (by / 2 + row) * cw + bx / 2 + col;
12729 out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
12730 out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
12731 }
12732 }
12733 }
12734 }
12735 out
12736}
12737
12738/// Encodes one picture as an inter frame predicting from `reference`'s
12739/// reconstruction, which the caller decoded (or, for the frame right after
12740/// the key frame, is the key frame's own reconstruction).
12741pub(crate) fn encode_inter_frame(
12742 picture: &Picture,
12743 reference: &Picture,
12744 base_q_idx: u8,
12745 deadzone: f64,
12746 order_hint: u32,
12747 // The order hint each of the seven `ref_frame_idx` entries names, which a
12748 // decoder reads out of its own reference state -- only spec 5.9.22's
12749 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
12750 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
12751 // callers that follow this crate's own flat slot plan.
12752 order_hints: [u32; 7],
12753 render: (usize, usize),
12754 // The tables this frame's writer starts from: what the previous frame
12755 // stored into the slot this one's `primary_ref_frame` names. `None`
12756 // starts from the defaults, which is right only for the frame straight
12757 // after a key frame.
12758 start_cdfs: Option<&crate::cdf_state::Cdfs>,
12759 // The key frame's own (padded) reconstruction, which every frame of the
12760 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
12761 // with `LAST_FRAME` alone, exactly as before.
12762 golden: Option<&Picture>,
12763 // The frame two back, held in the slot this frame is about to refresh
12764 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
12765 // inter frames of a GOP, where the frame two back IS the key frame.
12766 altref: Option<&Picture>,
12767 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
12768 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
12769 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
12770 // take. `None` (every caller but the pyramid leaves) codes the frame
12771 // with the reference set unchanged.
12772 last2: Option<&Picture>,
12773 fctx: &crate::decode::FrameCtx,
12774 // Where this frame sits in the coding-order pyramid; `None` is the flat
12775 // one-shown-frame-per-picture stream this encoder wrote before.
12776 pyramid: Option<PyramidFrame>,
12777 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
12778 // them), padded like this one -- the lookahead window the per-block
12779 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
12780 // EMPTY slice codes the frame at one lambda, as before.
12781 lookahead: &[Picture],
12782) -> Result<Encoded> {
12783 picture.check()?;
12784 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
12785 return Err(Error::unsupported(
12786 "AV1 encode",
12787 "an inter frame is coded only for a picture that is a whole number \
12788 of 64x64 superblocks -- the inter tile writer never splits a \
12789 superblock's partition below that",
12790 ));
12791 }
12792 if reference.width != picture.width || reference.height != picture.height {
12793 return Err(Error::unsupported(
12794 "AV1 encode",
12795 "the reference picture must be the same size as the one being coded",
12796 ));
12797 }
12798
12799 // The single slot this crate's inter frames ever predict from or
12800 // refresh (`inter_frame_headers`'s contract): every frame both reads and
12801 // overwrites slot 0, so the frame just coded is always what the next one
12802 // predicts against.
12803 const LAST_SLOT: u8 = 0;
12804 // Slot 0 and slot 2 alternate so the frame two back survives one more
12805 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
12806 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
12807 // in the very slot it will overwrite.
12808 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
12809 let last_slot = pyramid.map_or(
12810 if order_hint <= 1 {
12811 LAST_SLOT
12812 } else if (order_hint - 1) % 2 == 1 {
12813 0
12814 } else {
12815 2
12816 },
12817 |p| p.last_slot,
12818 );
12819 // `render`, not `picture.width`/`picture.height`: `picture` here is
12820 // already padded to a whole number of superblocks (`encode_sequence`'s
12821 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
12822 // every true-edge clamp downstream) must come from the frame's real,
12823 // unpadded size, same as `key_frame_headers_colour` takes `render` and
12824 // not the padded picture in `encode_key_frame_inner`.
12825 let (seq, mut header) = inter_frame_headers_slots(
12826 render.0,
12827 render.1,
12828 base_q_idx,
12829 order_hint,
12830 last_slot,
12831 self_slot,
12832 match pyramid {
12833 Some(p) => p.altref_slot,
12834 None if altref.is_some() => self_slot,
12835 None => GOLDEN_SLOT,
12836 },
12837 )?;
12838 header.render_width = render.0 as u32;
12839 header.render_height = render.1 as u32;
12840 // lane-refs: this frame's motion-compensation kernel, written into the
12841 // header AND armed on the context every prediction reads, in one place so
12842 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
12843 // tile decodes to different pixels than the encoder scored).
12844 header.interpolation_filter = frame_interp_filter();
12845 fctx.interp_filter.set(mc::InterpFilterKind::from_header(header.interpolation_filter));
12846 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
12847 // The order hint behind each `ref_frame_idx` entry. The flat path's own
12848 // slot plan (`inter_frame_headers_slots`) is: every reference but
12849 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
12850 // `ALTREF_FRAME`, which reads the frame two back when there is one;
12851 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
12852 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
12853 header.order_hints = order_hints;
12854 // lane-last2: `inter_frame_headers_slots` points every un-named
12855 // reference at `last_slot`; the pyramid's leaf chain retains a second,
12856 // older picture and names it here. The caller's `sign_bias` /
12857 // `order_hints` entry 1 is derived from this same slot, so the stack
12858 // scans and `skipModeAllowed` read what the decoder will.
12859 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
12860 header.ref_frame_idx[1] = slot;
12861 }
12862 header.reference_select = reference_select();
12863 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
12864 // per-reference order-hint distance is read by the block SEARCH, which
12865 // runs long before the writer arms these (the distance-scaled search step
12866 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
12867 // never reached the tool).
12868 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
12869 // lane-hpmv: armed here for the same reason the order hints are -- the
12870 // block SEARCH reads it (its eighth-pel stage) long before the writer.
12871 let hp_mv = header.allow_high_precision_mv;
12872 crate::tile::arm_high_precision_mv(hp_mv);
12873 if let Some(p) = pyramid {
12874 header.show_frame = p.show_frame;
12875 header.showable_frame = !p.show_frame;
12876 header.ref_frame_sign_bias = p.sign_bias;
12877 }
12878 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
12879 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
12880 // block inside this frame codes and searches its own `tx_depth`, the same
12881 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
12882 let tx_select = tx_select() && tx_select_inter();
12883 if tx_select {
12884 header.tx_mode = TxMode::Select;
12885 }
12886
12887 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
12888 // lane-palw: the encoder's own in-process reconstruct reads its palette
12889 // colour-index maps back through `decode::palette_onscreen`, which takes
12890 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
12891 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
12892 // them here so the reconstruct clamps a block cut by the frame edge
12893 // exactly as the writer now does.
12894 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
12895 fctx.seg_mi_dims.set(frame_mi_dims);
12896 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
12897 // here (see `encode_key_frame_inner`).
12898 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
12899 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
12900 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
12901 // This frame's own `allow_screen_content_tools`. It can only be set when
12902 // the SEQUENCE offers the bit at all, which is the key frame's decision
12903 // ([`SEQ_SCREEN`]): a frame header that contradicts
12904 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
12905 // encode.
12906 let screen = seq_screen()
12907 && screen_content(&picture_y8, picture.width, true_width, true_height);
12908 header.allow_screen_content_tools = screen;
12909 // lane-txi, as on the key frame: the header bit the writer's own
12910 // `Cdfs` then reads for every luma `tx_type` symbol.
12911 header.reduced_tx_set = !wide_tx_set(screen);
12912 // lane-intertx, desync (a): the frame context this value is read back
12913 // through ([`decode::reduce_inherited_chroma_tx_type`] inside
12914 // `recode_inter_chroma`, and every inter decode helper the search's own
12915 // trial decode shares) must carry THIS frame's bit, not whatever the
12916 // previous frame's trial decode last left in the shared cell -- a stale
12917 // `true` here narrows the chroma allowance the search reconstructs
12918 // against under the one the header's bit actually allows.
12919 fctx.reduced_tx_set_inter.set(header.reduced_tx_set);
12920 // The search prices coefficients against the tables this frame's writer
12921 // starts from, not against the defaults (lane-av1txbits) -- but only on a
12922 // frame the screen detector said no to (lane-av1price2): armed HERE, after
12923 // `screen` exists, and again on every search/tile worker below.
12924 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
12925 let mut luma = Plane {
12926 source: &picture_y8,
12927 reconstruction: vec![128; picture_y8.len()],
12928 width: picture.width,
12929 height: picture.height,
12930 true_width,
12931 true_height,
12932 tile_x0: 0,
12933 tile_y0: 0,
12934 tile_x1: picture.width,
12935 tile_y1: picture.height,
12936 ctx: CoefCtxMap::default(),
12937 };
12938 let mut chroma = [
12939 Plane {
12940 source: &picture_u8,
12941 reconstruction: vec![128; picture_u8.len()],
12942 width: picture.width / 2,
12943 height: picture.height / 2,
12944 true_width: true_width / 2,
12945 true_height: true_height / 2,
12946 tile_x0: 0,
12947 tile_y0: 0,
12948 tile_x1: picture.width / 2,
12949 tile_y1: picture.height / 2,
12950 ctx: CoefCtxMap::default(),
12951 },
12952 Plane {
12953 source: &picture_v8,
12954 reconstruction: vec![128; picture_v8.len()],
12955 width: picture.width / 2,
12956 height: picture.height / 2,
12957 true_width: true_width / 2,
12958 true_height: true_height / 2,
12959 tile_x0: 0,
12960 tile_y0: 0,
12961 tile_x1: picture.width / 2,
12962 tile_y1: picture.height / 2,
12963 ctx: CoefCtxMap::default(),
12964 },
12965 ];
12966
12967 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
12968 let top_arf = matches!(
12969 pyramid,
12970 Some(p) if p.dq_level == DqLevel::TopArf
12971 );
12972 let arfmode_v = arfmode();
12973 let search = Search {
12974 base_q_idx,
12975 deadzone,
12976 lambda: lambda_scale()
12977 * match pyramid {
12978 Some(p) if !p.show_frame => hidden_lambda_factor(),
12979 _ => 1.0,
12980 }
12981 * step
12982 * step,
12983 modes: &KEY_FRAME_MODES,
12984 top_k: prune_top_k_inter(),
12985 screen,
12986 // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose
12987 // offset is the pyramid's own `arf_q_offset`) reads its leaf offer
12988 // set from [`crate::speed::ARFMODE`]; every other frame -- the mid
12989 // and quarter hidden frames, the leaves, the flat path -- keeps the
12990 // full set.
12991 arf_leaf_intra: !top_arf || arfmode_v & 1 == 0,
12992 arf_leaf8: !top_arf || arfmode_v & 2 == 0,
12993 arf_leaf_compound: !top_arf || arfmode_v & 4 == 0,
12994 };
12995 let mode_bits_table = inter_mode_bits();
12996 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
12997 // this frame the NEXT one predicts from. Off (`None`) without a
12998 // lookahead picture or at strength 0.
12999 let tpl_k = tpl_strength();
13000 let window: Vec<&Picture> = lookahead
13001 .iter()
13002 .take_while(|n| n.width == picture.width && n.height == picture.height)
13003 .collect();
13004 let tpl_sources: Vec<Vec<u8>> =
13005 window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect();
13006 let tpl_cells_x = picture.width / 16;
13007 // `.1` is the propagating map's raw per-cell dependence ratio, which only
13008 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
13009 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> =
13010 (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| {
13011 if tpl_propagating() {
13012 let mut frames: Vec<&[u8]> = vec![&picture_y8];
13013 frames.extend(tpl_sources.iter().map(Vec::as_slice));
13014 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
13015 (f, Some(r))
13016 } else {
13017 // The shipped map is one factor per 64x64; it is spread over that
13018 // superblock's own 16 cells so the application site below (which
13019 // averages the four cells of a 32x32 block) reads exactly the
13020 // superblock factor, whichever map fed it.
13021 let map =
13022 tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
13023 let cells_y = picture.height / 16;
13024 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
13025 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
13026 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
13027 .collect();
13028 (f, None)
13029 }
13030 });
13031 let (tpl_factors, tpl_ratio) = match tpl_both {
13032 Some((f, r)) => (Some(f), r),
13033 None => (None, None),
13034 };
13035
13036 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
13037 // coding surface's: `blocks` carries one entry per 32x32 block the tile
13038 // writer will actually visit, same count it checks `blocks.len()`
13039 // against, which is fewer than the padded surface's own block count
13040 // whenever the true size is not a 64x64 multiple.
13041 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
13042 let (cols, rows) = (cols as usize, rows as usize);
13043 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
13044 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
13045 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
13046 // only when the map is, and `delta_q_res` follows straight into the frame
13047 // header (`write_delta_q_params`) and into the tile writer's own plan.
13048 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
13049 // measured the per-superblock quantizer as a win on both films and a
13050 // 0.5 loss vs libaom on the desktop capture, so a frame that set
13051 // `allow_screen_content_tools` codes no delta syntax at all and stays
13052 // byte-identical to the pre-lane encoder.
13053 // lane-arfq: the level whose `delta_q` strength this frame reads; the
13054 // flat path (no pyramid) is a leaf.
13055 let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level);
13056 let deltaq_res: Option<i32> = tpl_factors
13057 .as_ref()
13058 .filter(|_| !screen)
13059 .and(deltaq_res_log2().map(|r| 1i32 << r));
13060 // The same 16-cell mean the superblock's own lambda takes, clamped to the
13061 // map the frame actually has -- read over the factors or over the raw
13062 // dependence ratios, whichever mapping is asking.
13063 let sb_mean = |m: &[f64], sb: usize| {
13064 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
13065 (0..16)
13066 .map(|i| {
13067 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
13068 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
13069 })
13070 .sum::<f64>()
13071 / 16.0
13072 };
13073 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
13074 // raw dependence ratio; without it (and always without a ratio map, i.e.
13075 // on the one-frame area map) the shipped derivation stands.
13076 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
13077 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
13078 match (libaom, tpl_ratio.as_deref(), r_frame) {
13079 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
13080 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
13081 }
13082 };
13083 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
13084 (Some(f), Some(res)) => {
13085 let libaom = dq_tpl_strength(dq_level);
13086 let mut g: Vec<u8> =
13087 (0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect();
13088 // lane-b128m: under 128 superblocks the delta_q syntax is coded
13089 // ONCE per 128 root (the reader's own unit), so all four 64x64
13090 // cells of a root have to be searched -- and quantized -- at the
13091 // one qindex the root's top-left cell codes.
13092 if sb128_on() {
13093 for sb_r in 0.._sb_rows {
13094 for sb_c in 0..sb_cols {
13095 let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
13096 g[sb_r * sb_cols + sb_c] = q;
13097 }
13098 }
13099 }
13100 Some(g)
13101 }
13102 _ => None,
13103 };
13104 // lane-dq census: both mappings on the SAME superblocks, whether or not
13105 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
13106 // off, and the census then prices the default `res = 4` grid).
13107 if dq_census() {
13108 if let Some(f) = &tpl_factors {
13109 let res = deltaq_res.unwrap_or(4);
13110 let off = |libaom: Option<f64>| -> Vec<i32> {
13111 (0..sb_cols * _sb_rows)
13112 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
13113 .collect()
13114 };
13115 let strength = dq_tpl_strength(dq_level);
13116 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
13117 let coded = match (deltaq_res.is_some(), strength) {
13118 (false, _) => "none".to_string(),
13119 (true, None) => "ours".to_string(),
13120 (true, Some(k)) => format!("libaom k={k}"),
13121 };
13122 eprintln!(
13123 "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
13124 sb_cols * _sb_rows,
13125 r_frame.unwrap_or(f64::NAN),
13126 dq_summary(&ours),
13127 dq_summary(&aom),
13128 );
13129 }
13130 }
13131 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
13132 header.delta.q_present = true;
13133 header.delta.q_res = res.trailing_zeros() as u8;
13134 }
13135 // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
13136 // below, so the root search prices the group the writer really codes.
13137 let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
13138 if let Some(g) = &sb_q {
13139 let mut levels: Vec<u8> = g.clone();
13140 levels.sort_unstable();
13141 levels.dedup();
13142 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
13143 }
13144 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
13145 // This frame's tile grid, as in `encode_key_frame_inner`.
13146 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
13147 let layout =
13148 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
13149 header.tile_info = tile_info_of(&layout, 1);
13150 let header_tile_info = header.tile_info.clone();
13151 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
13152 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
13153 // once per frame (lane-av1rd2), not once per block, which is a whole
13154 // plane's map per 32x32 block and now per leaf too.
13155 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
13156 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
13157 // availability -- intra edges and the MV stack's scans alike -- already
13158 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
13159 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
13160 // giving each job its own planes and its own `MiGrid` therefore leaves
13161 // every decision, and so every coded bit, exactly where the whole-frame
13162 // loop left it, at any tile count and any thread count.
13163 let (frame_width, frame_height) = (picture.width, picture.height);
13164 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
13165 let [cb, cr] = &mut chroma;
13166 let chroma_out = [
13167 crate::par::Shared::new(&mut cb.reconstruction),
13168 crate::par::Shared::new(&mut cr.reconstruction),
13169 ];
13170 let search_tile = |index: usize,
13171 fctx: &crate::decode::FrameCtx|
13172 -> Result<Vec<(usize, Quadrant)>> {
13173 // Thread-local, and this job may be running on a `search_tiles`
13174 // worker: `ref_distance`'s order-hint distance (the scaled motion
13175 // search step) is read by the SEARCH, so every worker arms it or the
13176 // tile's bits depend on the thread count.
13177 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
13178 crate::tile::arm_high_precision_mv(hp_mv);
13179 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
13180 let rect = layout.rect(index);
13181 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
13182 let mut chroma = [
13183 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
13184 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
13185 ];
13186 clip_planes_to_tile(&mut luma, &mut chroma, rect);
13187 let mut grid = MiGrid::new(mi_cols, mi_rows);
13188 grid.set_sign_bias(sign_bias);
13189 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
13190 // built once per tile job (`obmc_prediction`).
13191 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
13192 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
13193 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
13194 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
13195 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
13196 grid.set_tile_bounds(
13197 rect.mi_row0 as usize,
13198 rect.mi_col0 as usize,
13199 rect.mi_row1 as usize,
13200 rect.mi_col1 as usize,
13201 );
13202 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
13203 // lane-b128: under a 128x128 superblock the search walks the roots the
13204 // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
13205 // not plain raster -- a search that visits BL before TR builds every mv
13206 // stack and neighbour context off blocks the writer has not coded yet,
13207 // which is what made the write-time drl clamp fire at all (lane-sb128b).
13208 // At a 64 superblock the two orders are identical and this is the same
13209 // raster loop as before.
13210 let sb128_search = sb128_on();
13211 let root_step = if sb128_search { 2 } else { 1 };
13212 let mut roots: Vec<(usize, usize)> = Vec::new();
13213 {
13214 let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
13215 let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
13216 let mut r = r0;
13217 while r < r1 {
13218 let mut c = c0;
13219 while c < c1 {
13220 roots.push((r, c));
13221 c += root_step;
13222 }
13223 r += root_step;
13224 }
13225 }
13226 for (root_r, root_c) in roots {
13227 // The 64x64 cells of this root, in the writer's own order.
13228 let cells: Vec<(usize, usize)> = if sb128_search {
13229 [(0, 0), (0, 1), (1, 0), (1, 1)]
13230 .into_iter()
13231 .map(|(dr, dc)| (root_r + dr, root_c + dc))
13232 .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
13233 .collect()
13234 } else {
13235 vec![(root_r, root_c)]
13236 };
13237 // What the four cells below really cost, against which the whole
13238 // 128x128 candidate is weighed.
13239 let mark128 = blocks.len();
13240 let mut root_cost = 0.0f64;
13241 // The 128 root's own compound pairs, at its 32x32-mi window (the 64
13242 // root builds the same list one size down, per superblock).
13243 let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13244 if header.reference_select && b128_compound() && !screen && sb128_search {
13245 [
13246 (crate::mvstack::GOLDEN_FRAME, golden),
13247 (crate::mvstack::ALTREF_FRAME, altref),
13248 ]
13249 .into_iter()
13250 .filter_map(|(r, pic)| {
13251 pic.map(|p| {
13252 (
13253 r,
13254 p,
13255 crate::mvstack::find_mv_stack_compound(
13256 &grid,
13257 root_r * 16,
13258 root_c * 16,
13259 32,
13260 32,
13261 (crate::mvstack::LAST_FRAME, r),
13262 mi_cols,
13263 mi_rows,
13264 grid.sign_bias_table(),
13265 &[(0, 0); 7],
13266 None,
13267 ),
13268 )
13269 })
13270 })
13271 .collect()
13272 } else {
13273 Vec::new()
13274 };
13275 let root128 = (sb128_search && b128_root() && cells.len() == 4)
13276 .then(|| search_root_128(
13277 &mut luma,
13278 &mut chroma,
13279 &grid,
13280 (root_r, root_c),
13281 (rows, cols),
13282 (header.mi_cols, header.mi_rows),
13283 search,
13284 &tpl_factors,
13285 sb_q.as_ref(),
13286 sb_cols,
13287 tpl_cells_x,
13288 base_q_idx,
13289 dq_res,
13290 reference,
13291 &root_compound,
13292 fctx,
13293 ))
13294 .flatten();
13295 // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
13296 // are priced; the cheaper one competes with the NONE block and with
13297 // the four superblocks below.
13298 let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
13299 let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
13300 .then(|| {
13301 let mut best: Option<(bool, _)> = None;
13302 for horz in [true, false] {
13303 if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
13304 continue;
13305 }
13306 let Some(found) = search_root_128_rect(
13307 &mut luma,
13308 &mut chroma,
13309 &mut grid,
13310 (root_r, root_c),
13311 (rows, cols),
13312 (header.mi_cols, header.mi_rows),
13313 search,
13314 &tpl_factors,
13315 sb_q.as_ref(),
13316 sb_cols,
13317 tpl_cells_x,
13318 base_q_idx,
13319 dq_res,
13320 reference,
13321 &root_compound,
13322 horz,
13323 fctx,
13324 ) else {
13325 continue;
13326 };
13327 if best.as_ref().is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) {
13328 best = Some((horz, found));
13329 }
13330 }
13331 best
13332 })
13333 .flatten();
13334 // lane-ab128: and the same root as one of the four AB shapes -- two
13335 // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
13336 // the cheapest joins the candidate list below.
13337 let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
13338 let root_ab = (sb128_search
13339 && (b128_ab() || forced_ab != 0)
13340 && cells.len() == 4
13341 && forced_rect == 0)
13342 .then(|| {
13343 let mut best: Option<(usize, _)> = None;
13344 for symbol in 4..=7usize {
13345 if forced_ab != 0 && usize::from(forced_ab) != symbol {
13346 continue;
13347 }
13348 let Some(found) = search_root_128_ab(
13349 &mut luma,
13350 &mut chroma,
13351 &mut grid,
13352 (root_r, root_c),
13353 (rows, cols),
13354 (header.mi_cols, header.mi_rows),
13355 search,
13356 &tpl_factors,
13357 sb_q.as_ref(),
13358 sb_cols,
13359 tpl_cells_x,
13360 base_q_idx,
13361 reference,
13362 &root_compound,
13363 symbol,
13364 fctx,
13365 ) else {
13366 continue;
13367 };
13368 if best.as_ref().is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0) {
13369 best = Some((symbol, found));
13370 }
13371 }
13372 best
13373 })
13374 .flatten();
13375 for (sb_r, sb_c) in cells {
13376 // lane-b64: the whole superblock as ONE 64x64 block, tried before
13377 // its quadrants are (`search_skip_64`) and compared against the
13378 // four of them below. Only a superblock wholly inside the true
13379 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
13380 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
13381 // only that the block's half is inside, and the trial is ranked
13382 // over the inside part alone ([`Plane::block_sse`]).
13383 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
13384 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
13385 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
13386 && x64 + SUPERBLOCK <= luma.true_width
13387 && y64 + SUPERBLOCK <= luma.true_height;
13388 let edge_inside = b64_edge()
13389 && crate::tile::has_half(
13390 sb_c as u32 * crate::tile::SB_MI,
13391 crate::tile::SB_MI,
13392 header.mi_cols,
13393 )
13394 && crate::tile::has_half(
13395 sb_r as u32 * crate::tile::SB_MI,
13396 crate::tile::SB_MI,
13397 header.mi_rows,
13398 );
13399 let sb64_legal = b64_root()
13400 && sb_r * 2 + 1 < rows
13401 && sb_c * 2 + 1 < cols
13402 && (whole_inside || edge_inside);
13403 // One lambda for the whole superblock, the same mean the 32x32
13404 // level takes over its own four tpl cells: the 64-vs-four-32
13405 // comparison below weighs one cost against four, so both sides
13406 // have to be priced at the same lambda.
13407 let sb_search = match &tpl_factors {
13408 // lane-deltaq: with a per-superblock quantizer the lambda
13409 // comes from that quantizer, not from the raw map factor --
13410 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
13411 Some(_) if sb_q.is_some() => sb_q_search(sb_q.as_ref().expect("armed"), sb_cols, base_q_idx, (sb_r, sb_c), search),
13412 Some(f) if sb64_legal => {
13413 let mean = (0..16)
13414 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
13415 .sum::<f64>()
13416 / 16.0;
13417 Search { lambda: search.lambda * mean, ..search }
13418 }
13419 _ => search,
13420 };
13421 let mark = blocks.len();
13422 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
13423 let mut sb_cost = 0.0f64;
13424 if sb64_legal {
13425 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
13426 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
13427 let stack =
13428 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
13429 // lane-b64b: the `LAST` + extra-reference pairs at this
13430 // superblock's own 16x16-mi window, the same stacks the tile
13431 // writer's `Whole64` arm rebuilds. Empty unless the frame
13432 // codes `reference_select`, which is what gates the syntax.
13433 // `!screen` for the same reason the residual arm is gated
13434 // there ([`b64_residual`]): a desktop capture's superblocks
13435 // are flat runs the skip arm already codes for nothing, and
13436 // MEASURED, compound at the root cost it +33.4/-23.8 ->
13437 // +33.7/-23.6 while both film rows gained (step 1's table).
13438 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13439 if header.reference_select && b64_compound() && !screen {
13440 [
13441 (crate::mvstack::GOLDEN_FRAME, golden),
13442 (crate::mvstack::ALTREF_FRAME, altref),
13443 ]
13444 .into_iter()
13445 .filter_map(|(r, pic)| {
13446 pic.map(|p| {
13447 (
13448 r,
13449 p,
13450 crate::mvstack::find_mv_stack_compound(
13451 &grid,
13452 mi_row,
13453 mi_col,
13454 16,
13455 16,
13456 (crate::mvstack::LAST_FRAME, r),
13457 mi_cols,
13458 mi_rows,
13459 grid.sign_bias_table(),
13460 &[(0, 0); 7],
13461 None,
13462 ),
13463 )
13464 })
13465 })
13466 .collect()
13467 } else {
13468 Vec::new()
13469 };
13470 if let Some((cost, block)) = search_skip_64(
13471 &mut luma,
13472 &mut chroma,
13473 (x64, y64),
13474 (SUPERBLOCK, SUPERBLOCK),
13475 &sb_search,
13476 b64_residual() && !screen,
13477 reference,
13478 &stack,
13479 &sb_compound,
13480 fctx,
13481 ) {
13482 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
13483 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
13484 let cost = cost
13485 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
13486 sb64 = Some((cost, block, after));
13487 }
13488 }
13489 // A superblock whose 64x64 trial already codes almost nothing per
13490 // pixel is taken outright and its quadrants are never searched --
13491 // the same `split_rd_breakout` shape the 32x32 level uses one
13492 // size up, and where this lever BUYS wall instead of spending it.
13493 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
13494 split_rd_breakout_at(
13495 b64_breakout_threshold(),
13496 *c,
13497 SUPERBLOCK,
13498 sb_search.lambda,
13499 )
13500 });
13501 for quadrant in 0..if early64 { 0 } else { 4 } {
13502 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
13503 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
13504 // decision under it (partition, mode, tx, motion) reads
13505 // `search.lambda`, so scaling the one field here scales all
13506 // of them. 32x32 and not the 16x16 the map is built at
13507 // because the whole-vs-split comparison right below weighs
13508 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
13509 // would make those two numbers incomparable.
13510 let search = match &tpl_factors {
13511 // lane-deltaq: the quantizer is a SUPERBLOCK-level
13512 // symbol, so all four quadrants take their superblock's
13513 // own qindex and the lambda it implies. No granularity is
13514 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
13515 // factor per superblock, shared by its sixteen cells.
13516 Some(_) if sb_q.is_some() => sb_q_search(sb_q.as_ref().expect("armed"), sb_cols, base_q_idx, (sb_r, sb_c), search),
13517 Some(f) => {
13518 let mean = (0..4)
13519 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
13520 .sum::<f64>()
13521 / 4.0;
13522 Search { lambda: search.lambda * mean, ..search }
13523 }
13524 None => search,
13525 };
13526 // Same filter as the tile writer's: a quadrant whose own mi
13527 // origin is not inside the true frame is never coded.
13528 if r32 >= rows || c32 >= cols {
13529 continue;
13530 }
13531 // spec `decode_partition`'s hasRows/hasCols recomputed at this
13532 // 32x32 block's own half (`crate::tile::has_half`), same as
13533 // the key frame search: the true frame edge can fall inside a
13534 // quadrant a superblock-level check already let through, and
13535 // such a quadrant cannot be left whole -- it must split into
13536 // the 16x16 leaves that are actually inside the true frame
13537 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
13538 // arm).
13539 let (has_cols32, has_rows32) = (
13540 crate::tile::has_half(
13541 c32 as u32 * crate::tile::BLOCK_MI,
13542 crate::tile::BLOCK_MI,
13543 header.mi_cols,
13544 ),
13545 crate::tile::has_half(
13546 r32 as u32 * crate::tile::BLOCK_MI,
13547 crate::tile::BLOCK_MI,
13548 header.mi_rows,
13549 ),
13550 );
13551 if has_cols32 && has_rows32 {
13552 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
13553 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
13554 let stack =
13555 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
13556 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
13557 (crate::mvstack::LAST2_FRAME, last2),
13558 (crate::mvstack::GOLDEN_FRAME, golden),
13559 (crate::mvstack::ALTREF_FRAME, altref),
13560 ]
13561 .into_iter()
13562 .filter_map(|(r, pic)| {
13563 pic.map(|p| {
13564 (
13565 r,
13566 p,
13567 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
13568 )
13569 })
13570 })
13571 .collect();
13572 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
13573 .iter()
13574 .map(|(r, p, st)| (*r, *p, st))
13575 .collect();
13576 // The COMPOUND stack of each `LAST` + extra pair, off the
13577 // same grid (and the same armed sign bias) the tile writer
13578 // rebuilds it from. Empty unless this frame codes
13579 // `reference_select`, which is what gates the syntax.
13580 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13581 if header.reference_select {
13582 extra_stacks
13583 .iter()
13584 .map(|&(r, p, _)| {
13585 (
13586 r,
13587 p,
13588 crate::mvstack::find_mv_stack_compound(
13589 &grid,
13590 mi_row,
13591 mi_col,
13592 8,
13593 8,
13594 (crate::mvstack::LAST_FRAME, r),
13595 mi_cols,
13596 mi_rows,
13597 grid.sign_bias_table(),
13598 &[(0, 0); 7],
13599 None,
13600 ),
13601 )
13602 })
13603 .collect()
13604 } else {
13605 Vec::new()
13606 };
13607
13608 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
13609 let (block, mut cost_whole) = search_inter_block(
13610 &mut luma,
13611 &mut chroma,
13612 (x, y),
13613 &search,
13614 &mode_bits_table,
13615 reference,
13616 &stack,
13617 &extra,
13618 &compound,
13619 &grid,
13620 (mi_row, mi_col),
13621 (mi_rows, mi_cols),
13622 fctx,
13623 );
13624 cost_whole += search.lambda * partition_bits(BLOCK, false);
13625 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
13626
13627 // What four 16x16 leaves cost instead (spec
13628 // PARTITION_SPLIT at BLOCK_32X32, which
13629 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
13630 // already writes for a straddling quadrant). Each leaf is
13631 // searched against the reconstruction -- and the `mi`
13632 // grid -- the ones before it left, exactly as the writer
13633 // and the decoder will read them.
13634 //
13635 // A block the whole-32 search left skipped (no residual
13636 // at all) is not offered the split: libaom prunes the
13637 // same way at cpu-used 6, and it is where the wall would
13638 // otherwise go on static content.
13639 let leaf_positions: Vec<(usize, usize)> = (0..4)
13640 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
13641 .collect();
13642 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
13643 crate::tile::has_half(
13644 sc as u32 * crate::tile::SUB_MI,
13645 crate::tile::SUB_MI,
13646 header.mi_cols,
13647 ) && crate::tile::has_half(
13648 sr as u32 * crate::tile::SUB_MI,
13649 crate::tile::SUB_MI,
13650 header.mi_rows,
13651 )
13652 });
13653 // The breakout above: a 32x32 block that codes almost
13654 // nothing is not offered the split at all.
13655 let breakout = split_breakout_coeffs();
13656 let split = (!block.skip
13657 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
13658 && (breakout == 0 || block.luma.len() > 4 * breakout)
13659 && leaves_legal
13660 && split_inter_blocks())
13661 .then(|| {
13662 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
13663 let mut cost = search.lambda * partition_bits(BLOCK, true);
13664 let mut leaves = Vec::with_capacity(4);
13665 for &(sr, sc) in &leaf_positions {
13666 let (mi_row, mi_col) = (sr * 4, sc * 4);
13667 let (lx, ly) = (sc * SUB, sr * SUB);
13668 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
13669 let stack = find_mv_stack(
13670 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
13671 );
13672 let cstacks = leaf_compound_stacks(
13673 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
13674 header.reference_select, golden, altref,
13675 );
13676 let (leaf, leaf_cost) = code_square_inter(
13677 &mut luma,
13678 &mut chroma,
13679 (lx, ly),
13680 SUB,
13681 &search,
13682 &mode_bits_table,
13683 reference,
13684 &stack,
13685 &cstacks,
13686 &grid,
13687 (mi_row, mi_col),
13688 (mi_rows, mi_cols),
13689 &obmc_refs,
13690 fctx,
13691 );
13692 let leaf_cost = leaf_cost
13693 + search.lambda * partition_bits(SUB, false);
13694 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
13695
13696 // And what four 8x8 leaves cost instead --
13697 // the same tree one step further down, which
13698 // the writer codes as a real PARTITION_SPLIT
13699 // at BLOCK_16X16 (lane-av1rd2). Same
13700 // skipped-block prune as the level above.
13701 let eight = (!leaf.skip
13702 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
13703 && (breakout == 0 || leaf.luma.len() > breakout)
13704 && split_inter_8()
13705 // lane-arfmode: arm 2 makes 16x16 the top
13706 // ARF's leaf floor -- the RD-optional 8x8
13707 // comparison is not offered. Counted only
13708 // when every other prune let it through,
13709 // so the counter means "refused", not
13710 // "never considered". The spec-forced 8x8s
13711 // at a straddling 16x16 (the
13712 // `sub_positions` path below) are a
13713 // different site and stay.
13714 && (search.arf_leaf8 || arfmode_hit_and_no()))
13715 .then(|| {
13716 restore(
13717 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
13718 );
13719 let mut cost8 = search.lambda
13720 * (partition_bits(SUB, true)
13721 + 4.0 * partition_bits(8, false));
13722 let mut eight = Vec::with_capacity(4);
13723 for i in 0..4 {
13724 let (mr, mc) =
13725 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
13726 let stack8 = find_mv_stack(
13727 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
13728 );
13729 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13730 if header.reference_select && leaf_compound() {
13731 [
13732 (crate::mvstack::GOLDEN_FRAME, golden),
13733 (crate::mvstack::ALTREF_FRAME, altref),
13734 ]
13735 .into_iter()
13736 .filter_map(|(r, pic)| {
13737 pic.map(|p| {
13738 (
13739 r,
13740 p,
13741 crate::mvstack::find_mv_stack_compound(
13742 &grid, mr, mc, 2, 2,
13743 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
13744 grid.sign_bias_table(), &[(0, 0); 7], None,
13745 ),
13746 )
13747 })
13748 })
13749 .collect()
13750 } else {
13751 Vec::new()
13752 };
13753 let (leaf8, cost) = code_square_inter(
13754 &mut luma,
13755 &mut chroma,
13756 (lx + (i % 2) * 8, ly + (i / 2) * 8),
13757 8,
13758 &search,
13759 &mode_bits_table,
13760 reference,
13761 &stack8,
13762 &cstacks8,
13763 &grid,
13764 (mr, mc),
13765 (mi_rows, mi_cols),
13766 &obmc_refs,
13767 fctx,
13768 );
13769 cost8 += cost;
13770 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
13771 eight.push(leaf8);
13772 }
13773 (eight, cost8)
13774 });
13775 match eight {
13776 Some((eight, cost8)) if cost8 < leaf_cost => {
13777 partition_hit(3);
13778 cost += cost8;
13779 leaves.push(BlockCoeffs {
13780 eight: Some(eight),
13781 ..BlockCoeffs::default()
13782 });
13783 continue;
13784 }
13785 Some(_) => restore(
13786 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
13787 ),
13788 None => {}
13789 }
13790 partition_hit(2);
13791 cost += leaf_cost;
13792 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
13793 leaves.push(leaf);
13794 }
13795 (leaves, cost)
13796 });
13797 if let Some((leaves, cost)) = split {
13798 if cost < cost_whole {
13799 // The leaves' own `mi` cells are already in the
13800 // grid, and their reconstruction is what the
13801 // planes hold.
13802 partition_hit(1);
13803 sb_cost += cost;
13804 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
13805 continue;
13806 }
13807 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
13808 }
13809 partition_hit(0);
13810 sb_cost += cost_whole;
13811 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
13812 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
13813 } else {
13814 // The sub-positions actually inside the true frame, same
13815 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
13816 let sub_positions: Vec<(usize, usize)> = (0..4)
13817 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
13818 .filter(|&(sr, sc)| {
13819 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
13820 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
13821 })
13822 .collect();
13823 // Each leaf searches intra against its own `NEARESTMV`
13824 // candidate (`code_square_inter`), same real-inter choice
13825 // `search_inter_block` makes for a whole 32x32 block, at
13826 // this leaf's own 4x4-mi mv-stack window -- unless the
13827 // leaf's own half itself straddles the true edge, which
13828 // it codes as two (or one, at a true corner) 8x8 leaves
13829 // (`crate::tile::write_leaf8`'s inter counterpart),
13830 // mirroring the key frame search's straddling-16x16
13831 // handling above (lane-av1inter8).
13832 let mut leaves = Vec::with_capacity(sub_positions.len());
13833 for (sr, sc) in sub_positions {
13834 let (has_cols16, has_rows16) = (
13835 crate::tile::has_half(
13836 sc as u32 * crate::tile::SUB_MI,
13837 crate::tile::SUB_MI,
13838 header.mi_cols,
13839 ),
13840 crate::tile::has_half(
13841 sr as u32 * crate::tile::SUB_MI,
13842 crate::tile::SUB_MI,
13843 header.mi_rows,
13844 ),
13845 );
13846 if has_cols16 && has_rows16 {
13847 let (x, y) = (sc * SUB, sr * SUB);
13848 let (mi_row, mi_col) = (sr * 4, sc * 4);
13849 let stack = find_mv_stack(
13850 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
13851 );
13852 let cstacks = leaf_compound_stacks(
13853 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
13854 header.reference_select, golden, altref,
13855 );
13856 let (block, _) = code_square_inter(
13857 &mut luma,
13858 &mut chroma,
13859 (x, y),
13860 SUB,
13861 &search,
13862 &mode_bits_table,
13863 reference,
13864 &stack,
13865 &cstacks,
13866 &grid,
13867 (mi_row, mi_col),
13868 (mi_rows, mi_cols),
13869 &obmc_refs,
13870 fctx,
13871 );
13872 // One publication point for every coded leaf
13873 // (`record_mi`): this site used to spell the vote
13874 // out with `ref_frame` pinned to LAST and `mv1`
13875 // to (0,0), which is the encoder-grid-drift class
13876 // -- correct only for as long as a leaf can never
13877 // be compound.
13878 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
13879 leaves.push(block);
13880 } else {
13881 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
13882 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
13883 let mut eight = Vec::with_capacity(2);
13884 for i in 0..4 {
13885 let leaf_x = x_sub + (i % 2) * 8;
13886 let leaf_y = y_sub + (i / 2) * 8;
13887 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
13888 continue;
13889 }
13890 let (mi_row, mi_col) =
13891 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
13892 let stack = find_mv_stack(
13893 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
13894 );
13895 let cstacks = leaf_compound_stacks(
13896 &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows,
13897 header.reference_select, golden, altref,
13898 );
13899 let (leaf, _) = code_square_inter(
13900 &mut luma,
13901 &mut chroma,
13902 (leaf_x, leaf_y),
13903 8,
13904 &search,
13905 &mode_bits_table,
13906 reference,
13907 &stack,
13908 &cstacks,
13909 &grid,
13910 (mi_row, mi_col),
13911 (mi_rows, mi_cols),
13912 &obmc_refs,
13913 fctx,
13914 );
13915 // Same publication point as the 16x16
13916 // straddling leaf above (`record_mi`).
13917 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
13918 eight.push(leaf);
13919 }
13920 leaves.push(BlockCoeffs {
13921 eight: Some(eight),
13922 ..BlockCoeffs::default()
13923 });
13924 }
13925 }
13926 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
13927 }
13928 }
13929 // The 64x64 root against what its four quadrants really cost.
13930 if let Some((cost64, block, after)) = sb64
13931 && (early64
13932 || cost64
13933 < sb_cost
13934 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
13935 {
13936 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13937 if block.inter.is_some_and(|i| i.ref1.is_some()) {
13938 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13939 }
13940 if !whole_inside {
13941 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13942 }
13943 blocks.truncate(mark);
13944 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
13945 // Overwrites every 16x16 mi cell the quadrant searches
13946 // published under this superblock, so the next block's stack
13947 // is built off the block that was really coded.
13948 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
13949 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
13950 for q in 1..4 {
13951 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
13952 blocks.push((r32 * cols + c32, Quadrant::Covered));
13953 }
13954 root_cost += cost64;
13955 } else {
13956 root_cost += sb_cost;
13957 }
13958 }
13959 // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
13960 // `partition_w128` symbol) against what its four superblocks really
13961 // cost, the same weighing the 64 root does one size down. Both sides
13962 // carry their own partition symbol, so the comparison is complete.
13963 // The root candidates, each tagged with the PARTITION symbol its
13964 // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
13965 // shapes (lane-ab128).
13966 let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
13967 if let Some((c, l, b, a)) = root128 {
13968 cands.push((c, l, 0, vec![b], a));
13969 }
13970 if let Some((horz, (c, l, halves, a))) = root_rect {
13971 cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
13972 }
13973 if let Some((symbol, (c, l, pieces, a))) = root_ab {
13974 cands.push((c, l, symbol, pieces.to_vec(), a));
13975 }
13976 // The witness knobs drop every other arm outright: on synthetic
13977 // content the whole block always wins its own comparison.
13978 if forced_rect != 0 {
13979 cands.retain(|c| c.2 == 1 || c.2 == 2);
13980 }
13981 if forced_ab != 0 {
13982 cands.retain(|c| c.2 == usize::from(forced_ab));
13983 }
13984 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
13985 // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
13986 // superblock arm codes the delta_q group too -- the Whole64 writer
13987 // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
13988 // with `!sb128_armed()`) and every smaller shape below it pass
13989 // `is_whole_sb = false` under a 128 grid, so the arm's first
13990 // (root-origin) superblock codes the group even when skipped. Only the skipped 128
13991 // NONE root escapes it, so the split side is charged here at the same
13992 // root lambda the candidates are priced with.
13993 let split_dq =
13994 delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
13995 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
13996 && (cost128
13997 < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
13998 // The witness knobs take the root whatever it costs, so the
13999 // forced block really reaches the writer.
14000 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
14001 || forced_rect != 0
14002 || forced_ab != 0)
14003 {
14004 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
14005 blocks.truncate(mark128);
14006 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
14007 let at = (root_r * 2) * cols + root_c * 2;
14008 match shape {
14009 0 => {
14010 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14011 let block = halves.into_iter().next().expect("the NONE arm's block");
14012 record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
14013 blocks.push((at, Quadrant::Whole128(block)));
14014 }
14015 // lane-ab128: three pieces, published at their own footprints
14016 // in the writer's own order ([`ab128_pieces`]).
14017 symbol @ 4..=7 => {
14018 B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14019 for (((mr, mc), (w, h)), piece) in
14020 ab128_pieces(symbol, (root_r * 16, root_c * 16)).iter().zip(&halves)
14021 {
14022 record_mi_rect(
14023 &mut grid,
14024 *mr,
14025 *mc,
14026 (w / 4, h / 4),
14027 piece.inter,
14028 piece.skip,
14029 );
14030 }
14031 blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
14032 }
14033 symbol => {
14034 let horz = symbol == 1;
14035 if horz {
14036 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14037 } else {
14038 B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14039 }
14040 let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
14041 for (i, half) in halves.iter().enumerate() {
14042 let (mr, mc) = if horz {
14043 (root_r * 16 + i * 16, root_c * 16)
14044 } else {
14045 (root_r * 16, root_c * 16 + i * 16)
14046 };
14047 record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
14048 }
14049 blocks.push((at, Quadrant::Rect128(horz, halves)));
14050 }
14051 }
14052 for q in 1..16 {
14053 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
14054 blocks.push((r32 * cols + c32, Quadrant::Covered));
14055 }
14056 }
14057 }
14058 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
14059 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
14060 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
14061 for (&out, tile) in chroma_out.iter().zip(&chroma) {
14062 copy_rect(
14063 out,
14064 &tile.reconstruction,
14065 frame_width / 2,
14066 x0 / 2,
14067 y0 / 2,
14068 x1.div_ceil(2),
14069 y1.div_ceil(2),
14070 );
14071 }
14072 Ok(blocks)
14073 };
14074 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
14075 .into_iter()
14076 .flatten()
14077 {
14078 blocks[at] = quadrant;
14079 }
14080
14081 // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
14082 // superblock roots the search left whole, so a flat BD result is
14083 // attributable (class `gate-blind-to-feature`). A key frame codes none:
14084 // only the inter writer has a 128x128 block.
14085 if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
14086 let whole = blocks
14087 .iter()
14088 .filter(|q| matches!(q, Quadrant::Whole128(_)))
14089 .count();
14090 let roots = blocks
14091 .iter()
14092 .filter(|q| !matches!(q, Quadrant::Covered))
14093 .count();
14094 // lane-b128r: of those roots, how many code a REAL residual rather
14095 // than the skip-only block lane-b128 shipped -- the fire count this
14096 // arm's own gate row is read against.
14097 let residual = blocks
14098 .iter()
14099 .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
14100 .count();
14101 // lane-b128r: and how many named a second reference (the compound
14102 // arm at the 128 root).
14103 let compound = blocks
14104 .iter()
14105 .filter(|q| {
14106 matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some()))
14107 })
14108 .count();
14109 // lane-b128hv: and how many roots took a rect cut instead, per shape
14110 // -- the HORZ/VERT fire count the gate rows are read against.
14111 let horz = blocks
14112 .iter()
14113 .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
14114 .count();
14115 let vert = blocks
14116 .iter()
14117 .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
14118 .count();
14119 let rect_compound = blocks
14120 .iter()
14121 .filter(|q| {
14122 matches!(q, Quadrant::Rect128(_, hs)
14123 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
14124 })
14125 .count();
14126 // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
14127 // .. _VERT_B order -- the per-shape fire count its gate rows are read
14128 // against.
14129 let ab: [usize; 4] = std::array::from_fn(|i| {
14130 blocks
14131 .iter()
14132 .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
14133 .count()
14134 });
14135 eprintln!(
14136 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
14137 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
14138 compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
14139 {roots} coded blocks ({:.1}% of the frame's area at 128)",
14140 ab[0],
14141 ab[1],
14142 ab[2],
14143 ab[3],
14144 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
14145 / blocks.len().max(1) as f64,
14146 );
14147 }
14148 let modes = blocks
14149 .iter()
14150 .flat_map(Quadrant::blocks)
14151 .map(|b| b.mode)
14152 .collect::<Vec<_>>();
14153 let inter_block_share = blocks
14154 .iter()
14155 .flat_map(Quadrant::blocks)
14156 .filter(|b| b.inter.is_some())
14157 .count() as f64
14158 / modes.len() as f64;
14159 for block in blocks.iter().flat_map(Quadrant::blocks) {
14160 if let Some(info) = block.inter {
14161 let r = (info.ref_frame as usize).min(7);
14162 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14163 }
14164 }
14165 #[cfg(test)]
14166 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
14167 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
14168 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
14169 // next frame's writer starts from them -- exactly what
14170 // `crate::stream::stored_cdfs_for` hands the decoder.
14171 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
14172 let mut cdfs = start_cdfs
14173 .cloned()
14174 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
14175 // lane-txi: set per frame, never inherited from the snapshot the
14176 // previous frame stored -- the content gate can flip the bit between
14177 // frames (class `per-tile-state-not-reset`).
14178 cdfs.reduced_tx_set = header.reduced_tx_set;
14179 let start_cdfs = CdfSnapshot(cdfs);
14180 let reference_select_bit = header.reference_select;
14181 let switchable_motion_mode = header.is_motion_mode_switchable;
14182 let warped_motion = header.allow_warped_motion;
14183 let order_hint_bits = seq.order_hint_bits;
14184 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
14185 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
14186 // What this frame stores is the LARGEST tile's end-of-tile tables --
14187 // its own header's `context_update_tile_id` (spec 7.20), which
14188 // `tile_info_of` set to exactly that tile.
14189 let store_tile = layout.largest_tile();
14190 let end_cdfs = std::cell::RefCell::new(None);
14191 // As in `encode_key_frame_inner`: every tile starts from this frame's
14192 // own tables, so no tile depends on any other.
14193 let code_tiles = |bits: u8,
14194 sb_cols: usize,
14195 cdef_grid: &[u8],
14196 units: &[Option<crate::restoration::WienerInfo>]|
14197 -> Result<Vec<Vec<u8>>> {
14198 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
14199 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
14200 crate::tile::arm_delta_q(
14201 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
14202 sb_cols,
14203 sb_q.clone().unwrap_or_default(),
14204 base_q_idx,
14205 );
14206 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
14207 crate::tile::arm_sb128(sb128_on());
14208 crate::tile::arm_sign_bias(sign_bias);
14209 // Thread-locals: every tile job arms its own worker.
14210 crate::tile::arm_reference_select(reference_select_bit);
14211 crate::tile::arm_motion_mode(switchable_motion_mode);
14212 crate::tile::arm_warped_motion(warped_motion);
14213 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
14214 crate::tile::arm_high_precision_mv(hp_mv);
14215 crate::tile::arm_screen(screen);
14216 crate::tile::arm_frame_mi_dims(frame_mi_dims);
14217 crate::tile::arm_filter_intra(filter_intra_on());
14218 let mut cdfs = start_cdfs.0.clone();
14219 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
14220 // Each tile's own MV grid: a candidate scan never reaches past
14221 // the tile's bounds, so a grid holding only this tile's own
14222 // blocks reads exactly as the decoder's frame-wide one does
14223 // under `MiGrid::set_tile_bounds`.
14224 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
14225 mv_grid.set_sign_bias(sign_bias);
14226 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
14227 mi_cols,
14228 mi_rows,
14229 base_q_idx,
14230 &blocks,
14231 tx_select,
14232 &mut cdfs,
14233 layout.rect(index),
14234 &mut mv_grid,
14235 )?;
14236 Ok((bytes, Some(cdfs)))
14237 })?;
14238 if let Some(cdfs) = stored {
14239 *end_cdfs.borrow_mut() = Some(cdfs);
14240 }
14241 Ok(out)
14242 };
14243 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
14244 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
14245 // this tile against the same single-slot reference this encoder predicted
14246 // from, under each candidate level.
14247 // The reference a DECODER holds is this frame's cropped size, not the
14248 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
14249 // reference whose height is not the header's own `frame_height` (spec
14250 // 7.9's compatible-size rule), and the chained-decode round trips prove
14251 // the two predict identically.
14252 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
14253 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
14254 reference.clone()
14255 } else {
14256 Picture {
14257 width: fw,
14258 height: fh,
14259 y: crop_plane(&reference.y, reference.width, fw, fh),
14260 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
14261 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
14262 }
14263 };
14264 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
14265 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
14266 // blocks may name GOLDEN needs that plane too, cropped the same way.
14267 let trial_golden = golden.map(|g| {
14268 if (g.width, g.height) == (fw, fh) {
14269 g.clone()
14270 } else {
14271 Picture {
14272 width: fw,
14273 height: fh,
14274 y: crop_plane(&g.y, g.width, fw, fh),
14275 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
14276 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
14277 }
14278 }
14279 });
14280 let trial_altref = altref.map(|a| {
14281 if (a.width, a.height) == (fw, fh) {
14282 a.clone()
14283 } else {
14284 Picture {
14285 width: fw,
14286 height: fh,
14287 y: crop_plane(&a.y, a.width, fw, fh),
14288 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
14289 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
14290 }
14291 }
14292 });
14293 let trial_last2 = last2.map(|l| {
14294 if (l.width, l.height) == (fw, fh) {
14295 l.clone()
14296 } else {
14297 Picture {
14298 width: fw,
14299 height: fh,
14300 y: crop_plane(&l.y, l.width, fw, fh),
14301 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
14302 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
14303 }
14304 }
14305 });
14306 let mut refs: [Option<&Picture>; 8] = [None; 8];
14307 refs[1] = Some(&trial_ref);
14308 refs[2] = trial_last2.as_ref();
14309 refs[4] = trial_golden.as_ref();
14310 refs[7] = trial_altref.as_ref();
14311 let refpix = crate::decode::RefPix::ready(refs);
14312 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
14313 // sum the block search believed it was minimising. Against the
14314 // post-filter per-frame PSNR the gate prints, this separates a trial
14315 // whose reconstruction is a lie from a filter stage that undoes the win.
14316 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
14317 let sse: u64 = luma
14318 .reconstruction
14319 .chunks(luma.width)
14320 .take(luma.true_height)
14321 .zip(picture_y8.chunks(luma.width))
14322 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
14323 .map(|(&r, &s)| {
14324 let d = i64::from(r) - i64::from(s);
14325 (d * d) as u64
14326 })
14327 .sum();
14328 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
14329 }
14330 let post = |luma: &Plane<'_>, tag: &str| {
14331 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
14332 return;
14333 }
14334 let sse: u64 = luma
14335 .reconstruction
14336 .chunks(luma.width)
14337 .take(luma.true_height)
14338 .zip(picture_y8.chunks(luma.width))
14339 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
14340 .map(|(&r, &s)| {
14341 let d = i64::from(r) - i64::from(s);
14342 (d * d) as u64
14343 })
14344 .sum();
14345 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
14346 };
14347 pick_and_apply_filters(
14348 &mut header,
14349 &mut luma,
14350 &mut chroma,
14351 [&picture_y8, &picture_u8, &picture_v8],
14352 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
14353 // this frame's own `tx_select`, so the search runs under inter
14354 // `TxMode::Select` too (it used to skip and leave every inter frame
14355 // unfiltered once Select became the default).
14356 true,
14357 &mut tiles,
14358 search.lambda,
14359 fctx,
14360 &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows),
14361 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
14362 // are what the NEXT frame writes from, so the winning re-code
14363 // publishes its own into `end_cdfs` -- the first write's are stale
14364 // the moment a second tile is coded.
14365 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
14366 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
14367 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
14368 crate::decode::decode_inter_frame_tiles_lr(
14369 &payloads,
14370 &header_tile_info,
14371 h.mi_cols,
14372 h.mi_rows,
14373 base_q_idx,
14374 h.frame_width,
14375 h.frame_height,
14376 &refpix,
14377 cdef,
14378 lf,
14379 h.allow_high_precision_mv,
14380 h.force_integer_mv,
14381 Some(fctx.interp_filter.get()),
14382 seq.enable_dual_filter,
14383 h.reference_select,
14384 // lane-txi: this frame's own bit, not the hardcoded `true`
14385 // the wrapper used to pass.
14386 h.reduced_tx_set,
14387 tx_select,
14388 lr,
14389 // The trial decode re-reads the tile the writer just wrote,
14390 // so it starts from the same tables the writer did (this
14391 // frame's `start_cdfs`), not from the defaults.
14392 Some(start_cdfs.0.clone()),
14393 sign_bias,
14394 h.allow_screen_content_tools,
14395 switchable_motion_mode,
14396 h.allow_warped_motion,
14397 seq.enable_filter_intra,
14398 // lane-deltaq: this frame's own delta_q/delta_lf params, so
14399 // the trial decode reads the per-superblock `delta_qindex`
14400 // syntax the writer just wrote.
14401 h.delta.clone(),
14402 fctx,
14403 )
14404 },
14405 )?;
14406 post(&luma, "EC_POSTFILTER");
14407 let mut cdfs = end_cdfs
14408 .into_inner()
14409 .unwrap_or_else(|| start_cdfs.0.clone());
14410 cdfs.reset_counts();
14411 let next_cdfs = CdfSnapshot(cdfs);
14412 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
14413 header.tile_info.tile_size_bytes = tile_size_bytes;
14414 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
14415 let mut stream = temporal_delimiter();
14416 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
14417
14418 let [u, v] = chroma;
14419 Ok(Encoded {
14420 stream,
14421 modes,
14422 inter_block_share,
14423 reconstruction: Picture {
14424 width: luma.width,
14425 height: luma.height,
14426 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14427 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14428 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14429 },
14430 tile,
14431 mi_cols: header.mi_cols,
14432 mi_rows: header.mi_rows,
14433 base_q_idx,
14434 tx_select,
14435 switchable_motion_mode,
14436 screen,
14437 reduced_tx_set: header.reduced_tx_set,
14438 start_cdfs,
14439 next_cdfs,
14440 loop_filter: header.loop_filter,
14441 cdef: header.cdef,
14442 loop_restoration: header.loop_restoration,
14443 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
14444 // intra frames only).
14445 allow_intrabc: false,
14446 delta: header.delta.clone(),
14447 })
14448}
14449
14450/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
14451/// frame's temporal unit followed by one inter frame's temporal unit per
14452/// remaining picture, all sharing the key frame's sequence header -- and
14453/// each frame's own [`Encoded`], in coding order.
14454#[derive(Clone, Debug)]
14455pub struct EncodedSequence {
14456 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
14457 /// sequence header and the key frame) followed by each later frame's
14458 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
14459 /// the sequence header the key frame carried).
14460 pub stream: Vec<u8>,
14461 /// One entry per picture, in DISPLAY order — the order a decoder outputs
14462 /// them and the order `pictures` came in. Without a pyramid that is also
14463 /// the coding order; with one the two differ, and `coding_order` is the
14464 /// map between them.
14465 pub frames: Vec<Encoded>,
14466 /// The index into `frames` of each coded frame, in CODING order — what a
14467 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
14468 /// `0..frames.len()` on the flat path.
14469 pub coding_order: Vec<usize>,
14470}
14471
14472/// Encodes a sequence of pictures as a key frame followed by one inter frame
14473/// per remaining picture, each predicting from the previous frame's own
14474/// decoded reconstruction — never from the source, which is what a decoder
14475/// cannot see. Every picture must be the same even size (any even width and
14476/// height — each is padded to a whole number of 64x64 superblocks
14477/// internally, which is what lets an inter frame's reference always match
14478/// the frame being coded against it), and `pictures` must be non-empty.
14479///
14480/// # Errors
14481/// Returns an error when `pictures` is empty, when any picture besides the
14482/// first is not the same size as the first, or under the same conditions
14483/// [`encode_key_frame`] and the inter frame path do.
14484pub(crate) fn encode_sequence_with_ctx(
14485 pictures: &[Picture],
14486 base_q_idx: u8,
14487 deadzone: f64, fctx: &crate::decode::FrameCtx,
14488) -> Result<EncodedSequence> {
14489 let Some((first, rest)) = pictures.split_first() else {
14490 return Err(Error::unsupported(
14491 "AV1 encode",
14492 "a sequence needs at least one picture",
14493 ));
14494 };
14495 first.check_even()?;
14496 let render = (first.width, first.height);
14497 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
14498 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
14499 // the leaves that predict backward off it, and a `show_existing_frame`
14500 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
14501 // an A/B. Screen content stays flat (the content gate in
14502 // `Av1Encoder::encode_frames`, whose detector this asks first so the
14503 // whole sequence path is decided in one place), and so does a run that
14504 // asks for a quantizer rounding offset the facade does not carry: the
14505 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
14506 // the ablations' -- must keep the flat path rather than be silently
14507 // ignored.
14508 //
14509 // The reordering itself is NOT reimplemented here: it is the facade's
14510 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
14511 // called with this sequence's shape, so the two paths cannot drift.
14512 let pyramid = crate::encoder::Pyramid::from_env()
14513 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
14514 .filter(|_| !picture_is_screen(first));
14515 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
14516 if let Some(pyramid) = pyramid {
14517 for picture in rest {
14518 picture.check_even()?;
14519 if (picture.width, picture.height) != render {
14520 return Err(Error::unsupported(
14521 "AV1 encode",
14522 "every picture in a sequence must be the same size as the first",
14523 ));
14524 }
14525 }
14526 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
14527 pictures,
14528 base_q_idx,
14529 pyramid,
14530 armed_tiles(),
14531 );
14532 }
14533 // The key frame and every inter frame after it are coded at the same
14534 // padded size, so the reference each inter frame predicts from -- the
14535 // previous frame's own uncropped reconstruction, at the size a decoder's
14536 // reference buffer actually holds -- always matches the frame being
14537 // coded against it.
14538 let key = encode_key_frame_inner(
14539 &first.padded_to(SUPERBLOCK),
14540 base_q_idx,
14541 deadzone,
14542 &KEY_FRAME_MODES,
14543 split_blocks(),
14544 render,
14545 unspecified_color_config(), fctx,
14546 )?;
14547 let mut stream = key.stream.clone();
14548 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
14549 // key frame refreshes every slot, each inter frame only slot 0), which is
14550 // what `GOLDEN_FRAME` names.
14551 let golden = key.reconstruction.clone();
14552 // The frame two back, once there is one that is not the key frame
14553 // itself (which `GOLDEN_FRAME` already names).
14554 let mut prev2: Option<Picture> = None;
14555 let mut carried = key.next_cdfs.clone();
14556 let mut reference = key.reconstruction.clone();
14557 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
14558 for (i, picture) in rest.iter().enumerate() {
14559 picture.check_even()?;
14560 // lane-av1tpl2: the lookahead window the per-block lambda weighting
14561 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
14562 // sources at this frame's coded (padded) size. The tail of the
14563 // sequence gets a shorter window, and the last frame none at all.
14564 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
14565 .iter()
14566 .take(tpl_depth() - 1)
14567 .map(|n| n.padded_to(SUPERBLOCK))
14568 .collect();
14569 if (picture.width, picture.height) != render {
14570 return Err(Error::unsupported(
14571 "AV1 encode",
14572 "every picture in a sequence must be the same size as the first",
14573 ));
14574 }
14575 let order_hint = (i + 1) as u32;
14576 let inter = encode_inter_frame(
14577 &picture.padded_to(SUPERBLOCK),
14578 &reference,
14579 base_q_idx,
14580 deadzone,
14581 order_hint,
14582 flat_order_hints(order_hint, 0, prev2.is_some()),
14583 render,
14584 Some(&carried.0),
14585 Some(&golden),
14586 prev2.as_ref(),
14587 None,
14588 fctx,
14589 None,
14590 &lookahead,
14591 )?;
14592 stream.extend_from_slice(&inter.stream);
14593 carried = inter.next_cdfs.clone();
14594 prev2 = Some(std::mem::replace(
14595 &mut reference,
14596 inter.reconstruction.clone(),
14597 ));
14598 frames.push(crop_encoded(&inter, render.0, render.1));
14599 }
14600 Ok(EncodedSequence {
14601 stream,
14602 coding_order: (0..frames.len()).collect(),
14603 frames,
14604 })
14605}
14606
14607#[cfg(test)]
14608mod tests {
14609
14610 /// Every (site, frame type, block side) the census can be called with
14611 /// lands in its own ten-counter bucket, inside the array (class
14612 /// `enumerate-table-domain`: an off-by-one here would silently add two
14613 /// sites' trials together).
14614 #[test]
14615 fn the_split_census_buckets_are_distinct_and_in_bounds() {
14616 let mut seen = std::collections::BTreeSet::new();
14617 for site in 0..2 {
14618 for key in [true, false] {
14619 for side in [8usize, 16, 32, 64] {
14620 let base = super::split_census_base(site, key, side);
14621 assert!(base + 10 <= super::SPLIT_CENSUS.len(), "{site} {key} {side}");
14622 assert!(seen.insert(base), "{site} {key} {side} collides");
14623 }
14624 }
14625 }
14626 assert_eq!(seen.len(), 16);
14627 }
14628
14629 /// An [`crate::mvstack::MvStack`] with every context at zero and no
14630 /// neighbours, for the pricer tests below to fill the one band each of
14631 /// them is about.
14632 /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
14633 /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
14634 /// against the same stack -- an offer the writer clamps prices the
14635 /// residual against a predictor the decoder never derives, which is the
14636 /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
14637 /// side, so the stream stays legal; here the pricer's own offer set is
14638 /// enumerated, class `enumerate-table-domain`).
14639 ///
14640 /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
14641 #[test]
14642 fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
14643 for n in 0..=4usize {
14644 let mut stack = bare_stack();
14645 for i in 0..n {
14646 stack.entries.push(crate::mvstack::StackEntry {
14647 mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
14648 weight: 1,
14649 });
14650 stack.drl_ctx.push(0);
14651 }
14652 stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
14653 stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
14654 stack.pred_mv = stack.nearest_mv;
14655 // Aim the vector at each entry in turn, so every index the offer
14656 // set holds is the one that wins at least once.
14657 for target in 0..n.max(1) {
14658 let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
14659 let (_, idx) = best_new_mv_syntax(&stack, mv)
14660 .expect("a zero residual is always codable");
14661 let idx = usize::from(idx);
14662 assert_eq!(
14663 crate::tile::signalled_drl_idx(n, 0, idx),
14664 idx,
14665 "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
14666 );
14667 }
14668 // The NEARMV arm's own offer set (`search_inter_block`,
14669 // `search_skip_64`): indices 1 and 2, offered only when the stack
14670 // really holds that entry.
14671 for idx in 1..=2usize {
14672 if stack.entries.get(idx).is_some() {
14673 assert_eq!(
14674 crate::tile::signalled_drl_idx(n, 1, idx),
14675 idx,
14676 "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
14677 );
14678 }
14679 }
14680 }
14681 }
14682
14683 fn bare_stack() -> crate::mvstack::MvStack {
14684 crate::mvstack::MvStack {
14685 entries: Default::default(),
14686 nearest_mv: (0, 0),
14687 near_mv: (0, 0),
14688 pred_mv: (0, 0),
14689 new_mv_ctx: 0,
14690 ref_mv_ctx: 0,
14691 zero_mv_ctx: 0,
14692 drl_ctx: Default::default(),
14693 above_refs: (None, None),
14694 left_refs: (None, None),
14695 above_nbr: None,
14696 left_nbr: None,
14697 above_skip: false,
14698 left_skip: false,
14699 }
14700 }
14701
14702 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
14703 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
14704 /// own neighbour-derived context. Red before lane-ctx, where the pricer
14705 /// spent four constants at CDF row 0 that assumed the pair was
14706 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
14707 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
14708 #[test]
14709 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
14710 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
14711 use crate::encode::symbol_bits as b;
14712 use crate::mvstack::{
14713 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
14714 LAST_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
14715 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
14716 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
14717 };
14718 // (pair, unidirectional?, the tree's symbols as (table, p index,
14719 // context selector, value)) -- transcribed from the writer.
14720 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
14721 type Sym = (char, usize, usize, usize);
14722 let cases: [((i8, i8), bool, &[Sym]); 7] = [
14723 ((LAST_FRAME, LAST2_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 0)]),
14724 (
14725 (LAST_FRAME, LAST3_FRAME),
14726 true,
14727 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
14728 ),
14729 (
14730 (LAST_FRAME, GOLDEN_FRAME),
14731 true,
14732 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
14733 ),
14734 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
14735 (
14736 (LAST_FRAME, ALTREF_FRAME),
14737 false,
14738 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
14739 ),
14740 (
14741 (LAST_FRAME, BWDREF_FRAME),
14742 false,
14743 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 0)],
14744 ),
14745 (
14746 (LAST_FRAME, ALTREF2_FRAME),
14747 false,
14748 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 1)],
14749 ),
14750 ];
14751 let nbr = |ref0, ref1: Option<i8>| {
14752 Some(NeighbourRef {
14753 is_inter: true,
14754 ref0,
14755 ref1,
14756 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
14757 })
14758 };
14759 // No neighbours (every context zero), then a mixed pair that puts the
14760 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
14761 for (above_nbr, left_nbr, above_refs, left_refs) in [
14762 (None, None, (None, None), (None, None)),
14763 (
14764 nbr(LAST_FRAME, None),
14765 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
14766 (Some(LAST_FRAME), None),
14767 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
14768 ),
14769 ] {
14770 let stack = crate::mvstack::MvStack {
14771 above_nbr,
14772 left_nbr,
14773 above_refs,
14774 left_refs,
14775 ..bare_stack()
14776 };
14777 let (a, a1) = above_refs;
14778 let (l, l1) = left_refs;
14779 let ctx_of = |sel: usize| match sel {
14780 1 => single_ref_p1_ctx(a, a1, l, l1),
14781 2 => single_ref_p2_ctx(a, a1, l, l1),
14782 3 => single_ref_p3_ctx(a, a1, l, l1),
14783 4 => single_ref_p4_ctx(a, a1, l, l1),
14784 5 => single_ref_p5_ctx(a, a1, l, l1),
14785 6 => single_ref_p6_ctx(a, a1, l, l1),
14786 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
14787 };
14788 for (pair, unidir, symbols) in cases {
14789 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
14790 + b(
14791 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
14792 usize::from(!unidir),
14793 );
14794 for &(table, p, sel, v) in symbols {
14795 let row = ctx_of(sel);
14796 want += match table {
14797 'u' => b(&UNI_COMP_REF[row][p], v),
14798 'c' => b(&COMP_REF[row][p], v),
14799 _ => b(&COMP_BWDREF[row][p], v),
14800 };
14801 }
14802 let got = super::compound_ref_bits(pair, &stack);
14803 assert!(
14804 (got - want).abs() < 1e-9,
14805 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
14806 priced {got} bits, writer codes {want}"
14807 );
14808 }
14809 }
14810 }
14811
14812 /// The `skip` and `is_inter` symbols are priced at the SAME context
14813 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
14814 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
14815 /// on every neighbour configuration whose context is not zero (class
14816 /// pricer-context-zero).
14817 #[test]
14818 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
14819 use crate::cdf::{INTRA_INTER, SKIP};
14820 use crate::encode::symbol_bits as b;
14821 use crate::mvstack::NeighbourRef;
14822 let nbr = |is_inter| NeighbourRef {
14823 is_inter,
14824 ref0: if is_inter { crate::mvstack::LAST_FRAME } else { 0 },
14825 ref1: None,
14826 uni: false,
14827 };
14828 for (above, left, above_skip, left_skip) in [
14829 (None, None, false, false),
14830 (Some(nbr(true)), Some(nbr(true)), true, false),
14831 (Some(nbr(false)), Some(nbr(false)), true, true),
14832 (Some(nbr(false)), None, false, true),
14833 (None, Some(nbr(true)), true, true),
14834 ] {
14835 let stack = crate::mvstack::MvStack {
14836 above_nbr: above,
14837 left_nbr: left,
14838 above_skip,
14839 left_skip,
14840 ..bare_stack()
14841 };
14842 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
14843 let ii_ctx = crate::tile::intra_inter_ctx(
14844 above.is_some(),
14845 left.is_some(),
14846 above.is_some_and(|n| n.is_inter),
14847 left.is_some_and(|n| n.is_inter),
14848 );
14849 for v in [false, true] {
14850 let (got, want) = (
14851 super::skip_bits_at(&stack, v),
14852 b(&SKIP[skip_ctx], usize::from(v)),
14853 );
14854 assert!(
14855 (got - want).abs() < 1e-9,
14856 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
14857 );
14858 let (got, want) = (
14859 super::intra_inter_bits_at(&stack, v),
14860 b(&INTRA_INTER[ii_ctx], usize::from(v)),
14861 );
14862 assert!(
14863 (got - want).abs() < 1e-9,
14864 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
14865 );
14866 }
14867 }
14868 }
14869
14870 /// [`super::single_ref_bits`] pays exactly what tile.rs'
14871 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
14872 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
14873 /// the context that symbol's own `single_ref_p*_ctx` derives from the
14874 /// block's above/left neighbours. Red before lane-pricer, where every
14875 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
14876 #[test]
14877 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
14878 use crate::cdf::SINGLE_REF as SR;
14879 use crate::encode::symbol_bits as b;
14880 use crate::mvstack::{
14881 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
14882 LAST_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
14883 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
14884 };
14885 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
14886 above_refs,
14887 left_refs,
14888 above_nbr,
14889 left_nbr,
14890 ..bare_stack()
14891 };
14892 let nbr = |ref0, ref1| {
14893 Some(crate::mvstack::NeighbourRef { is_inter: true, ref0, ref1, uni: false })
14894 };
14895 // (reference, the symbols `write_single_ref` emits as (p index, value))
14896 let cases: [(i8, &[(usize, usize)]); 7] = [
14897 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
14898 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
14899 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
14900 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
14901 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
14902 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
14903 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
14904 ];
14905 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
14906 // that puts every p* context on a different row -- the second with a
14907 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
14908 // off row 0.
14909 for (above_refs, left_refs, above_nbr, left_nbr) in [
14910 ((None, None), (None, None), None, None),
14911 (
14912 (Some(LAST_FRAME), None),
14913 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
14914 nbr(LAST_FRAME, None),
14915 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
14916 ),
14917 ] {
14918 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
14919 let (a, a1) = above_refs;
14920 let (l, l1) = left_refs;
14921 let ctx_of = |p: usize| match p {
14922 0 => single_ref_p1_ctx(a, a1, l, l1),
14923 1 => single_ref_p2_ctx(a, a1, l, l1),
14924 2 => single_ref_p3_ctx(a, a1, l, l1),
14925 3 => single_ref_p4_ctx(a, a1, l, l1),
14926 4 => single_ref_p5_ctx(a, a1, l, l1),
14927 _ => single_ref_p6_ctx(a, a1, l, l1),
14928 };
14929 for (ref_frame, symbols) in cases {
14930 // Plus the `comp_mode = 0` symbol the writer codes ahead of
14931 // the reference syntax on a `reference_select` frame.
14932 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
14933 if super::reference_select() {
14934 want += b(
14935 &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(
14936 above_nbr, left_nbr,
14937 )],
14938 0,
14939 );
14940 }
14941 let got = super::single_ref_bits(ref_frame, &stack);
14942 assert!(
14943 (got - want).abs() < 1e-9,
14944 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
14945 priced {got} bits, writer codes {want}"
14946 );
14947 }
14948 }
14949 }
14950
14951 /// lane-av1tpl2's propagated map, on the two properties every decision
14952 /// under it rests on: a frame the whole lookahead window repeats exactly
14953 /// (uniform texture) leans on every cell alike, so every factor is 1 and
14954 /// the weighting is a no-op; and where the window really does save bits
14955 /// by predicting -- the textured half of a frame whose other half is
14956 /// flat -- the factor FALLS below 1, i.e. that half is coded more
14957 /// distortion-averse than the half nothing gains from.
14958 /// The distortion metric itself (lane-sse): a block the true frame edge
14959 /// cuts through is scored over its INSIDE part only, so a difference that
14960 /// lives entirely in the padding costs nothing and a block wholly past
14961 /// the edge scores zero. Before this, the search ranked modes,
14962 /// transforms and partition trees on samples the display crop throws
14963 /// away -- which lane-b64b had fixed for the 64x64 root alone.
14964 #[test]
14965 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
14966 // A 40x40 true frame on a 64x64 padded coding surface.
14967 let source = vec![10u8; 64 * 64];
14968 let plane = fresh_plane(&source, 64, 64, 40, 40);
14969 let mut reconstruction = vec![10u8; 64 * 64];
14970 // Off by 190 at (50, 50) -- past the true edge in both axes.
14971 reconstruction[50 * 64 + 50] = 200;
14972 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored");
14973 // Off by 10 at (39, 39) -- the last sample the decoder shows.
14974 reconstruction[39 * 64 + 39] = 20;
14975 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored");
14976 // A 16x16 block whose every sample is padding.
14977 let block = vec![200u8; 16 * 16];
14978 assert_eq!(plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored");
14979 // A 16x16 block the edge cuts: 8 of its columns are inside.
14980 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
14981 }
14982
14983 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
14984 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
14985 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
14986 #[test]
14987 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
14988 let (base, res) = (162u8, 4i32);
14989 let rf = 2.0;
14990 // A superblock the window leans on more than the frame average is
14991 // coded FINER (lower qindex); a slack one coarser; the average one
14992 // exactly at the base.
14993 assert!(super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, "leaned-on SB must go finer");
14994 assert!(super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, "idle SB must go coarser");
14995 assert_eq!(super::deltaq_libaom(base, rf, rf, 1.0, res), base, "the average SB moves 0");
14996 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
14997 let max = ((res * 9 - 1) / res) * res;
14998 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
14999 for k in [0.5f64, 1.0, 1.5] {
15000 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
15001 let d = q - i32::from(base);
15002 assert_eq!(d % res, 0, "r={r} k={k}: offset {d} is not a whole {res}-step");
15003 assert!(d.abs() <= max, "r={r} k={k}: offset {d} past libaom's +-{max}");
15004 }
15005 }
15006 // The clamp is REACHED from both ends, so the bound is a real bound
15007 // and not a formula that never gets there.
15008 assert_eq!(i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), -max);
15009 assert_eq!(i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), max);
15010 // A stronger `k` never moves less than a weaker one.
15011 let d = |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs();
15012 assert!(d(0.5) <= d(1.0) && d(1.0) <= d(1.5), "strength must be monotone: {} {} {}", d(0.5), d(1.0), d(1.5));
15013 // The frame reference is libaom's log-mean: flat in, the same value out.
15014 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
15015 }
15016
15017 /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
15018 /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
15019 /// shipped default, and the multiplier reaches the strength.
15020 #[test]
15021 fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
15022 let d = crate::speed::DQ_LEVEL_K;
15023 assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
15024 assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
15025 // Short and broken fields fall back per SLOT, not per spec.
15026 assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
15027 assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
15028 assert_eq!(super::DqLevel::TopArf as usize, 0);
15029 assert_eq!(super::DqLevel::MidArf as usize, 1);
15030 assert_eq!(super::DqLevel::Leaf as usize, 2);
15031 }
15032
15033 #[test]
15034 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
15035 // Four 64x64 superblocks across: the shipped map forms its ratio per
15036 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
15037 // only ever produce one ratio -- and one ratio, mean-normalised, is
15038 // the flat map, whatever the content underneath it.
15039 let (w, h) = (256usize, 64usize);
15040 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
15041 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
15042 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
15043 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
15044 for (i, &v) in f.iter().enumerate() {
15045 assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda");
15046 }
15047
15048 // Left half textured, right half constant: the window saves bits
15049 // predicting the left half and nothing at all on the right.
15050 let split: Vec<u8> = (0..w * h)
15051 .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 })
15052 .collect();
15053 let frames: Vec<&[u8]> = vec![&split, &split, &split];
15054 let cells_x = w / 16;
15055 for k in [0.25f64, 0.5, 1.0, 2.0] {
15056 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
15057 for r in 0..h / 16 {
15058 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
15059 assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1");
15060 assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1");
15061 }
15062 }
15063 }
15064
15065 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
15066 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
15067 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
15068 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
15069 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
15070 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
15071 /// only a quarter of the 16x8 table and read the wrong byte for every
15072 /// block row but the first (silently wrong above-right/below-left
15073 /// availability -- wrong pixels, no error).
15074 #[test]
15075 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
15076 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
15077 let (bw_log2, bh_log2) =
15078 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
15079 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
15080 for (name, table) in
15081 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
15082 {
15083 assert_eq!(
15084 table.len() * 8,
15085 rows * cols,
15086 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
15087 );
15088 let mut seen = vec![0u32; table.len() * 8];
15089 for blk_row in 0..rows {
15090 for blk_col in 0..cols {
15091 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
15092 assert!(
15093 idx < seen.len(),
15094 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
15095 );
15096 seen[idx] += 1;
15097 }
15098 }
15099 assert!(
15100 seen.iter().all(|&n| n == 1),
15101 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
15102 (row stride is not {cols})"
15103 );
15104 }
15105 }
15106 }
15107 use super::*;
15108 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
15109 use crate::probe::run_with_stdin;
15110 use std::process::{Command, Stdio};
15111
15112 /// Every rectangular shape this decoder codes, at every position a block
15113 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
15114 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
15115 /// (`reconintra.c`) answer, whose bodies are ported below.
15116 ///
15117 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
15118 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
15119 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
15120 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
15121 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
15122 /// oracle's own arrays, so a re-routed or truncated table fails here even
15123 /// where the two rows happen to agree.
15124 ///
15125 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
15126 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
15127 /// callers handle by predicting each transform unit as its own block.
15128 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
15129 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
15130 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
15131 /// (the horizontal shapes, which those partitions never produce).
15132 #[test]
15133 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
15134 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
15135 // it pins the 64 reach explicitly instead of following the process's
15136 // own superblock knob (`for_encoder`), which made it red under
15137 // `EC_AV1_SB128=1` for no defect of the code under test.
15138 let fctx = &crate::decode::FrameCtx::new();
15139 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
15140 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
15141 (4, 8, 64, 9280, 64, 550),
15142 (8, 4, 64, 3712, 64, 9630),
15143 (8, 16, 16, 2352, 16, 134),
15144 (16, 8, 16, 960, 16, 2400),
15145 (16, 32, 4, 620, 4, 32),
15146 (32, 16, 4, 32, 4, 184),
15147 (32, 64, 1, 127, 1, 0),
15148 (64, 32, 1, 19, 1, 34),
15149 (4, 16, 32, 5472, 32, 14),
15150 (16, 4, 32, 960, 32, 6464),
15151 (8, 32, 8, 1400, 8, 2),
15152 (32, 8, 8, 32, 8, 1136),
15153 (16, 64, 2, 382, 2, 0),
15154 (64, 16, 2, 4, 2, 84),
15155 ];
15156 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
15157 /// a block whose transform covers it whole (`row_off == col_off == 0`,
15158 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
15159 /// superblock (`sb_mi_size == 16`).
15160 fn libaom_reach(
15161 bw: usize,
15162 bh: usize,
15163 x: usize,
15164 y: usize,
15165 width: usize,
15166 height: usize, _fctx: &crate::decode::FrameCtx,
15167 ) -> (bool, bool) {
15168 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
15169 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
15170 let sb_mi_size = 16usize;
15171 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
15172 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
15173 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
15174 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
15175 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
15176 // has_top_right: top_available && right_available, then row_off == 0.
15177 let top_right = if y == 0 || x + bw >= width {
15178 false
15179 } else if blk_row_in_sb == 0 {
15180 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
15181 // `bw_unit < bw_unit`, false for a whole-block transform.)
15182 true
15183 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
15184 false
15185 } else {
15186 bit(tr_table)
15187 };
15188 // has_bottom_left: bottom_available && left_available, col_off == 0.
15189 let bottom_left = if x == 0 || y + bh >= height {
15190 false
15191 } else if blk_col_in_sb == 0 {
15192 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
15193 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
15194 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
15195 false
15196 } else {
15197 bit(bl_table)
15198 };
15199 (top_right, bottom_left)
15200 }
15201 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
15202 let (tr, bl) = rect_reach_tables(bw, bh);
15203 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
15204 assert_eq!(
15205 (tr.len(), sum(tr), bl.len(), sum(bl)),
15206 (tr_len, tr_sum, bl_len, bl_sum),
15207 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
15208 );
15209 // Two superblocks across and down, so the superblock-relative
15210 // position (and not the frame position) is what decides.
15211 for sb_y in [0usize, 64] {
15212 for sb_x in [0usize, 64] {
15213 for y in (sb_y..sb_y + 64).step_by(bh) {
15214 for x in (sb_x..sb_x + 64).step_by(bw) {
15215 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
15216 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
15217 assert_eq!(
15218 (got.above_right, got.below_left),
15219 want,
15220 "{bw}x{bh} at ({x}, {y})"
15221 );
15222 }
15223 }
15224 }
15225 }
15226 }
15227 }
15228
15229 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
15230 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
15231 /// aomenc gate decodes its stream through ffmpeg and is meaningless
15232 /// without it -- turns it into a hard failure. Without this the require
15233 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
15234 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
15235 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
15236 fn have_ffmpeg() -> bool {
15237 let present = Command::new("ffmpeg")
15238 .arg("-version")
15239 .stdout(Stdio::null())
15240 .stderr(Stdio::null())
15241 .status()
15242 .is_ok_and(|s| s.success());
15243 assert!(
15244 present
15245 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
15246 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
15247 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
15248 );
15249 present
15250 }
15251
15252 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
15253 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
15254 fn have_encoder(encoder: &str) -> bool {
15255 Command::new("ffmpeg")
15256 .args(["-hide_banner", "-encoders"])
15257 .stderr(Stdio::null())
15258 .output()
15259 .is_ok_and(|o| {
15260 String::from_utf8_lossy(&o.stdout)
15261 .lines()
15262 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
15263 })
15264 }
15265
15266 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
15267 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
15268 let out = run_with_stdin(
15269 Command::new("ffmpeg").args([
15270 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
15271 ]),
15272 stream,
15273 );
15274 assert!(
15275 out.status.success(),
15276 "ffmpeg refused the stream: {}",
15277 String::from_utf8_lossy(&out.stderr)
15278 );
15279 let (luma, chroma) = (width * height, width * height / 4);
15280 assert_eq!(
15281 out.stdout.len(),
15282 luma + 2 * chroma,
15283 "expected one 4:2:0 frame"
15284 );
15285 Picture {
15286 width,
15287 height,
15288 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
15289 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
15290 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
15291 }
15292 }
15293
15294 /// A picture with something of everything in it: a gradient, an edge, a
15295 /// ripple and a block of flat colour, none of them aligned to the block
15296 /// grid.
15297 /// The in-loop filters actually FIRE and the stream still decodes to
15298 /// exactly what the encoder kept as its reconstruction
15299 /// (gate-blind-to-feature: a filter search that always answered "off"
15300 /// would leave every other test just as green, and the BD gate that
15301 /// would notice is `#[ignore]`d).
15302 ///
15303 /// Run:
15304 /// cargo test -p ec-av1 --release --lib -- \
15305 /// encode::tests::the_filter_search_picks_real_filters
15306 #[test]
15307 fn the_filter_search_picks_real_filters() {
15308 let _knobs = crate::speed::knob_read();
15309 let fctx = &crate::decode::FrameCtx::for_encoder();
15310 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
15311 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
15312 let fired = encoded
15313 .frames
15314 .iter()
15315 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
15316 .count();
15317 assert!(
15318 fired > 0,
15319 "no frame of this sequence chose any in-loop filtering: {:?}",
15320 encoded
15321 .frames
15322 .iter()
15323 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
15324 .collect::<Vec<_>>()
15325 );
15326 // The reconstruction the encoder predicts from is the FILTERED one,
15327 // and it is what a decoder of the stream produces -- byte for byte,
15328 // frame for frame.
15329 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
15330 assert_eq!(decoded.len(), encoded.frames.len());
15331 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
15332 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
15333 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
15334 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
15335 }
15336 }
15337
15338 fn test_card(width: usize, height: usize) -> Picture {
15339 let mut picture = Picture::grey(width, height);
15340 for y in 0..height {
15341 for x in 0..width {
15342 let gradient = x as f64 * 200.0 / width as f64;
15343 let ripple = 30.0
15344 * (x as f64 * std::f64::consts::PI / 23.0).sin()
15345 * (y as f64 * std::f64::consts::PI / 37.0).cos();
15346 let edge = if x > width * 3 / 7 && y > height / 3 {
15347 40.0
15348 } else {
15349 0.0
15350 };
15351 picture.y[y * width + x] =
15352 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
15353 }
15354 }
15355 for y in 0..height / 2 {
15356 for x in 0..width / 2 {
15357 let i = y * width / 2 + x;
15358 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
15359 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
15360 }
15361 }
15362 picture
15363 }
15364
15365 fn psnr(a: &[u16], b: &[u16]) -> f64 {
15366 let squared: f64 = a
15367 .iter()
15368 .zip(b)
15369 .map(|(&x, &y)| {
15370 let d = f64::from(x) - f64::from(y);
15371 d * d
15372 })
15373 .sum();
15374 if squared == 0.0 {
15375 return f64::INFINITY;
15376 }
15377 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
15378 }
15379
15380 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
15381 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
15382 /// frame's new root fires on most superblocks -- and what BOTH decoders
15383 /// produce is the encoder's own reconstruction, sample for sample.
15384 ///
15385 /// The fire count is the `gate-blind-to-feature` guard: without it every
15386 /// assert below passes on a stream that codes no whole superblock at all.
15387 #[test]
15388 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
15389 let _knobs = crate::speed::knob_read();
15390 let fctx = &crate::decode::FrameCtx::for_encoder();
15391 // 4 x 3 superblocks, all of them wholly inside the frame.
15392 let (width, height) = (256usize, 192usize);
15393 let mut picture = Picture::grey(width, height);
15394 for y in 0..height {
15395 for x in 0..width {
15396 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
15397 }
15398 }
15399 for y in 0..height / 2 {
15400 for x in 0..width / 2 {
15401 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
15402 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
15403 }
15404 }
15405 let _ = take_i64_root_hits();
15406 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
15407 let [roots, _offered, _edge] = take_i64_root_hits();
15408 // The counters are process-global, so another test encoding in
15409 // parallel can only ADD to them -- the per-FRAME fact is the mode
15410 // list, which carries one entry per coded block and so exactly 12
15411 // when every superblock was coded as one 64x64 intra block.
15412 assert_eq!(
15413 encoded.modes.len(),
15414 12,
15415 "not every superblock was coded as one 64x64 intra block"
15416 );
15417 assert!(
15418 roots >= 8,
15419 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
15420 );
15421 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
15422
15423 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
15424 assert_eq!(ours.len(), 1, "our decoder's frames");
15425 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
15426 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
15427 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
15428
15429 if !have_ffmpeg() {
15430 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15431 return;
15432 }
15433 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15434 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15435 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15436 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15437 }
15438
15439 /// The claim the whole encoder rests on: what a decoder produces is what
15440 /// the encoder said it would, sample for sample, on every plane.
15441 ///
15442 /// Prediction reads the reconstruction, so a single sample of drift
15443 /// anywhere would spread into every block below and to the right of it —
15444 /// which is why this is an equality and not a tolerance.
15445 #[test]
15446 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
15447 let _knobs = crate::speed::knob_read();
15448 let fctx = &crate::decode::FrameCtx::for_encoder();
15449 if !have_ffmpeg() {
15450 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
15451 return;
15452 }
15453 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48), (248, 152)] {
15454 let picture = test_card(width, height);
15455 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15456 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15457 assert_eq!(
15458 decoded.y, encoded.reconstruction.y,
15459 "{width}x{height}: luma"
15460 );
15461 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
15462 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
15463 }
15464 // One q index from each of the four coefficient-CDF contexts
15465 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
15466 let (width, height) = (64usize, 64usize);
15467 let picture = test_card(width, height);
15468 let _ = take_tx_depth_hits();
15469 for &q in &[15u8, 45, 100, 200] {
15470 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15471 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15472 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
15473 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
15474 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
15475 }
15476 // lane-av1tx: the exactness above is only a claim about SPLIT
15477 // transforms if some block actually split one (`gate-blind-to-feature`
15478 // -- with `tx_depth` stuck at 0 every assert here passes on the
15479 // pre-lane stream). The test card's edges split at these four
15480 // quantizers; the counter is per-process (another test encoding in
15481 // parallel can only ADD to it, so this can be masked, never falsely
15482 // failed), so it is read once for the whole q ladder.
15483 let depths = take_tx_depth_hits();
15484 assert!(
15485 depths[1] + depths[2] > 0,
15486 "no block split its transform: depths {depths:?}"
15487 );
15488 }
15489
15490 /// A synthetic screen-content picture -- a few flat colours in a grid of
15491 /// boxes with hard edges and text-like bars, the shape a desktop capture
15492 /// has -- so the palette path is exercised on content it is for.
15493 #[cfg(test)]
15494 fn screen_card(width: usize, height: usize) -> Picture {
15495 const INK: [u16; 4] = [16, 90, 180, 235];
15496 let mut picture = Picture::grey(width, height);
15497 for y in 0..height {
15498 for x in 0..width {
15499 let cell = (x / 24 + y / 24) % 2;
15500 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
15501 picture.y[y * width + x] = INK[cell * 2 + bar];
15502 }
15503 }
15504 // Four chroma colours, not two: a two-colour chroma block only ever
15505 // codes a `PaletteSizeUV` of 2, which leaves
15506 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
15507 // deltas and the neighbour cache flags, exercised only when
15508 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
15509 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
15510 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
15511 for y in 0..height / 2 {
15512 for x in 0..width / 2 {
15513 let cell = (x / 12 + 2 * (y / 12)) % 4;
15514 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
15515 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
15516 }
15517 }
15518 picture
15519 }
15520
15521 /// The lane's own end-to-end check: on screen content the detector fires,
15522 /// blocks really take a palette (fire count, class
15523 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
15524 /// symbol this lane writes -- reconstructs exactly what the encoder did.
15525 /// The film-shaped `test_card` must NOT trip the detector, which is what
15526 /// keeps every non-screen stream byte-identical.
15527 #[test]
15528 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
15529 let _knobs = crate::speed::knob_read();
15530 let fctx = &crate::decode::FrameCtx::for_encoder();
15531 let (width, height) = (192usize, 96usize);
15532 let _ = crate::tile::take_palette_hits();
15533 let picture = screen_card(width, height);
15534 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15535 assert!(
15536 encoded.screen,
15537 "the detector did not fire on screen content -- no palette syntax was coded at all"
15538 );
15539 let hits = crate::tile::take_palette_hits();
15540 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
15541 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
15542 // The chroma half is a claim about the plane-1 syntax only if some
15543 // block really took a chroma palette (`gate-blind-to-feature`): every
15544 // exactness assert below passes on a stream that codes
15545 // `palette_uv_mode == 0` everywhere.
15546 let uv_hits = crate::tile::take_palette_uv_hits();
15547 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
15548 let uv_cached = crate::tile::take_palette_uv_cache_hits();
15549 eprintln!(
15550 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
15551 uv_hits[0],
15552 &uv_hits[2..]
15553 );
15554 assert!(
15555 uv_cached > 0,
15556 "no chroma base colour came out of the neighbour cache -- \
15557 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
15558 );
15559 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
15560 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
15561 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
15562 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
15563 if !have_ffmpeg() {
15564 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15565 return;
15566 }
15567 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15568 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15569 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15570 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15571 // A whole GOP: the inter frames' own intra blocks carry the palette
15572 // syntax too (the three intra arms of the inter writers), which only
15573 // ffmpeg reading the frames back can prove.
15574 let moved: Vec<Picture> = (0..4)
15575 .map(|f| {
15576 let base = screen_card(width, height);
15577 let mut out = Picture::grey(width, height);
15578 for y in 0..height {
15579 for x in 0..width {
15580 let sx = (x + f * 7) % width;
15581 out.y[y * width + x] = base.y[y * width + sx];
15582 }
15583 }
15584 for y in 0..height / 2 {
15585 for x in 0..width / 2 {
15586 let sx = (x + f * 3) % (width / 2);
15587 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
15588 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
15589 }
15590 }
15591 out
15592 })
15593 .collect();
15594 let _ = crate::tile::take_palette_hits();
15595 let _ = crate::tile::take_palette_uv_hits();
15596 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
15597 let gop_hits = crate::tile::take_palette_hits();
15598 let gop_uv_hits = crate::tile::take_palette_uv_hits();
15599 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
15600 eprintln!(
15601 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
15602 {} chroma palette blocks",
15603 inter_screen, gop_hits[0], gop_uv_hits[0]
15604 );
15605 assert!(
15606 gop_uv_hits[0] > 0,
15607 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
15608 );
15609 assert!(
15610 inter_screen > 0,
15611 "no inter frame set allow_screen_content_tools"
15612 );
15613 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
15614 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
15615 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
15616 }
15617 if have_ffmpeg() {
15618 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
15619 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
15620 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
15621 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
15622 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
15623 }
15624 }
15625
15626 // The other half of the keep rule: film-shaped content leaves the
15627 // detector (and so the whole sequence header) alone.
15628 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
15629 assert!(!film.screen, "the detector fired on the film-shaped test card");
15630 }
15631
15632 /// The lane's keep-rule measurement: the gate's own screen capture, one
15633 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
15634 /// Setting the bit forces deblocking, CDEF and loop restoration off for
15635 /// that frame, so the table is exactly the filter loss against the bytes
15636 /// the copied blocks save.
15637 #[test]
15638 #[ignore = "needs the real-library manifest and ffmpeg"]
15639 fn probe_intrabc_key_frame() {
15640 let _knobs = crate::speed::knob_write();
15641 let fctx = &crate::decode::FrameCtx::for_encoder();
15642 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
15643 .join("../../fixtures");
15644 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
15645 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
15646 return;
15647 };
15648 let Some(clip) = manifest
15649 .lines()
15650 .skip(1)
15651 .filter_map(|l| l.split('\t').next())
15652 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
15653 else {
15654 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
15655 return;
15656 };
15657 let (width, height) = (1280usize, 768usize);
15658 let picture = clip_frame(clip, "0", width, height);
15659 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
15660 for q in [5u8, 20, 35, 45] {
15661 for on in [false, true] {
15662 force_intrabc(Some(on));
15663 let _ = crate::tile::take_intrabc_hits();
15664 let _ = take_intrabc_search();
15665 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15666 let hits = crate::tile::take_intrabc_hits();
15667 let search = take_intrabc_search();
15668 eprintln!(
15669 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
15670 if encoded.allow_intrabc { "on" } else { "off" },
15671 encoded.stream.len(),
15672 psnr_all(&encoded.reconstruction, &picture),
15673 hits[0],
15674 &hits[1..],
15675 search[0], search[1], search[2],
15676 );
15677 }
15678 }
15679 force_intrabc(None);
15680 }
15681
15682 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
15683 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
15684 /// take a block vector (fire count + DV histogram, class
15685 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
15686 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
15687 /// exactly what the encoder did.
15688 #[test]
15689 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
15690 let _knobs = crate::speed::knob_write();
15691 let fctx = &crate::decode::FrameCtx::for_encoder();
15692 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
15693 // superblocks of 64) and tall enough for a source superblock row
15694 // above the blocks that copy from it.
15695 let (width, height) = (512usize, 256usize);
15696 let picture = screen_card(width, height);
15697 let _ = crate::tile::take_intrabc_hits();
15698 // The default is OFF (it measured worse on the real screen capture --
15699 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
15700 // the arm on for its own encode and puts it back straight after.
15701 force_intrabc(Some(true));
15702 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15703 force_intrabc(None);
15704 assert!(
15705 encoded.allow_intrabc,
15706 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
15707 intrabc_source_share() * 100.0
15708 );
15709 let hits = crate::tile::take_intrabc_hits();
15710 eprintln!(
15711 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
15712 hits[0],
15713 &hits[1..],
15714 intrabc_source_share() * 100.0
15715 );
15716 let search = take_intrabc_search();
15717 eprintln!(
15718 "intrabc searches {} found-valid {} won-RD {}",
15719 search[0], search[1], search[2]
15720 );
15721 assert!(
15722 hits[0] > 0,
15723 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
15724 );
15725 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
15726 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
15727 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
15728 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
15729 if !have_ffmpeg() {
15730 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15731 return;
15732 }
15733 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15734 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15735 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15736 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15737 }
15738
15739 /// The minimal repro that isolated the inter-residual desync: a key frame
15740 /// followed by one inter frame whose single superblock carries one
15741 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
15742 /// coefficient, its three sibling blocks all `skip: true`. Before the
15743 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
15744 /// found when processing input") even though every symbol either block
15745 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
15746 /// same coefficient syntax decodes clean on every intra key-frame gate).
15747 #[test]
15748 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
15749 let _knobs = crate::speed::knob_write();
15750 let fctx = &crate::decode::FrameCtx::for_encoder();
15751 if !have_ffmpeg() {
15752 eprintln!(
15753 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
15754 );
15755 return;
15756 }
15757 let (width, height) = (64usize, 64usize);
15758 let picture = Picture::grey(width, height);
15759 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15760
15761 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
15762 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
15763
15764 let residual_block = BlockCoeffs {
15765 luma_tx_types: Vec::new(),
15766 angle_delta_y: 0,
15767 cfl_alphas: None,
15768 filter_intra: None,
15769 luma: vec![Coeff {
15770 row: 0,
15771 col: 0,
15772 level: 4,
15773 }],
15774 u: Vec::new(),
15775 v: Vec::new(),
15776 mode: 0,
15777 uv_mode: 0,
15778 skip: false,
15779 eight: None,
15780 dv: None,
15781 palette: None,
15782 palette_uv: None,
15783 tx_depth: 0,
15784 inter: Some(InterInfo {
15785 ref1: None,
15786 mv1: (0, 0),
15787 ref_frame: crate::mvstack::LAST_FRAME,
15788 mode: InterMode::NearestMv,
15789 mv: (0, 0),
15790 ref_mv_idx: 0,
15791 }),
15792 motion_mode: 0,
15793 };
15794 let skipped_block = BlockCoeffs {
15795 skip: true,
15796 inter: Some(InterInfo {
15797 ref1: None,
15798 mv1: (0, 0),
15799 ref_frame: crate::mvstack::LAST_FRAME,
15800 mode: InterMode::NearestMv,
15801 mv: (0, 0),
15802 ref_mv_idx: 0,
15803 }),
15804 ..BlockCoeffs::default()
15805 };
15806 let blocks = vec![
15807 Quadrant::Whole(residual_block),
15808 Quadrant::Whole(skipped_block.clone()),
15809 Quadrant::Whole(skipped_block.clone()),
15810 Quadrant::Whole(skipped_block),
15811 ];
15812 // lane-av1obmc: the header this tile is decoded under carries
15813 // `is_motion_mode_switchable`, so the writer must be armed with it
15814 // too or the decoder reads a `motion_mode` symbol nobody wrote.
15815 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
15816 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
15817 let tile =
15818 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
15819 .unwrap();
15820
15821 // `key.stream` is already a temporal delimiter, the sequence header
15822 // and the key frame's own OBU (`encode_key_frame` built it from the
15823 // same `key_frame_headers(width, height, 100)` this test calls), so
15824 // the inter frame's OBU is appended straight onto it rather than
15825 // re-deriving the key frame's tile bytes.
15826 let mut stream = key.stream.clone();
15827 stream.extend_from_slice(&temporal_delimiter());
15828 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
15829
15830 ffmpeg_decode_sequence(&stream, width, height, 2);
15831 }
15832
15833 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
15834 /// frame size an AV1 decoder allocates, not necessarily the render size
15835 /// (see [`a_frame_round_trips_at_its_own_size`]).
15836 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
15837 // Distinct per call, not per process: the test binary runs callers on
15838 // parallel threads, and a shared name lets one test's cleanup delete
15839 // the stream another test's ffprobe is still reading.
15840 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
15841 let path = std::env::temp_dir().join(format!(
15842 "ec-av1-probe-{}-{}.obu",
15843 std::process::id(),
15844 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
15845 ));
15846 let _ = std::fs::remove_file(&path);
15847 std::fs::write(&path, stream).expect("writing the probe stream");
15848 let out = Command::new("ffprobe")
15849 .args([
15850 "-v",
15851 "error",
15852 "-f",
15853 "obu",
15854 "-select_streams",
15855 "v:0",
15856 "-show_entries",
15857 "stream=width,height",
15858 "-of",
15859 "csv=p=0",
15860 ])
15861 .arg(&path)
15862 .output()
15863 .expect("ffprobe failed to run");
15864 let _ = std::fs::remove_file(&path);
15865 assert!(
15866 out.status.success(),
15867 "ffprobe refused the stream: {}",
15868 String::from_utf8_lossy(&out.stderr)
15869 );
15870 let text = String::from_utf8_lossy(&out.stdout);
15871 let mut fields = text.trim().split(',');
15872 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
15873 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
15874 (width, height)
15875 }
15876
15877 /// lane-av1cap: the final filter replay against the capture decode it
15878 /// replaced, at the block-padded and straddling sizes the whole-frame
15879 /// tests cover -- `set_verify_final_replay` makes
15880 /// [`pick_and_apply_filters`] run both on every frame and assert, per
15881 /// frame, that the spliced picture and the two filter stages the
15882 /// restoration search reads are bit-identical over the frame's own crop.
15883 #[test]
15884 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
15885 let _knobs = crate::speed::knob_write();
15886 let fctx = &crate::decode::FrameCtx::for_encoder();
15887 crate::decode::set_verify_final_replay(true);
15888 for &(width, height) in
15889 &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)]
15890 {
15891 eprintln!("--- {width}x{height}");
15892 let picture = test_card(width, height);
15893 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15894 }
15895 crate::decode::set_verify_final_replay(false);
15896 }
15897
15898 /// A key frame at an arbitrary even size round-trips through ffmpeg over
15899 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
15900 /// picture's own size, and what ffmpeg decodes over that same top-left
15901 /// region equals it sample for sample.
15902 ///
15903 /// This does not check that `ffprobe` reports the picture's own size,
15904 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
15905 /// (block-padded) frame size, the same one libaom itself would code for
15906 /// a non-block-aligned picture. `render_width`/`render_height` (which
15907 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
15908 /// decoder is required to crop pixels by, and ffmpeg's does not --
15909 /// checked empirically against ffprobe here and against a real libaom
15910 /// encode separately. So the coded size, not the render size, is what
15911 /// `ffprobe` is asserted to report below.
15912 #[test]
15913 fn a_frame_round_trips_at_its_own_size() {
15914 let _knobs = crate::speed::knob_read();
15915 let fctx = &crate::decode::FrameCtx::for_encoder();
15916 if !have_ffmpeg() {
15917 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
15918 return;
15919 }
15920 // 854x480 is covered separately by
15921 // `an_854x480_picture_round_trips_through_its_padding`, which its own
15922 // doc comment explains was worth keeping as its own test.
15923 for &(width, height) in &[
15924 (1920usize, 1080usize),
15925 (640, 352),
15926 (1280, 720),
15927 (64, 56),
15928 (854, 480),
15929 (216, 96),
15930 (192, 120),
15931 ] {
15932 let picture = test_card(width, height);
15933 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15934 assert_eq!(
15935 (encoded.reconstruction.width, encoded.reconstruction.height),
15936 (width, height),
15937 "{width}x{height}: reconstruction is cropped to the picture's own size"
15938 );
15939 assert_eq!(
15940 ffprobe_size(&encoded.stream),
15941 (width as u32, height as u32),
15942 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
15943 );
15944 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15945 assert_eq!(
15946 decoded.y, encoded.reconstruction.y,
15947 "{width}x{height}: luma"
15948 );
15949 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
15950 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
15951 }
15952 }
15953
15954 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
15955 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
15956 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
15957 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
15958 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
15959 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
15960 /// col`) -- different bits of an 8-byte table, one true, one false. The
15961 /// stride libaom indexes by is fixed at its compile-time maximum
15962 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
15963 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
15964 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
15965 /// row/col position within the (correctly 64-relative) superblock stayed
15966 /// right, only the table's own row stride was wrong. Fixed in
15967 /// `Reach::table_stride`; not an arithmetic-coder desync (an
15968 /// EC_RNG-per-symbol trace against the same debug decoder found the
15969 /// bitstream byte-for-byte identical to libaom's across all 51188
15970 /// symbols of this frame before this bug was found).
15971 ///
15972 /// Since the frame header started writing the true (unpadded) display
15973 /// size into `frame_width`/`frame_height` rather than the padded coded
15974 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
15975 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
15976 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
15977 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
15978 /// the header's own size before output).
15979 #[test]
15980 fn an_854x480_picture_round_trips_through_its_padding() {
15981 let _knobs = crate::speed::knob_read();
15982 let fctx = &crate::decode::FrameCtx::for_encoder();
15983 if !have_ffmpeg() {
15984 return;
15985 }
15986 let (width, height) = (854usize, 480usize);
15987 let picture = test_card(width, height);
15988 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15989 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15990 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
15991 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
15992 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
15993 }
15994
15995 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
15996 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
15997 /// superblock, both partition tables:
15998 ///
15999 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
16000 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
16001 /// wiring the TU sites onto it changes no existing stream;
16002 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
16003 /// NULL in libaom because that lookup never happens, and reading a
16004 /// 4x4 row out of the three-row vert tables is what crashed a real
16005 /// `--enable-tx-size-search=1` stream (r2);
16006 /// 3. and it must be the BLOCK's vert answer where the two tables
16007 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
16008 /// row 1, column 0 reads its above-right samples from the 8x8 to its
16009 /// upper right, which a vertical AB partition codes AFTER it
16010 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
16011 #[test]
16012 fn of_tu_follows_the_block_row_including_under_vert_ab() {
16013 let fctx = &crate::decode::FrameCtx::for_encoder();
16014 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
16015 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
16016 // above-right answer is the BLOCK's, which is the whole reason a unit
16017 // asks the block instead of looking itself up (the
16018 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
16019 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
16020 assert_eq!(
16021 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
16022 plain.above_right,
16023 "ordinary table: the top-right TX4 unit takes the block's row"
16024 );
16025 let guard = Reach::vert_ab_partition();
16026 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
16027 assert_eq!(
16028 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
16029 vert.above_right,
16030 "vert AB: the unit follows the vert row the block just picked"
16031 );
16032 assert_ne!(
16033 plain.above_right, vert.above_right,
16034 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
16035 );
16036 drop(guard);
16037 }
16038
16039 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
16040 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
16041 /// reconintra.c`), for every 16x16 and 32x32 block position across three
16042 /// superblocks square -- interior and every superblock edge (top row,
16043 /// left column, right column, bottom row) both sizes reach. Written to
16044 /// catch the class the `table_stride` bug was: an index stride silently
16045 /// wrong for one block size while looking plausible for the other.
16046 #[test]
16047 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
16048 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
16049 // it pins the 64 reach explicitly instead of following the process's
16050 // own superblock knob (`for_encoder`), which made it red under
16051 // `EC_AV1_SB128=1` for no defect of the code under test.
16052 let fctx = &crate::decode::FrameCtx::new();
16053 // Transcribed from has_top_right/has_bottom_left's row_off==0,
16054 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
16055 // 128px reference grid) pinned as libaom pins it, independent of the
16056 // 64px superblock this crate actually codes.
16057 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
16058 if y == 0 || x + side >= width {
16059 return false;
16060 }
16061 let (row, col, per_side) = (
16062 (y % SUPERBLOCK) / side,
16063 (x % SUPERBLOCK) / side,
16064 SUPERBLOCK / side,
16065 );
16066 if row == 0 {
16067 return true;
16068 }
16069 if col + 1 == per_side {
16070 return false;
16071 }
16072 let stride = 128 / side;
16073 let index = row * stride + col;
16074 let table = if side == BLOCK {
16075 [95u8, 87].to_vec()
16076 } else {
16077 vec![255, 85, 119, 85, 127, 85, 119, 85]
16078 };
16079 (table[index / 8] >> (index % 8)) & 1 != 0
16080 }
16081
16082 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
16083 if x == 0 || y + side >= height {
16084 return false;
16085 }
16086 let (row, col, per_side) = (
16087 (y % SUPERBLOCK) / side,
16088 (x % SUPERBLOCK) / side,
16089 SUPERBLOCK / side,
16090 );
16091 if col == 0 {
16092 return row * side + side < SUPERBLOCK;
16093 }
16094 if row + 1 == per_side {
16095 return false;
16096 }
16097 let stride = 128 / side;
16098 let index = row * stride + col;
16099 let table = if side == BLOCK {
16100 [4u8, 4].to_vec()
16101 } else {
16102 vec![84, 16, 84, 0, 84, 16, 84, 0]
16103 };
16104 (table[index / 8] >> (index % 8)) & 1 != 0
16105 }
16106
16107 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
16108 for side in [16usize, BLOCK] {
16109 for y in (0..height).step_by(side) {
16110 for x in (0..width).step_by(side) {
16111 let reach = Reach::of(side, x, y, width, height, fctx);
16112 assert_eq!(
16113 reach.above_right,
16114 libaom_top_right(side, x, y, width, height),
16115 "side={side} x={x} y={y}: above_right"
16116 );
16117 assert_eq!(
16118 reach.below_left,
16119 libaom_bottom_left(side, x, y, height, fctx),
16120 "side={side} x={x} y={y}: below_left"
16121 );
16122 }
16123 }
16124 }
16125 }
16126
16127 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
16128 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
16129 /// column inside the superblock) may read the below-left samples the
16130 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
16131 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
16132 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
16133 /// stream that partitions that small first hits the still-refused
16134 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
16135 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
16136 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
16137 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
16138 /// pixels -- lane-palette2 r12: the square multi-TU path used the
16139 /// standalone-block tables instead of this rule and granted a 16x16
16140 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
16141 #[test]
16142 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
16143 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
16144 // *_count_unit = tx size / 4.
16145 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
16146 let (plane_bw_unit, count) = (bw / 4, tx / 4);
16147 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
16148 let _ = bh;
16149 if row_off_u > 0 {
16150 col_off_u + count < plane_bw_unit
16151 } else if col_off_u + count < plane_bw_unit {
16152 true
16153 } else {
16154 blk
16155 }
16156 }
16157 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
16158 let (plane_bh_unit, count) = (bh / 4, tx / 4);
16159 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
16160 let _ = bw;
16161 if col_off_u > 0 {
16162 false
16163 } else if row_off_u + count < plane_bh_unit {
16164 true
16165 } else {
16166 blk
16167 }
16168 }
16169 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
16170 for &tx in &[4usize, 8, 16, 32] {
16171 if tx > bw.min(bh) {
16172 continue;
16173 }
16174 for row_off in (0..bh).step_by(tx) {
16175 for col_off in (0..bw).step_by(tx) {
16176 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
16177 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
16178 assert_eq!(
16179 got.above_right,
16180 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
16181 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
16182 );
16183 assert_eq!(
16184 got.below_left,
16185 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
16186 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
16187 );
16188 }
16189 }
16190 }
16191 }
16192 }
16193 }
16194
16195 #[test]
16196 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
16197 let fctx = &crate::decode::FrameCtx::for_encoder();
16198 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
16199 // Interior superblock, so neither the frame edge nor the col == 0 /
16200 // last-row early returns answer instead of the table.
16201 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
16202 let mut flipped = 0;
16203 for row in 0..8 {
16204 for col in 1..8 {
16205 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
16206 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
16207 let vert = {
16208 let _guard = Reach::vert_ab_partition();
16209 Reach::of(8, x, y, width, height, fctx).below_left
16210 };
16211 // The TR square of a VERT_A/_B sits at an even row, odd
16212 // column; every other slot must be untouched by the guard.
16213 if row % 2 == 0 && col % 2 == 1 {
16214 assert!(!raster, "raster below_left at row={row} col={col}");
16215 assert!(vert, "vert below_left at row={row} col={col}");
16216 flipped += 1;
16217 } else {
16218 assert_eq!(raster, vert, "guard moved row={row} col={col}");
16219 }
16220 }
16221 }
16222 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
16223 // The guard is scoped: it must not leak past its own block.
16224 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
16225 }
16226
16227 /// An odd width or height is refused by name, not by however the padder
16228 /// or the block coder would happen to fail on it.
16229 #[test]
16230 fn odd_dimensions_are_refused() {
16231 let _knobs = crate::speed::knob_read();
16232 let fctx = &crate::decode::FrameCtx::for_encoder();
16233 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
16234 let picture = Picture::grey(width, height);
16235 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
16236 .expect_err(&format!("{width}x{height} is odd and must be refused"));
16237 assert!(
16238 err.to_string().contains("even"),
16239 "{width}x{height}: error was {err}"
16240 );
16241 }
16242 }
16243
16244 /// A sequence at a size that is not a multiple of the block grid decodes
16245 /// to the right frame count and the right size for every frame,
16246 /// including the inter frames whose reference is the previous frame's
16247 /// own (padded) reconstruction.
16248 #[test]
16249 fn sequence_round_trips_at_a_non_multiple_size() {
16250 let _knobs = crate::speed::knob_read();
16251 let fctx = &crate::decode::FrameCtx::for_encoder();
16252 if !have_ffmpeg() {
16253 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
16254 return;
16255 }
16256 let (width, height) = (160usize, 96usize);
16257 let pictures: Vec<Picture> = (0..3)
16258 .map(|i| panned_test_card(width, height, i * 3))
16259 .collect();
16260 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16261 assert_eq!(encoded.frames.len(), 3);
16262 for (i, frame) in encoded.frames.iter().enumerate() {
16263 assert_eq!(
16264 (frame.reconstruction.width, frame.reconstruction.height),
16265 (width, height),
16266 "frame {i}: reconstruction size"
16267 );
16268 }
16269 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
16270 // true (display) size a sequence's frames share, not the padded one.
16271 assert_eq!(
16272 ffprobe_size(&encoded.stream),
16273 (width as u32, height as u32),
16274 "sequence: ffprobe reports the true (display) size"
16275 );
16276 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
16277 assert_eq!(decoded.len(), 3, "decoded frame count");
16278 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16279 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16280 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16281 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16282 }
16283 }
16284
16285 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
16286 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
16287 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
16288 /// `pos + side_mi / 2 < bound` boundary), which is the case
16289 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
16290 /// refusing. A key frame alone already covered this size; this proves the
16291 /// inter tile writer's parity with it across a real multi-frame export.
16292 #[test]
16293 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
16294 let _knobs = crate::speed::knob_read();
16295 let fctx = &crate::decode::FrameCtx::for_encoder();
16296 if !have_ffmpeg() {
16297 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
16298 return;
16299 }
16300 let (width, height) = (1280usize, 720usize);
16301 let pictures: Vec<Picture> = (0..3)
16302 .map(|i| panned_test_card(width, height, i * 3))
16303 .collect();
16304 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16305 assert_eq!(encoded.frames.len(), 3);
16306 for (i, frame) in encoded.frames.iter().enumerate() {
16307 assert_eq!(
16308 (frame.reconstruction.width, frame.reconstruction.height),
16309 (width, height),
16310 "frame {i}: reconstruction size"
16311 );
16312 }
16313 assert_eq!(
16314 ffprobe_size(&encoded.stream),
16315 (width as u32, height as u32),
16316 "ffprobe reports the true (display) 1280x720 size"
16317 );
16318 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
16319 assert_eq!(decoded.len(), 3, "decoded frame count");
16320 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16321 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16322 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16323 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16324 }
16325 }
16326
16327 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
16328 /// leaf's own half (`has_half` at the SUB level) itself straddles the
16329 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
16330 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
16331 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
16332 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
16333 /// straddling-16x16 branch), so an inter frame no longer refuses this
16334 /// size either. This only proves the encoder does not error out -- see
16335 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
16336 /// decoder-clean proof (a 3-frame sequence, so the inter path is
16337 /// actually exercised).
16338 #[test]
16339 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
16340 let _knobs = crate::speed::knob_read();
16341 let fctx = &crate::decode::FrameCtx::for_encoder();
16342 let (width, height) = (640usize, 360usize);
16343 let picture = Picture::grey(width, height);
16344 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
16345
16346 // `encode_sequence`'s second frame is the inter path: same size, now
16347 // wired the same way.
16348 let pictures = vec![picture.clone(), picture];
16349 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
16350 .expect("inter frame now codes the mod-32==8 straddle too");
16351 }
16352
16353 /// The r15 fix at production size: three 640x360 key frames (inter is
16354 /// still refused at this size, per the test above, so this stands in for
16355 /// the charter's "3-frame sequence" using three independent key frames of
16356 /// shifted content), each proven decoder-clean through ffmpeg rather than
16357 /// only encoder-clean.
16358 #[test]
16359 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
16360 let _knobs = crate::speed::knob_read();
16361 let fctx = &crate::decode::FrameCtx::for_encoder();
16362 if !have_ffmpeg() {
16363 eprintln!(
16364 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
16365 no ffmpeg"
16366 );
16367 return;
16368 }
16369 let (width, height) = (640usize, 360usize);
16370 for shift in [0i64, 7, 19] {
16371 let picture = panned_test_card(width, height, shift);
16372 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16373 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16374 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
16375 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
16376 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
16377 }
16378 }
16379
16380 /// The 640x360 straddle class, but through the inter path an actual
16381 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
16382 /// proves the leaf-8 inter stream this round wires up is not just
16383 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
16384 #[test]
16385 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
16386 let _knobs = crate::speed::knob_read();
16387 let fctx = &crate::decode::FrameCtx::for_encoder();
16388 if !have_ffmpeg() {
16389 eprintln!(
16390 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
16391 );
16392 return;
16393 }
16394 let (width, height) = (640usize, 360usize);
16395 let pictures: Vec<Picture> = (0..4)
16396 .map(|i| panned_test_card(width, height, i * 3))
16397 .collect();
16398 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16399 assert_eq!(encoded.frames.len(), 4);
16400 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
16401 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
16402 }
16403 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
16404 assert_eq!(decoded.len(), 4, "decoded frame count");
16405 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16406 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16407 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16408 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16409 }
16410 }
16411
16412 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
16413 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
16414 let out = Command::new("ffmpeg")
16415 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
16416 .args(["-vf", &format!("scale={width}:{height}")])
16417 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
16418 .output()
16419 .expect("ffmpeg failed to run");
16420 assert!(
16421 out.status.success(),
16422 "ffmpeg: {}",
16423 String::from_utf8_lossy(&out.stderr)
16424 );
16425 let (luma, chroma) = (width * height, width * height / 4);
16426 assert_eq!(
16427 out.stdout.len(),
16428 luma + 2 * chroma,
16429 "expected one 4:2:0 frame"
16430 );
16431 Picture {
16432 width,
16433 height,
16434 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
16435 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
16436 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
16437 }
16438 }
16439
16440 /// Prints what the mode search saves over DC prediction alone, for the
16441 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
16442 /// weight the search puts on rate can be swept.
16443 #[test]
16444 #[ignore = "a sweep, not a gate"]
16445 fn probe_lambda() {
16446 let _knobs = crate::speed::knob_read();
16447 let fctx = &crate::decode::FrameCtx::for_encoder();
16448 let mut pictures = vec![
16449 ("test card".to_string(), test_card(160, 96)),
16450 ("stripes".to_string(), stripes(160, 96, true)),
16451 ];
16452 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
16453 for entry in clips.split(':').filter(|e| !e.is_empty()) {
16454 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
16455 let name = path.rsplit('/').next().unwrap_or(path).to_string();
16456 pictures.push((name, clip_frame(path, skip, 640, 352)));
16457 }
16458 }
16459 for (name, picture) in pictures {
16460 let dc = ladder(&picture, &[DC_PRED], fctx);
16461 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
16462 println!(
16463 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
16464 bd_rate(&dc, &searched) * 100.0,
16465 10f64.powf(searched[1].1),
16466 searched[1].0,
16467 10f64.powf(dc[1].1),
16468 dc[1].0,
16469 );
16470 }
16471 }
16472
16473 /// Prints the whole mode-search ladder, so two builds of the search can be
16474 /// compared against each other rather than each against its own baseline.
16475 #[test]
16476 #[ignore = "a sweep, not a gate"]
16477 fn probe_ladder() {
16478 let _knobs = crate::speed::knob_read();
16479 let fctx = &crate::decode::FrameCtx::for_encoder();
16480 for (name, picture) in sweep_pictures() {
16481 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
16482 let points = all
16483 .iter()
16484 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
16485 .collect::<Vec<_>>()
16486 .join(" ");
16487 println!("ladder {name}: {points}");
16488 }
16489 }
16490
16491 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
16492 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
16493 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
16494 #[test]
16495 #[ignore = "a sweep, not a gate"]
16496 fn probe_split() {
16497 let _knobs = crate::speed::knob_read();
16498 let fctx = &crate::decode::FrameCtx::for_encoder();
16499 for (name, picture) in sweep_pictures() {
16500 let ladder = |split: bool| {
16501 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
16502 .iter()
16503 .map(|&q| {
16504 let encoded = encode_key_frame_inner(
16505 &picture,
16506 q,
16507 0.5,
16508 &KEY_FRAME_MODES,
16509 split,
16510 (picture.width, picture.height),
16511 unspecified_color_config(), fctx,
16512 )
16513 .unwrap();
16514 (
16515 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
16516 (encoded.stream.len() as f64).log10(),
16517 )
16518 })
16519 .collect();
16520 points.sort_by(|a, b| a.0.total_cmp(&b.0));
16521 points
16522 };
16523 let (whole, split) = (ladder(false), ladder(true));
16524 let blocks = encode_key_frame_inner(
16525 &picture,
16526 90,
16527 0.5,
16528 &KEY_FRAME_MODES,
16529 true,
16530 (picture.width, picture.height),
16531 unspecified_color_config(), fctx,
16532 )
16533 .unwrap()
16534 .modes
16535 .len();
16536 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
16537 println!(
16538 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
16539 bd_rate(&whole, &split) * 100.0
16540 );
16541 }
16542 }
16543
16544 /// A striped picture, running one way or the other. The stripes are what
16545 /// separates a vertical predictor from a horizontal one: a mode search
16546 /// reading a transposed edge would pick the wrong one of the pair, which no
16547 /// symmetric picture would show.
16548 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
16549 let mut picture = Picture::grey(width, height);
16550 for y in 0..height {
16551 for x in 0..width {
16552 let along = if vertical { x } else { y };
16553 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
16554 }
16555 }
16556 picture
16557 }
16558
16559 /// Where two planes first disagree, and by how much: a mismatch reported as
16560 /// a position says which block and which sample of it went wrong, which a
16561 /// pair of thousand-sample arrays does not.
16562 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
16563 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
16564 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
16565 Some(format!(
16566 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
16567 i % width,
16568 i / width,
16569 ours[i],
16570 theirs[i]
16571 ))
16572 }
16573
16574 /// Every mode the encoder offers has to predict what the decoder predicts,
16575 /// not just the ones a particular picture happens to choose: each is forced
16576 /// over a whole picture and the reconstruction gated against ffmpeg.
16577 #[test]
16578 fn every_mode_decodes_to_what_the_encoder_predicted() {
16579 let _knobs = crate::speed::knob_write();
16580 let fctx = &crate::decode::FrameCtx::for_encoder();
16581 if !have_ffmpeg() {
16582 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
16583 return;
16584 }
16585 // A mode ablation measures the MODE search: a filter-intra block is
16586 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
16587 // "the encoder coded something else" check for a reason that is not
16588 // about the mode search at all.
16589 force_filter_intra(Some(false));
16590 // 128 wide is a whole number of superblocks and 160 is not: the last
16591 // superblock of a 160-wide row is half a one, whose blocks have no
16592 // above-right samples inside the frame at all.
16593 for (width, height) in [(128, 96), (160, 96)] {
16594 let picture = test_card(width, height);
16595 for mode in KEY_FRAME_MODES {
16596 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
16597 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16598 for (plane, ours, theirs, stride) in [
16599 ("luma", &encoded.reconstruction.y, &decoded.y, width),
16600 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
16601 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
16602 ] {
16603 assert!(
16604 first_difference(ours, theirs, stride).is_none(),
16605 "{width}x{height} mode {mode}, {plane}: {}",
16606 first_difference(ours, theirs, stride).unwrap()
16607 );
16608 }
16609 assert!(
16610 encoded.modes.iter().all(|&m| m == mode),
16611 "mode {mode}: the encoder coded something else"
16612 );
16613 }
16614 }
16615 }
16616
16617 /// The search has to follow the picture: vertical stripes are cheapest
16618 /// predicted from the row above, horizontal ones from the column to the
16619 /// left. Reading the edges the other way round would swap the two answers
16620 /// while leaving every fidelity gate intact.
16621 #[test]
16622 fn the_search_picks_the_direction_the_picture_runs() {
16623 let _knobs = crate::speed::knob_write();
16624 let fctx = &crate::decode::FrameCtx::for_encoder();
16625 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
16626 // a filter-intra block is coded `DC_PRED` whatever mode the arm
16627 // offers, and these stripes are SCREEN content, where the filter arm
16628 // now searches its own transform depth (lane-fitu) and wins outright
16629 // -- which says nothing about the mode search this gate measures.
16630 force_filter_intra(Some(false));
16631 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
16632 let picture = stripes(128, 96, vertical);
16633 // Only the pair, because on stripes a third mode predicts exactly
16634 // what the right one of the pair does -- PAETH reads the corner and
16635 // the left column, which a striped picture makes equal -- and the
16636 // tie then goes to whichever is cheaper to name, which is not what
16637 // this gate is about.
16638 let encoded =
16639 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
16640 // The first block of the picture has neither neighbour, so it
16641 // cannot tell the modes apart; every other one can.
16642 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
16643 assert!(
16644 picked * 2 > encoded.modes.len() - 1,
16645 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
16646 encoded.modes.len() - 1,
16647 encoded.modes
16648 );
16649 }
16650 }
16651
16652 /// What the search is for: the same picture, at the same quantizer, coded
16653 /// smaller and more faithfully than DC alone can manage.
16654 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
16655 /// between the two rate-distortion curves in log-rate against PSNR, as a
16656 /// fraction of the reference's rate. Negative means the second curve costs
16657 /// less for the same picture.
16658 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
16659 let low = reference[0].0.max(other[0].0);
16660 let high = reference[reference.len() - 1]
16661 .0
16662 .min(other[other.len() - 1].0);
16663 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
16664 // the non-directional one on the synthetic diagonals -- every point
16665 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
16666 // to integrate over any more. A curve that dominates that way has
16667 // saved everything the measure can express (the
16668 // `instrument-at-bound` class: the answer is at the instrument's own
16669 // edge, not undefined), so name it rather than panicking; anything
16670 // less clean than strict dominance still is.
16671 if high <= low {
16672 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
16673 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
16674 let dominates = other[0].0 > reference[reference.len() - 1].0
16675 && other_hi_rate <= ref_lo_rate;
16676 assert!(
16677 dominates,
16678 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
16679 );
16680 return -1.0;
16681 }
16682 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
16683 let i = curve
16684 .windows(2)
16685 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
16686 .unwrap_or(0);
16687 let (x0, y0) = curve[i];
16688 let (x1, y1) = curve[i + 1];
16689 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
16690 };
16691 let steps = 64;
16692 let mut area = 0.0;
16693 for step in 0..steps {
16694 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
16695 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
16696 }
16697 10f64.powf(area / f64::from(steps)) - 1.0
16698 }
16699
16700 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
16701 /// fidelity.
16702 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
16703 // A mode ablation measures the MODE search: the palette would code
16704 // these synthetic two-colour pictures losslessly under every arm and
16705 // leave nothing to compare (see [`force_screen`]).
16706 force_screen(Some(false));
16707 // Same reason, for the filter-intra candidate: it wins blocks under
16708 // BOTH arms of a mode ablation and so cancels the difference the
16709 // ablation measures (class `gate-recipe-confound`).
16710 force_filter_intra(Some(false));
16711 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
16712 .iter()
16713 .map(|&q| {
16714 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
16715 (
16716 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
16717 (encoded.stream.len() as f64).log10(),
16718 )
16719 })
16720 .collect();
16721 points.sort_by(|a, b| a.0.total_cmp(&b.0));
16722 points
16723 }
16724
16725 /// What the search is for: the same pictures cost less to code at the same
16726 /// fidelity than DC prediction alone can manage. A picture that runs one
16727 /// way saves far more than a busy one, which is the shape a working
16728 /// directional pair has.
16729 #[test]
16730 fn the_search_beats_dc_alone() {
16731 let _knobs = crate::speed::knob_read();
16732 let fctx = &crate::decode::FrameCtx::for_encoder();
16733 for (name, picture, want) in [
16734 ("test card", test_card(160, 96), -0.05),
16735 ("stripes", stripes(160, 96, true), -0.40),
16736 ] {
16737 let saved = bd_rate(
16738 &ladder(&picture, &[DC_PRED], fctx),
16739 &ladder(&picture, &NON_DIRECTIONAL, fctx),
16740 );
16741 assert!(
16742 saved < want,
16743 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
16744 saved * 100.0,
16745 -want * 100.0
16746 );
16747 }
16748 }
16749
16750 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
16751 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
16752 fn sweep_pictures() -> Vec<(String, Picture)> {
16753 let mut pictures = vec![
16754 ("test card".to_string(), test_card(160, 96)),
16755 ("stripes".to_string(), stripes(160, 96, true)),
16756 ("diagonal".to_string(), diagonal(160, 96, true)),
16757 ];
16758 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
16759 for entry in clips.split(':').filter(|e| !e.is_empty()) {
16760 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
16761 let name = path.rsplit('/').next().unwrap_or(path).to_string();
16762 pictures.push((name, clip_frame(path, skip, 640, 352)));
16763 }
16764 }
16765 pictures
16766 }
16767
16768 /// What the six directional modes are worth, per picture, at whatever
16769 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
16770 /// no further, and how often the search picks one.
16771 #[test]
16772 #[ignore = "a sweep, not a gate"]
16773 fn probe_directional() {
16774 let _knobs = crate::speed::knob_write();
16775 let fctx = &crate::decode::FrameCtx::for_encoder();
16776 for (name, picture) in sweep_pictures() {
16777 let dc = ladder(&picture, &[DC_PRED], fctx);
16778 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
16779 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
16780 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
16781 let directional = encoded
16782 .modes
16783 .iter()
16784 .filter(|&&m| (3..=8).contains(&m))
16785 .count();
16786 // A picture whose ladders sit at different fidelities altogether
16787 // has no BD-rate to report -- see the flat-sample-window class.
16788 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
16789 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
16790 };
16791 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
16792 if overlap(a, b) {
16793 format!("{:+.2}%", bd_rate(a, b) * 100.0)
16794 } else {
16795 "no overlap".to_string()
16796 }
16797 };
16798 println!(
16799 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
16800 against(&flat, &all),
16801 against(&dc, &all),
16802 encoded.modes.len(),
16803 );
16804 }
16805 }
16806
16807 /// A picture whose stripes run along a diagonal, one way or the other.
16808 /// This is to the directional modes what [`stripes`] is to the vertical and
16809 /// horizontal pair: a predictor that walked the edge in the wrong direction
16810 /// would answer the two pictures the same way round.
16811 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
16812 let mut picture = Picture::grey(width, height);
16813 for y in 0..height {
16814 for x in 0..width {
16815 let along = if down_right { x + height - y } else { x + y };
16816 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
16817 }
16818 }
16819 picture
16820 }
16821
16822 /// The mode picked by the most blocks of a picture, ignoring the first
16823 /// block, which has no neighbours to tell the modes apart with.
16824 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
16825 // A mode ablation measures the MODE search: the palette would code
16826 // these synthetic two-colour pictures losslessly under every arm and
16827 // leave nothing to compare (see [`force_screen`]).
16828 force_screen(Some(false));
16829 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
16830 let blocks = &encoded.modes[1..];
16831 let mut counts = [0usize; 13];
16832 for &mode in blocks {
16833 counts[usize::from(mode)] += 1;
16834 }
16835 let (mode, count) = counts
16836 .iter()
16837 .enumerate()
16838 .max_by_key(|&(_, count)| *count)
16839 .expect("thirteen modes");
16840 (mode as u8, *count, blocks.len())
16841 }
16842
16843 /// The search has to follow a diagonal the way it runs: stripes down and to
16844 /// the right are cheapest predicted at 135 degrees, stripes down and to the
16845 /// left at 45. A walk that stepped the wrong way along the edge, or read
16846 /// the above row where it should read the left column, would swap these.
16847 #[test]
16848 fn the_search_picks_the_diagonal_the_picture_runs() {
16849 let _knobs = crate::speed::knob_write();
16850 let fctx = &crate::decode::FrameCtx::for_encoder();
16851 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
16852 let picture = diagonal(160, 96, down_right);
16853 let (mode, count, blocks) = favourite_mode(&picture, fctx);
16854 assert_eq!(
16855 mode, want,
16856 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
16857 );
16858 }
16859 }
16860
16861 /// What the directional modes are for: a picture that runs along a diagonal
16862 /// costs far less to code with them than the seven that read only their own
16863 /// edges can manage, and a picture that runs no particular way costs no
16864 /// more. The second half is the one that bites: a mode set the search
16865 /// cannot price is a mode set that loses rate on content that does not want
16866 /// it, which is what costing the mode symbol is for.
16867 #[test]
16868 fn the_diagonals_beat_the_modes_that_read_no_further() {
16869 let _knobs = crate::speed::knob_read();
16870 let fctx = &crate::decode::FrameCtx::for_encoder();
16871 for (name, picture, want) in [
16872 ("down-right", diagonal(160, 96, true), -0.20),
16873 ("down-left", diagonal(160, 96, false), -0.20),
16874 ("test card", test_card(160, 96), 0.01),
16875 ] {
16876 let saved = bd_rate(
16877 &ladder(&picture, &NON_DIRECTIONAL, fctx),
16878 &ladder(&picture, &KEY_FRAME_MODES, fctx),
16879 );
16880 assert!(
16881 saved < want,
16882 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
16883 saved * 100.0,
16884 -want * 100.0
16885 );
16886 }
16887 }
16888
16889 /// A mode the encoder cannot predict must be refused rather than coded as
16890 /// something else, and a search with nothing to choose from likewise.
16891 #[test]
16892 fn a_mode_the_encoder_cannot_predict_is_refused() {
16893 let _knobs = crate::speed::knob_read();
16894 let fctx = &crate::decode::FrameCtx::for_encoder();
16895 let picture = test_card(64, 64);
16896 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
16897 .unwrap_err()
16898 .to_string();
16899 assert!(
16900 message.contains("intra mode 13"),
16901 "the refusal must name the mode, got {message}"
16902 );
16903 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
16904 }
16905
16906 /// The picture that comes back is the picture that went in, to within the
16907 /// quantizer. A prediction that read the wrong neighbours, or a block
16908 /// written into the wrong place, would still decode to what the encoder
16909 /// reconstructed — it is this gate that says the reconstruction is of the
16910 /// right picture.
16911 #[test]
16912 fn the_encoded_picture_is_the_one_that_went_in() {
16913 let _knobs = crate::speed::knob_read();
16914 let fctx = &crate::decode::FrameCtx::for_encoder();
16915 let picture = test_card(160, 96);
16916 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16917 let luma = psnr(&encoded.reconstruction.y, &picture.y);
16918 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
16919 for (plane, (got, want)) in [
16920 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
16921 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
16922 ]
16923 .iter()
16924 .enumerate()
16925 {
16926 let chroma = psnr(got, want);
16927 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
16928 }
16929 }
16930
16931 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
16932 /// does the opposite. Both are monotone, which is what a rate-distortion
16933 /// loop above this will assume.
16934 #[test]
16935 fn fidelity_and_rate_move_with_the_quantizer() {
16936 let _knobs = crate::speed::knob_read();
16937 let fctx = &crate::decode::FrameCtx::for_encoder();
16938 let picture = test_card(128, 128);
16939 let mut previous: Option<(usize, f64)> = None;
16940 for &q in &[70u8, 90, 110] {
16941 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16942 let quality = psnr(&encoded.reconstruction.y, &picture.y);
16943 if let Some((bytes, better)) = previous {
16944 assert!(
16945 encoded.stream.len() < bytes,
16946 "q {q}: {} bytes",
16947 encoded.stream.len()
16948 );
16949 assert!(quality < better, "q {q}: PSNR {quality}");
16950 }
16951 previous = Some((encoded.stream.len(), quality));
16952 }
16953
16954 // The deadzone half of this claim lives in
16955 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
16956 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
16957 // every zeroing, the deadzone no longer moves a coded stream
16958 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
16959 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
16960 // job, not a quantiser defect.
16961
16962 // Bytes must not jump up across a q-context boundary: a wrong CDF
16963 // table for the far side would show up as a rate discontinuity here,
16964 // even though a coarser quantizer always codes no more than a finer
16965 // one on the same picture.
16966 //
16967 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
16968 // chroma searches its own mode, a coarser quantizer can pick a
16969 // *different* uv_mode on a block whose modes now cost nearly the
16970 // same, and the search prices that symbol against the static default
16971 // CDF while the writer codes it against an adapted one -- 311 -> 319
16972 // bytes at q 120->121 on this picture. The table this gate is really
16973 // watching would move the rate by far more than the mode churn does.
16974 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
16975 // same block can also change transform DEPTH between two neighbouring
16976 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
16977 // symbol is priced off the static CDF row 0 for the same reason the
16978 // uv_mode one is.
16979 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
16980 // path is pricing through the adapting CDF state (what
16981 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
16982 // drift of), after which the exact bound comes back.
16983 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
16984 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
16985 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
16986 assert!(
16987 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
16988 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
16989 );
16990 }
16991 }
16992
16993 /// A flat picture is a flat stream: every block predicts its neighbours'
16994 /// average, which is the picture's own value, and codes nothing.
16995 #[test]
16996 fn a_flat_picture_costs_almost_nothing() {
16997 let _knobs = crate::speed::knob_read();
16998 let fctx = &crate::decode::FrameCtx::for_encoder();
16999 let mut picture = Picture::grey(128, 128);
17000 picture.y.fill(97);
17001 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17002 // The first block has no neighbour and predicts 128, so it carries a
17003 // DC; every block after it predicts 97 and carries nothing.
17004 assert!(
17005 encoded.stream.len() < 100,
17006 "{} bytes for a flat picture",
17007 encoded.stream.len()
17008 );
17009 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
17010 assert_eq!(s, 97, "sample {i} of a flat picture");
17011 }
17012 }
17013
17014 /// The sizes the encoder refuses, refused for a reason rather than by
17015 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
17016 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
17017 /// lands past the halfway point of whichever block it falls in, so
17018 /// `PARTITION_NONE` or a single gathered split flag still says everything
17019 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
17020 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
17021 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
17022 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
17023 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
17024 /// refusal here claimed otherwise and was wrong; see
17025 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
17026 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
17027 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
17028 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
17029 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
17030 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
17031 /// still refused is a malformed picture.
17032 #[test]
17033 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
17034 let _knobs = crate::speed::knob_read();
17035 let fctx = &crate::decode::FrameCtx::for_encoder();
17036 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
17037 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
17038 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
17039 .expect("36 luma columns still round up to an even MiCols");
17040
17041 let mut short = Picture::grey(64, 64);
17042 short.u.truncate(10);
17043 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
17044 }
17045
17046 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
17047 /// column half only (`has_half` false on cols, true on rows) -- exactly
17048 /// the single-axis straddle lane-av1-rect r7 wires through
17049 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
17050 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
17051 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
17052 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
17053 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
17054 /// `partition_context_lookup` entry this writer ever produces (no 4x4
17055 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
17056 /// leaf regardless of neighbour state -- our writer already agreed with
17057 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
17058 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
17059 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
17060 /// it does not regress the gate. r11 tell-for-tell traced two further,
17061 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
17062 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
17063 /// leaves, when the second leaf's true above (or left) neighbour is the
17064 /// first leaf itself -- fixed by threading the first leaf's mode into the
17065 /// second leaf's context, mi-precise, like `record_mi` already does for
17066 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
17067 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
17068 /// `reduced_tx_set` is false), but this crate's key frames set
17069 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
17070 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
17071 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
17072 /// symbol bits to desync everything after it. Fixed with a new
17073 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
17074 /// eset/size slot). Both fixes are provably correct against libaom
17075 /// source and each closed part of the gap (leaf0's `eob` went from a
17076 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
17077 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
17078 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
17079 /// (do not reuse r11's committed logs, which predate its own fixes) and
17080 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
17081 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
17082 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
17083 /// every other `write_block` caller at 16x16 and up already passes
17084 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
17085 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
17086 /// different amount of arithmetic range and derailed everything after
17087 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
17088 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
17089 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
17090 /// never updating those coarse arrays itself -- so a *second* straddling
17091 /// 16x16 quadrant stacked above or left of the first (never covered by
17092 /// r11's same-call `prev_leaf` override, which only threads state
17093 /// between the two leaves of one shared quadrant) read whatever stale
17094 /// mode sat in that slot before either leaf ran. Fixed by writing the
17095 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
17096 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
17097 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
17098 /// offset of a single unit; fixing (3)+(4) together still leaves a
17099 /// residual divergence one leaf further in -- the decoder now reads
17100 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
17101 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
17102 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
17103 /// desyncs the stream by exactly the width of one earlier symbol -- not
17104 /// yet isolated to a single named symbol. r15 found the last bug: the
17105 /// header fix from r14 explained the rng skew fully, and the remaining
17106 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
17107 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
17108 /// loop, once per leaf, so the first leaf's write clobbered the true
17109 /// external neighbour mode the second leaf of the *same* straddling
17110 /// quadrant still needed for its non-adjacency axis (a column-straddle
17111 /// case: two leaves share one `outer_at` column index, so leaf 1's
17112 /// write to `left_mode[r]` overwrote the real western neighbour before
17113 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
17114 /// doing it once, after the whole leaf loop, from the last (bottom/
17115 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
17116 #[test]
17117 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
17118 let _knobs = crate::speed::knob_read();
17119 let fctx = &crate::decode::FrameCtx::for_encoder();
17120 if !have_ffmpeg() {
17121 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
17122 return;
17123 }
17124 let (width, height) = (40usize, 32usize);
17125 let picture = test_card(width, height);
17126 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17127 assert_eq!(
17128 (encoded.reconstruction.width, encoded.reconstruction.height),
17129 (width, height)
17130 );
17131 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
17132 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
17133 }
17134 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17135 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
17136 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
17137 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
17138 }
17139
17140 /// A frame of real video, rather than a picture built to be easy.
17141 ///
17142 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
17143 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
17144 /// encoder's reconstruction has to survive the same equality gate as the
17145 /// synthetic pictures — real video reaches contexts a test card does not.
17146 #[test]
17147 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
17148 let _knobs = crate::speed::knob_read();
17149 let fctx = &crate::decode::FrameCtx::for_encoder();
17150 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
17151 eprintln!(
17152 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
17153 set EC_AV1_CLIP to a clip"
17154 );
17155 return;
17156 };
17157 if !have_ffmpeg() {
17158 eprintln!(
17159 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
17160 );
17161 return;
17162 }
17163 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
17164 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
17165 // test quick while still spanning many superblocks.
17166 let (width, height) = (640usize, 352usize);
17167 let picture = clip_frame(&clip, &skip, width, height);
17168
17169 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17170 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17171 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
17172 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
17173 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
17174 eprintln!(
17175 "{} bytes, luma PSNR {:.2} dB",
17176 encoded.stream.len(),
17177 psnr(&decoded.y, &picture.y)
17178 );
17179 }
17180
17181 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
17182 /// sequence of these is a translation a motion search can actually find
17183 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
17184 /// inter frame's rate against the key frame's is measuring the same
17185 /// picture moving, not two different pictures.
17186 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
17187 let mut picture = Picture::grey(width, height);
17188 for y in 0..height {
17189 for x in 0..width {
17190 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
17191 let gradient = sx * 200.0 / width as f64;
17192 let ripple = 30.0
17193 * (sx * std::f64::consts::PI / 23.0).sin()
17194 * (y as f64 * std::f64::consts::PI / 37.0).cos();
17195 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
17196 40.0
17197 } else {
17198 0.0
17199 };
17200 picture.y[y * width + x] =
17201 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
17202 }
17203 }
17204 for y in 0..height / 2 {
17205 for x in 0..width / 2 {
17206 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
17207 let i = y * width / 2 + x;
17208 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
17209 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
17210 }
17211 }
17212 picture
17213 }
17214
17215 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
17216 fn ffmpeg_decode_sequence(
17217 stream: &[u8],
17218 width: usize,
17219 height: usize,
17220 frames: usize,
17221 ) -> Vec<Picture> {
17222 let out = run_with_stdin(
17223 Command::new("ffmpeg").args([
17224 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
17225 ]),
17226 stream,
17227 );
17228 assert!(
17229 out.status.success(),
17230 "ffmpeg refused the stream: {}",
17231 String::from_utf8_lossy(&out.stderr)
17232 );
17233 let (luma, chroma) = (width * height, width * height / 4);
17234 let frame_bytes = luma + 2 * chroma;
17235 assert_eq!(
17236 out.stdout.len(),
17237 frame_bytes * frames,
17238 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
17239 String::from_utf8_lossy(&out.stderr)
17240 );
17241 (0..frames)
17242 .map(|i| {
17243 let base = i * frame_bytes;
17244 Picture {
17245 width,
17246 height,
17247 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
17248 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
17249 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
17250 }
17251 })
17252 .collect()
17253 }
17254
17255 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
17256 /// makes for a key frame, extended down the reference chain: each inter
17257 /// frame's reconstruction predicts from the previous frame's own decoded
17258 /// reconstruction, so a single sample of drift anywhere would propagate
17259 /// into every frame after it -- which is why every frame is checked, not
17260 /// just the last one, and why this is an equality and not a tolerance.
17261 #[test]
17262 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
17263 let _knobs = crate::speed::knob_read();
17264 let fctx = &crate::decode::FrameCtx::for_encoder();
17265 if !have_ffmpeg() {
17266 eprintln!(
17267 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
17268 );
17269 return;
17270 }
17271 let (width, height) = (128usize, 64usize);
17272 let pictures: Vec<Picture> = (0..5)
17273 .map(|i| panned_test_card(width, height, i * 3))
17274 .collect();
17275 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17276 assert_eq!(encoded.frames.len(), 5);
17277
17278 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
17279 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17280 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
17281 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
17282 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
17283 }
17284
17285 eprintln!("frame bytes luma PSNR (dB) inter share");
17286 for (i, frame) in encoded.frames.iter().enumerate() {
17287 eprintln!(
17288 "{i:5} {:5} {:14.2} {:11.2}",
17289 frame.stream.len(),
17290 psnr(&frame.reconstruction.y, &pictures[i].y),
17291 frame.inter_block_share
17292 );
17293 }
17294 }
17295
17296 /// The same sequence through OUR OWN decoder, sample-exact against the
17297 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
17298 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
17299 /// divergence point at all, while our decoder can be traced symbol by
17300 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
17301 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
17302 /// names the first differing frame, plane and position.
17303 /// lane-sb128b: the writer used to price a `NEWMV` residual against
17304 /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
17305 /// write-time stack could not carry, while the drl symbols signalled the
17306 /// clamped index -- so the decoder derived a DIFFERENT motion vector with
17307 /// the entropy stream still in sync, and the drift only surfaced frames
17308 /// later as a drl desync (on film B, as the encoder's own trial decode
17309 /// refusing a reference slot).
17310 ///
17311 /// The clamp needs a stack that shrinks between search and write, which
17312 /// is what a 128x128 superblock's visit order does; the counter is the
17313 /// point (class `gate-blind-to-feature`): a green round trip on a clip
17314 /// that never clamps proves nothing.
17315 ///
17316 /// `#[ignore]`: [`force_sb128`] moves a process-global.
17317 ///
17318 /// cargo test -p ec-av1 --release --lib -- --ignored \
17319 /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture
17320 /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
17321 /// and one motion vector where the four 64x64 roots below spend four of
17322 /// each (cen3's L1). The counter is the gate on the fixture (class
17323 /// `gate-blind-to-feature`): a green round trip on a clip that never
17324 /// codes a 128x128 block proves nothing. RED before the search existed
17325 /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
17326 /// root by construction).
17327 ///
17328 /// Both readers: our own decoder sample-exact against the encoder's
17329 /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
17330 /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
17331 ///
17332 /// `#[ignore]`: [`force_sb128`] moves a process-global.
17333 ///
17334 /// cargo test -p ec-av1 --release --lib -- --ignored \
17335 /// a_128_superblock_clip_whose_root_search --nocapture
17336 #[test]
17337 #[ignore = "sets the process-global superblock size: run it alone"]
17338 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
17339 let _knobs = crate::speed::knob_write();
17340 if !have_ffmpeg() {
17341 eprintln!("SKIP: no ffmpeg");
17342 return;
17343 }
17344 force_sb128(true);
17345 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
17346 std::fs::create_dir_all(&dir).unwrap();
17347 let clip = dir.join("smpte-1280x768.y4m");
17348 // A slow horizontal pan over a still pattern: whole 128x128 regions
17349 // share one motion vector, which is exactly what a 128 root can code
17350 // as one block and four 64 roots cannot.
17351 let ok = Command::new("ffmpeg")
17352 .args(["-v", "error", "-y", "-f", "lavfi"])
17353 .args(["-i", "smptebars=size=1600x768:rate=24"])
17354 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17355 .args(["-pix_fmt", "yuv420p"])
17356 .arg(&clip)
17357 .status()
17358 .expect("ffmpeg failed to run")
17359 .success();
17360 assert!(ok, "ffmpeg could not write the synthetic clip");
17361 let (width, height) = (1280usize, 768usize);
17362 let pictures =
17363 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17364 let _ = take_b128_none_hits();
17365 let _ = crate::tile::take_sb128_none_hits();
17366 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17367 let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
17368 eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
17369 assert!(
17370 coded > 0,
17371 "no 128x128 block was coded on this clip, so it cannot witness the root search",
17372 );
17373 assert_eq!(won, coded, "every 128x128 root the search took must be coded as one");
17374 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17375 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17376 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17377 let recon = &frame.reconstruction;
17378 for (plane, got, want) in [
17379 ("luma", &dec.y, &recon.y),
17380 ("U", &dec.u, &recon.u),
17381 ("V", &dec.v, &recon.v),
17382 ] {
17383 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17384 assert_eq!(
17385 differ, 0,
17386 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17387 own reconstruction",
17388 got.len()
17389 );
17390 }
17391 }
17392 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17393 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17394 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17395 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17396 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17397 }
17398 }
17399
17400 /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
17401 /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
17402 /// same pan the skip-only witness above uses, with the arm FORCED
17403 /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
17404 /// about once per frame, which witnesses the shape but not every context
17405 /// it reads, and forcing codes all 420 roots of the clip through it. RED
17406 /// before this lane by construction (`write_inter_block_128` refused
17407 /// every non-skip 128 block, so no such block existed to decode), and RED
17408 /// again on the first draft of the writer, whose neighbour band recorded
17409 /// `skip = true` for a block that carries a residual -- the next root's
17410 /// `skip` symbol then took CDF row 1 where the reader takes row 0.
17411 ///
17412 /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces
17413 /// the skip arm's cost unconditionally (that is what makes the writer see
17414 /// the residual), and the cost model moved under it since lane-b128r --
17415 /// lane-rectdq made every non-skipped root pay its delta_q group and the
17416 /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root
17417 /// lost its partition at ALL 420 roots and the writer coded none. q=60
17418 /// puts 52 written blocks back on this clip; the `coded > 0` assert below
17419 /// is the guard that catches the next such drift.
17420 ///
17421 /// cargo test -p ec-av1 --release --lib -- --ignored \
17422 /// a_128_root_block_with_a_real_residual --nocapture
17423 #[test]
17424 #[ignore = "sets the process-global superblock size: run it alone"]
17425 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
17426 let _knobs = crate::speed::knob_write();
17427 if !have_ffmpeg() {
17428 eprintln!("SKIP: no ffmpeg");
17429 return;
17430 }
17431 force_sb128(true);
17432 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
17433 std::fs::create_dir_all(&dir).unwrap();
17434 let clip = dir.join("smpte-pan-1280x768.y4m");
17435 let ok = Command::new("ffmpeg")
17436 .args(["-v", "error", "-y", "-f", "lavfi"])
17437 .args(["-i", "smptebars=size=1600x768:rate=24"])
17438 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17439 .args(["-pix_fmt", "yuv420p"])
17440 .arg(&clip)
17441 .status()
17442 .expect("ffmpeg failed to run")
17443 .success();
17444 assert!(ok, "ffmpeg could not write the synthetic clip");
17445 let (width, height) = (1280usize, 768usize);
17446 let pictures =
17447 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17448 let _ = take_b128_residual_hits();
17449 let _ = crate::tile::take_sb128_residual_hits();
17450 force_b128_residual(true);
17451 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17452 let (won, coded) =
17453 (take_b128_residual_hits(), crate::tile::take_sb128_residual_hits());
17454 eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
17455 assert!(
17456 coded > 0,
17457 "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
17458 );
17459 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17460 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17461 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17462 let recon = &frame.reconstruction;
17463 for (plane, got, want) in [
17464 ("luma", &dec.y, &recon.y),
17465 ("U", &dec.u, &recon.u),
17466 ("V", &dec.v, &recon.v),
17467 ] {
17468 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17469 assert_eq!(
17470 differ, 0,
17471 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17472 own reconstruction",
17473 got.len()
17474 );
17475 }
17476 }
17477 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17478 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17479 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17480 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17481 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17482 }
17483 }
17484
17485 /// lane-edge128: a 128x128 root block WITH a residual on a clip whose
17486 /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec
17487 /// 5.11.56) codes ONE literal for the block that first reaches a unit and
17488 /// copies it over every unit the block SPANS, so the four units of a 128
17489 /// root share one index -- while the encoder's CDEF search prices a
17490 /// preset per unit and its filter replay applied all four. Only the first
17491 /// reached the stream, so every decoder filtered the other three with the
17492 /// origin's strengths and the encoder's reconstruction (the picture the
17493 /// next frame predicts from) was a filter apart from what a decoder
17494 /// produces. RED before this lane on the native BD gate's bars 2160p row
17495 /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples,
17496 /// the rows above the 128 superblock's own edge); the stream itself was
17497 /// always right -- ffmpeg and our own decoder agreed with each other and
17498 /// disagreed with the encoder.
17499 ///
17500 /// `take_cdef_covered_units` is the gate on the fixture (class
17501 /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair
17502 /// for the whole frame codes no literal at all and witnesses nothing.
17503 ///
17504 /// cargo test -p ec-av1 --release --lib -- --ignored \
17505 /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture
17506 #[test]
17507 #[ignore = "sets the process-global superblock size: run it alone"]
17508 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
17509 let _knobs = crate::speed::knob_write();
17510 if !have_ffmpeg() {
17511 eprintln!("SKIP: no ffmpeg");
17512 return;
17513 }
17514 force_sb128(true);
17515 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
17516 std::fs::create_dir_all(&dir).unwrap();
17517 let clip = dir.join("testsrc2-1280x768.y4m");
17518 // Detailed synthetic content: its CDEF search spends more than one
17519 // strength pair, which is what puts a `cdef_idx` literal in the tile.
17520 let ok = Command::new("ffmpeg")
17521 .args(["-v", "error", "-y", "-f", "lavfi"])
17522 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17523 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17524 .arg(&clip)
17525 .status()
17526 .expect("ffmpeg failed to run")
17527 .success();
17528 assert!(ok, "ffmpeg could not write the synthetic clip");
17529 let (width, height) = (1280usize, 768usize);
17530 let pictures =
17531 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17532 force_b128_root(true);
17533 force_b128_residual(true);
17534 let _ = crate::tile::take_sb128_residual_hits();
17535 let _ = crate::filter_search::take_cdef_covered_units();
17536 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17537 let coded = crate::tile::take_sb128_residual_hits();
17538 let covered = crate::filter_search::take_cdef_covered_units();
17539 eprintln!(
17540 "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17541 another unit's literal: {covered}"
17542 );
17543 assert!(coded > 0, "no 128x128 block carried a residual on this clip");
17544 assert!(
17545 covered > 0,
17546 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17547 cannot witness the rule",
17548 );
17549 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17550 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17551 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17552 for (plane, got, want) in [
17553 ("luma", &dec.y, &frame.reconstruction.y),
17554 ("U", &dec.u, &frame.reconstruction.u),
17555 ("V", &dec.v, &frame.reconstruction.v),
17556 ] {
17557 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17558 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17559 }
17560 }
17561 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17562 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17563 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17564 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17565 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17566 }
17567 }
17568
17569 /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
17570 /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
17571 /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
17572 /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
17573 /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
17574 /// rect partition with [`force_b128_rect`]) so every inter root of the
17575 /// clip goes through it; the `coded > 0` assert is the guard that catches
17576 /// the next fixture drift (the whole-128 twin of this witness went RED
17577 /// twice that way).
17578 ///
17579 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17580 /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
17581 #[test]
17582 #[ignore = "sets the process-global superblock size: run it alone"]
17583 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
17584 let _knobs = crate::speed::knob_write();
17585 if !have_ffmpeg() {
17586 eprintln!("SKIP: no ffmpeg");
17587 return;
17588 }
17589 force_sb128(true);
17590 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
17591 std::fs::create_dir_all(&dir).unwrap();
17592 let clip = dir.join("smpte-pan-1280x768.y4m");
17593 let ok = Command::new("ffmpeg")
17594 .args(["-v", "error", "-y", "-f", "lavfi"])
17595 .args(["-i", "smptebars=size=1600x768:rate=24"])
17596 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17597 .args(["-pix_fmt", "yuv420p"])
17598 .arg(&clip)
17599 .status()
17600 .expect("ffmpeg failed to run")
17601 .success();
17602 assert!(ok, "ffmpeg could not write the synthetic clip");
17603 let (width, height) = (1280usize, 768usize);
17604 let pictures =
17605 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17606 force_b128_rect(1);
17607 force_b128_rectres(true);
17608 let _ = take_b128_rectres_hits();
17609 let _ = crate::tile::take_sb128_rectres_hits();
17610 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17611 let (won, coded) =
17612 (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17613 eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
17614 assert!(
17615 coded > 0,
17616 "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
17617 );
17618 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17619 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17620 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17621 let recon = &frame.reconstruction;
17622 for (plane, got, want) in [
17623 ("luma", &dec.y, &recon.y),
17624 ("U", &dec.u, &recon.u),
17625 ("V", &dec.v, &recon.v),
17626 ] {
17627 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17628 assert_eq!(
17629 differ, 0,
17630 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17631 own reconstruction",
17632 got.len()
17633 );
17634 }
17635 }
17636 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17637 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17638 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17639 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17640 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17641 }
17642 }
17643
17644 /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
17645 /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
17646 /// the two 64x64 squares through the one-chunk arm (the shape libaom's
17647 /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
17648 /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
17649 /// reference picture the GOP has not produced yet, which refuses before
17650 /// any AB root is coded.
17651 ///
17652 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17653 /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
17654 #[test]
17655 #[ignore = "sets the process-global superblock size: run it alone"]
17656 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
17657 let _knobs = crate::speed::knob_write();
17658 if !have_ffmpeg() {
17659 eprintln!("SKIP: no ffmpeg");
17660 return;
17661 }
17662 force_sb128(true);
17663 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
17664 std::fs::create_dir_all(&dir).unwrap();
17665 let clip = dir.join("testsrc2-1280x768.y4m");
17666 let ok = Command::new("ffmpeg")
17667 .args(["-v", "error", "-y", "-f", "lavfi"])
17668 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17669 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17670 .arg(&clip)
17671 .status()
17672 .expect("ffmpeg failed to run")
17673 .success();
17674 assert!(ok, "ffmpeg could not write the synthetic clip");
17675 let (width, height) = (1280usize, 768usize);
17676 let pictures =
17677 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17678 force_b128_ab(4);
17679 force_b128_rectres(true);
17680 let _ = take_b128_rectres_hits();
17681 let _ = crate::tile::take_sb128_rectres_hits();
17682 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17683 let (won, coded) =
17684 (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17685 eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
17686 assert!(
17687 coded > 0,
17688 "no AB piece carried a residual on this clip, so it cannot witness the arm",
17689 );
17690 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17691 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17692 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17693 let recon = &frame.reconstruction;
17694 for (plane, got, want) in [
17695 ("luma", &dec.y, &recon.y),
17696 ("U", &dec.u, &recon.u),
17697 ("V", &dec.v, &recon.v),
17698 ] {
17699 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17700 assert_eq!(
17701 differ, 0,
17702 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17703 own reconstruction",
17704 got.len()
17705 );
17706 }
17707 }
17708 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17709 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17710 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17711 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17712 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17713 }
17714 }
17715
17716 /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
17717 /// half WITH a residual under a clip whose CDEF search codes a
17718 /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
17719 /// and the decoder stamps BOTH units it spans with it, so the owner map
17720 /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
17721 /// collapse the pair -- exactly the bug class that broke bars 2160p at
17722 /// the whole-128 root. RED before this lane by construction: no rect
17723 /// piece could carry a residual, so no such literal existed.
17724 ///
17725 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17726 /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
17727 #[test]
17728 #[ignore = "sets the process-global superblock size: run it alone"]
17729 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
17730 let _knobs = crate::speed::knob_write();
17731 if !have_ffmpeg() {
17732 eprintln!("SKIP: no ffmpeg");
17733 return;
17734 }
17735 force_sb128(true);
17736 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
17737 std::fs::create_dir_all(&dir).unwrap();
17738 let clip = dir.join("testsrc2-1280x768.y4m");
17739 // Detailed synthetic content: its CDEF search spends more than one
17740 // strength pair, which is what puts a `cdef_idx` literal in the tile.
17741 let ok = Command::new("ffmpeg")
17742 .args(["-v", "error", "-y", "-f", "lavfi"])
17743 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17744 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17745 .arg(&clip)
17746 .status()
17747 .expect("ffmpeg failed to run")
17748 .success();
17749 assert!(ok, "ffmpeg could not write the synthetic clip");
17750 let (width, height) = (1280usize, 768usize);
17751 let pictures =
17752 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17753 force_b128_rect(1);
17754 force_b128_rectres(true);
17755 let _ = crate::tile::take_sb128_rectres_hits();
17756 let _ = crate::filter_search::take_cdef_covered_units();
17757 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17758 let coded = crate::tile::take_sb128_rectres_hits();
17759 let covered = crate::filter_search::take_cdef_covered_units();
17760 eprintln!(
17761 "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17762 another unit's literal: {covered}"
17763 );
17764 assert!(coded > 0, "no 128x64 half carried a residual on this clip");
17765 assert!(
17766 covered > 0,
17767 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17768 cannot witness the rule",
17769 );
17770 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17771 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17772 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17773 for (plane, got, want) in [
17774 ("luma", &dec.y, &frame.reconstruction.y),
17775 ("U", &dec.u, &frame.reconstruction.u),
17776 ("V", &dec.v, &frame.reconstruction.v),
17777 ] {
17778 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17779 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17780 }
17781 }
17782 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17783 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17784 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17785 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17786 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17787 }
17788 }
17789
17790 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
17791 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
17792 /// `write_compound_block` chain every smaller compound block takes, at a
17793 /// window it had never been exercised at. RED before this lane: the
17794 /// search passed an empty compound list at the 128 root, so the count was
17795 /// 0 and no such block existed to decode.
17796 ///
17797 /// cargo test -p ec-av1 --release --lib -- --ignored \
17798 /// a_128_root_compound_block --nocapture
17799 #[test]
17800 #[ignore = "sets the process-global superblock size: run it alone"]
17801 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
17802 let _knobs = crate::speed::knob_write();
17803 if !have_ffmpeg() {
17804 eprintln!("SKIP: no ffmpeg");
17805 return;
17806 }
17807 force_sb128(true);
17808 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
17809 std::fs::create_dir_all(&dir).unwrap();
17810 let clip = dir.join("testsrc2-1280x768.y4m");
17811 // Moving objects that occlude each other: a pan is coded by one
17812 // reference outright, and a compound pair only pays where the two
17813 // references disagree.
17814 let ok = Command::new("ffmpeg")
17815 .args(["-v", "error", "-y", "-f", "lavfi"])
17816 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17817 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17818 .arg(&clip)
17819 .status()
17820 .expect("ffmpeg failed to run")
17821 .success();
17822 assert!(ok, "ffmpeg could not write the synthetic clip");
17823 let (width, height) = (1280usize, 768usize);
17824 let pictures =
17825 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17826 // The compound candidate wins the 128 block's own search on this pan
17827 // but the root then loses to its four cells, so the root is forced
17828 // (the residual arm is left at its default, off).
17829 force_b128_root(true);
17830 let _ = take_b128_compound_hits();
17831 let _ = crate::tile::take_sb128_compound_hits();
17832 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17833 let (won, coded) =
17834 (take_b128_compound_hits(), crate::tile::take_sb128_compound_hits());
17835 eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
17836 assert!(coded > 0, "no compound 128x128 block was coded on this clip");
17837 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17838 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17839 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17840 for (plane, got, want) in [
17841 ("luma", &dec.y, &frame.reconstruction.y),
17842 ("U", &dec.u, &frame.reconstruction.u),
17843 ("V", &dec.v, &frame.reconstruction.v),
17844 ] {
17845 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17846 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17847 }
17848 }
17849 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17850 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17851 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17852 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17853 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17854 }
17855 }
17856
17857 /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
17858 /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
17859 /// square. Three passes over one `testsrc2` clip:
17860 ///
17861 /// * HORZ forced at every root ([`force_b128_rect`]), so every context
17862 /// the 128x64 shape reads is exercised rather than the handful the RD
17863 /// would pick;
17864 /// * VERT forced the same way;
17865 /// * UNFORCED, which is the count the gate rows are read against -- the
17866 /// same clip with the RD free to choose among NONE / HORZ / VERT /
17867 /// four superblocks.
17868 ///
17869 /// Each pass is sample-exact against the encoder's own reconstruction
17870 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17871 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17872 /// before this lane by construction: `write_sb128_root` could only name
17873 /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
17874 ///
17875 /// cargo test -p ec-av1 --release --lib -- --ignored \
17876 /// a_128_root_horz_and_vert --nocapture
17877 #[test]
17878 #[ignore = "sets the process-global superblock size: run it alone"]
17879 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
17880 let _knobs = crate::speed::knob_write();
17881 if !have_ffmpeg() {
17882 eprintln!("SKIP: no ffmpeg");
17883 return;
17884 }
17885 force_sb128(true);
17886 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
17887 std::fs::create_dir_all(&dir).unwrap();
17888 let clip = dir.join("testsrc2-1280x768.y4m");
17889 let ok = Command::new("ffmpeg")
17890 .args(["-v", "error", "-y", "-f", "lavfi"])
17891 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17892 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17893 .arg(&clip)
17894 .status()
17895 .expect("ffmpeg failed to run")
17896 .success();
17897 assert!(ok, "ffmpeg could not write the synthetic clip");
17898 let (width, height) = (1280usize, 768usize);
17899 let pictures =
17900 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17901 let mut unforced = (0usize, 0usize);
17902 for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
17903 force_b128_rect(force);
17904 let _ = take_b128_horz_hits();
17905 let _ = take_b128_vert_hits();
17906 let _ = crate::tile::take_sb128_horz_hits();
17907 let _ = crate::tile::take_sb128_vert_hits();
17908 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17909 let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
17910 let (coded_h, coded_v) = (
17911 crate::tile::take_sb128_horz_hits(),
17912 crate::tile::take_sb128_vert_hits(),
17913 );
17914 eprintln!(
17915 "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
17916 {coded_h} 128x64 + {coded_v} 64x128 halves"
17917 );
17918 match force {
17919 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
17920 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
17921 // The unforced count is REPORTED, not asserted: it is the
17922 // number the gate is read against, and a zero here would be
17923 // an RD result, not a defect (the forced passes already prove
17924 // the writer and the reader agree on the shape).
17925 _ => unforced = (won_h, won_v),
17926 }
17927 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17928 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
17929 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17930 for (plane, got, want) in [
17931 ("luma", &dec.y, &frame.reconstruction.y),
17932 ("U", &dec.u, &frame.reconstruction.u),
17933 ("V", &dec.v, &frame.reconstruction.v),
17934 ] {
17935 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17936 assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
17937 }
17938 }
17939 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17940 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17941 assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
17942 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
17943 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
17944 }
17945 }
17946 force_b128_rect(0);
17947 eprintln!(
17948 "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
17949 unforced.0, unforced.1
17950 );
17951 }
17952
17953 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
17954 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
17955 /// Five passes over the same `testsrc2` clip
17956 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
17957 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
17958 /// context and every visit order the shape reads is exercised rather than
17959 /// the handful the RD would pick, and then an UNFORCED pass whose
17960 /// per-shape count is REPORTED (it is the number the gate rows are read
17961 /// against).
17962 ///
17963 /// Each pass is sample-exact against the encoder's own reconstruction
17964 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17965 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17966 /// before this lane by construction: `write_sb128_root` could only name
17967 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
17968 ///
17969 /// cargo test -p ec-av1 --release --lib -- --ignored \
17970 /// a_128_root_ab_shapes --nocapture
17971 #[test]
17972 #[ignore = "sets the process-global superblock size: run it alone"]
17973 fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
17974 let _knobs = crate::speed::knob_write();
17975 if !have_ffmpeg() {
17976 eprintln!("SKIP: no ffmpeg");
17977 return;
17978 }
17979 force_sb128(true);
17980 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
17981 std::fs::create_dir_all(&dir).unwrap();
17982 let clip = dir.join("testsrc2-1280x768.y4m");
17983 let ok = Command::new("ffmpeg")
17984 .args(["-v", "error", "-y", "-f", "lavfi"])
17985 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17986 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17987 .arg(&clip)
17988 .status()
17989 .expect("ffmpeg failed to run")
17990 .success();
17991 assert!(ok, "ffmpeg could not write the synthetic clip");
17992 let (width, height) = (1280usize, 768usize);
17993 let pictures =
17994 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17995 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
17996 let mut unforced = [0usize; 4];
17997 for force in [4u8, 5, 6, 7, 0] {
17998 force_b128_ab(force);
17999 let label = if force == 0 { "unforced" } else { names[usize::from(force) - 4] };
18000 let _ = take_b128_ab_hits();
18001 let _ = crate::tile::take_sb128_ab_hits();
18002 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
18003 let won = take_b128_ab_hits();
18004 let coded = crate::tile::take_sb128_ab_hits();
18005 eprintln!(
18006 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
18007 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
18008 );
18009 if force == 0 {
18010 // The unforced counts are REPORTED, not asserted: a zero here
18011 // would be an RD result, not a defect (the four forced passes
18012 // already prove the writer and the reader agree on the shape).
18013 unforced = won;
18014 } else {
18015 let i = usize::from(force) - 4;
18016 assert!(coded[i] > 0, "no {label} root was coded with {label} forced");
18017 }
18018 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18019 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
18020 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18021 for (plane, got, want) in [
18022 ("luma", &dec.y, &frame.reconstruction.y),
18023 ("U", &dec.u, &frame.reconstruction.u),
18024 ("V", &dec.v, &frame.reconstruction.v),
18025 ] {
18026 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18027 assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
18028 }
18029 }
18030 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18031 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18032 assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
18033 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
18034 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
18035 }
18036 }
18037 force_b128_ab(0);
18038 eprintln!(
18039 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
18040 unforced[0], unforced[1], unforced[2], unforced[3],
18041 );
18042 }
18043
18044 #[test]
18045 #[ignore = "sets the process-global superblock size: run it alone"]
18046 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
18047 let _knobs = crate::speed::knob_write();
18048 if !have_ffmpeg() {
18049 eprintln!("SKIP: no ffmpeg");
18050 return;
18051 }
18052 force_sb128(true);
18053 let dir = std::env::temp_dir().join(format!("ec-av1-sb128b-{}", std::process::id()));
18054 std::fs::create_dir_all(&dir).unwrap();
18055 let clip = dir.join("mandelbrot-1280x768.y4m");
18056 let ok = Command::new("ffmpeg")
18057 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "mandelbrot=size=1280x768:rate=24"])
18058 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
18059 .arg(&clip)
18060 .status()
18061 .expect("ffmpeg failed to run")
18062 .success();
18063 assert!(ok, "ffmpeg could not write the synthetic clip");
18064 let path = clip.to_str().unwrap();
18065 let (width, height) = (1280usize, 768usize);
18066 let pictures = crate::probe::source(path, "0", "null", width, height, 12);
18067
18068 let _ = crate::tile::take_drl_clamp_hits();
18069 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
18070 let clamps = crate::tile::take_drl_clamp_hits();
18071 assert!(
18072 clamps > 0,
18073 "this clip never asked for a drl index the write-time stack could not carry, \
18074 so it cannot witness the defect"
18075 );
18076 eprintln!("clamped drl indices: {clamps}");
18077
18078 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18079 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18080 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18081 let recon = &frame.reconstruction;
18082 for (plane, got, want) in [
18083 ("luma", &dec.y, &recon.y),
18084 ("U", &dec.u, &recon.u),
18085 ("V", &dec.v, &recon.v),
18086 ] {
18087 let differ = got.iter().zip(want).filter(|(a, b)| a != b).count();
18088 assert_eq!(
18089 differ, 0,
18090 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18091 own reconstruction",
18092 got.len()
18093 );
18094 }
18095 }
18096 }
18097
18098 #[test]
18099 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
18100 let _knobs = crate::speed::knob_read();
18101 let fctx = &crate::decode::FrameCtx::for_encoder();
18102 // 256x128, not the 128x64 this started at: once a leaf could search
18103 // its second reference (lane-av1comp4) the small card's every
18104 // eligible block went to a compound winner, which commits its flat
18105 // transform, and the split below stopped firing on content that
18106 // still splits at every larger size ([[gate-blind-to-feature]] --
18107 // the guard is right, the fixture had shrunk under it).
18108 let (width, height) = (256usize, 128usize);
18109 let pictures: Vec<Picture> =
18110 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
18111 let _ = take_inter_tx_split_hits();
18112 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18113 let raw = take_inter_tx_split_hits();
18114 // Summed over the four block classes the census keys on (leaf/32x32 x
18115 // single/compound): this assert is about the split firing at all.
18116 let split = [
18117 raw.iter().step_by(2).sum::<usize>(),
18118 raw.iter().skip(1).step_by(2).sum::<usize>(),
18119 ];
18120 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
18121 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
18122 // content splits -- a green round trip in which the split never fires
18123 // would prove only the flat path.
18124 if tx_select() && tx_select_inter() {
18125 assert!(split[1] > 0, "the inter var-tx split never fired");
18126 }
18127 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18128 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18129 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18130 let recon = &frame.reconstruction;
18131 for (plane, got, want, stride) in [
18132 ("luma", &dec.y, &recon.y, width),
18133 ("U", &dec.u, &recon.u, width / 2),
18134 ("V", &dec.v, &recon.v, width / 2),
18135 ] {
18136 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
18137 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
18138 panic!(
18139 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
18140 reconstruction {} ({} of {} samples differ)",
18141 at % stride,
18142 at / stride,
18143 got[at],
18144 want[at],
18145 got.iter().zip(want).filter(|(a, b)| a != b).count(),
18146 got.len(),
18147 );
18148 }
18149 }
18150 }
18151 }
18152
18153 /// The rate term the mode search ranks every decision by has to be the
18154 /// rate the writer then spends. The search prices a block's coefficients
18155 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
18156 /// against the default CDFs a tile starts from and the contexts of a
18157 /// block whose neighbours coded nothing -- while the tile writer codes
18158 /// them against a state that has been adapting all frame (the
18159 /// price-the-narrowing class). This measures that drift: the sum of what
18160 /// the search paid for the coefficients it kept, against the bytes the
18161 /// writer actually emitted for the whole tile (which also carries the
18162 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
18163 /// expected to be the larger of the two).
18164 #[test]
18165 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
18166 let _knobs = crate::speed::knob_read();
18167 let fctx = &crate::decode::FrameCtx::for_encoder();
18168 let (width, height) = (256usize, 128usize);
18169 let pictures: Vec<Picture> = (0..5)
18170 .map(|i| panned_test_card(width, height, i * 2))
18171 .collect();
18172 let _ = take_predicted_bits();
18173 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18174 let predicted = take_predicted_bits();
18175 assert_eq!(predicted.len(), encoded.frames.len());
18176
18177 eprintln!("frame predicted bits written bits drift");
18178 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
18179 // defect this gate exists to catch), a positive one is the written
18180 // side carrying syntax the coefficient sum leaves out -- and since
18181 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
18182 // on that side, so the two directions no longer share a bound.
18183 let mut worst_over: f64 = 0.0;
18184 let mut worst_under: f64 = 0.0;
18185 // The census is per CODED frame, so it is zipped in coding order --
18186 // which is not display order under a pyramid.
18187 let coded: Vec<&Encoded> =
18188 encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect();
18189 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
18190 let written = frame.tile.len() as f64 * 8.0;
18191 let drift = (written - bits) / written;
18192 worst_over = worst_over.max(-drift);
18193 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
18194 // all (150-250 bits of tile, nearly all of it partition/mode/mv
18195 // syntax the coefficient sum never counts), so its ratio measures
18196 // that floor rather than any drift. Frames under 512 written bits
18197 // are left out of the under-price bound for that reason; the
18198 // over-price bound -- the defect direction, where the search pays
18199 // MORE than the writer -- still covers every frame.
18200 if written >= 512.0 {
18201 worst_under = worst_under.max(drift);
18202 }
18203 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
18204 }
18205 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
18206 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
18207 // over-prices every frame but the last (its sum EXCLUDES the
18208 // partition/mode/skip/mv syntax the written side carries, so the true
18209 // coefficient over-price is larger still): the writer's CDFs adapt to
18210 // the content while the search's stay at the defaults. The bound is
18211 // set just above the worst measured point -- a widening drift is the
18212 // thing this gate exists to catch.
18213 assert!(
18214 worst_over <= 0.16,
18215 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
18216 worst_over * 100.0
18217 );
18218 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
18219 // the worst inter frame, where nearly every block now codes an MV
18220 // residual and a reference the coefficient sum never counts. Re-measured
18221 // at +29.6% once the encoder's grid published compound blocks properly
18222 // (compound share 8.8% -> 11.5%): a compound block carries a second
18223 // reference tree, a compound mode symbol and -- for the half-new modes
18224 // -- an MV residual, none of which the coefficient sum counts.
18225 // lane-av1txbits: pricing against the tables the frame's writer really
18226 // starts from collapses the over-price above to nothing, so the whole
18227 // remaining gap is the syntax the coefficient sum leaves out. That is
18228 // the default on a non-screen frame since lane-av1price2 (this
18229 // fixture is one), and it reads +32.6% here.
18230 // lane-av1obmc: every eligible single-reference inter block now also
18231 // carries a `motion_mode` symbol the coefficient sum never counts,
18232 // and an OBMC block carries the more expensive of the two values --
18233 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
18234 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
18235 // decisions, so this bound and the byte pins above FAIL BY DESIGN
18236 // under it; the default path (no motion_mode syntax at all) is the
18237 // one they are measured on.
18238 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
18239 // coding pyramid now, so the five frames are a key frame, a hidden
18240 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
18241 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
18242 // near-empty leaves below it. Both bounds stand where they were.
18243 // lane-av1rejudge: local warp is ON by default now, so every eligible
18244 // single-reference block carries that same `motion_mode` symbol (a
18245 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
18246 // +34.9% here, one point past the OBMC reading above. The bound moves
18247 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
18248 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
18249 // symbol and one or two magnitude symbols, none of which the
18250 // coefficient sum counts either -- +36.9% here against the same
18251 // fixture's +34.9% with `EC_AV1_CFL=0`.
18252 // ... and a directional block whose `angle_delta_y` is no longer
18253 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
18254 assert!(
18255 worst_under <= 0.40,
18256 "the writer spent {:.2}% more than the search priced -- more than \
18257 the mode/mv syntax outside the coefficient sum explains",
18258 worst_under * 100.0
18259 );
18260 }
18261
18262 /// The census behind step (1) of the pricer lane: for every transform
18263 /// block the writer really codes, what the search priced those levels at
18264 /// against what the writer spent on them, split by table set and non-zero
18265 /// count. One average hides the interesting part -- the classes the
18266 /// estimate is systematically wrong about (all-zero blocks, the
18267 /// one-coefficient blocks the inter search lives on) -- so the split is
18268 /// printed and only the total is asserted on.
18269 #[test]
18270 fn pricer_error_census_by_block_class() {
18271 let _knobs = crate::speed::knob_read();
18272 let fctx = &crate::decode::FrameCtx::for_encoder();
18273 let (width, height) = (256usize, 128usize);
18274 let pictures: Vec<Picture> = (0..5)
18275 .map(|i| panned_test_card(width, height, i * 2))
18276 .collect();
18277 crate::tile::pricer_census_on();
18278 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18279 let rows = crate::tile::take_pricer_census();
18280 assert!(!rows.is_empty(), "the census saw no transform block");
18281
18282 println!("| set | nz | blocks | priced bits | written bits | error |");
18283 println!("|---|---|---|---|---|---|");
18284 let (mut priced_all, mut written_all) = (0.0, 0.0);
18285 for ((set, bucket), (blocks, priced, written)) in &rows {
18286 priced_all += priced;
18287 written_all += written;
18288 println!(
18289 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
18290 crate::tile::census_bucket_label(*bucket),
18291 if *written > 0.0 {
18292 (priced - written) / written * 100.0
18293 } else {
18294 0.0
18295 }
18296 );
18297 }
18298 println!(
18299 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
18300 rows.values().map(|r| r.0).sum::<u64>(),
18301 (priced_all - written_all) / written_all * 100.0
18302 );
18303 assert!(written_all > 0.0);
18304 }
18305
18306 /// Step (2) of the pricer lane: the same census, but on the REAL clips
18307 /// the BD gate scores -- one film clip and the screen capture -- so the
18308 /// question the film/screen split raises can be answered from data. Real
18309 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
18310 /// the screen capture larger, and the census says why: on a screen
18311 /// capture the frame's own starting tables are the tables of a frame that
18312 /// coded PALETTE and long runs of zero blocks, so they are far from the
18313 /// tables the writer ends the frame with; the pricer error does not fall
18314 /// the way it does on film.
18315 ///
18316 /// Not a gate -- it prints. Run it once per mode:
18317 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
18318 /// --ignored pricer_error_census_on_clips --nocapture
18319 #[test]
18320 #[ignore = "reads the real library, needs ffmpeg"]
18321 fn pricer_error_census_on_clips() {
18322 let _knobs = crate::speed::knob_write();
18323 if !have_ffmpeg() {
18324 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
18325 return;
18326 }
18327 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
18328 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
18329 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
18330 if film.exists() {
18331 clips.push(("film 1080p".to_string(), film));
18332 }
18333 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
18334 && let Some(p) = manifest
18335 .lines()
18336 .skip(1)
18337 .filter_map(|l| l.split('\t').next())
18338 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
18339 {
18340 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
18341 }
18342 assert!(!clips.is_empty(), "no source clip available");
18343 let (width, height, frames) = (640usize, 384usize, 6usize);
18344 for (name, path) in &clips {
18345 let fctx = &crate::decode::FrameCtx::for_encoder();
18346 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
18347 SCREEN_FRAMES.iter().for_each(|c| {
18348 c.store(0, std::sync::atomic::Ordering::Relaxed);
18349 });
18350 let _ = crate::tile::take_pricing_hits();
18351 crate::tile::pricer_census_on();
18352 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18353 let rows = crate::tile::take_pricer_census();
18354 let (price_default, price_real) = crate::tile::take_pricing_hits();
18355 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
18356 println!(
18357 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
18358 {screen_on}, pricer armings default={price_default} real={price_real}"
18359 );
18360 println!("| set | nz | blocks | priced bits | written bits | error |");
18361 println!("|---|---|---|---|---|---|");
18362 let (mut priced_all, mut written_all) = (0.0, 0.0);
18363 for ((set, bucket), (blocks, priced, written)) in &rows {
18364 priced_all += priced;
18365 written_all += written;
18366 println!(
18367 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
18368 crate::tile::census_bucket_label(*bucket),
18369 if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
18370 );
18371 }
18372 println!(
18373 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
18374 rows.values().map(|r| r.0).sum::<u64>(),
18375 (priced_all - written_all) / written_all * 100.0
18376 );
18377 assert!(written_all > 0.0, "{name}: the census saw no transform block");
18378 }
18379 }
18380
18381 /// Low motion has to actually buy something: at least one inter frame of
18382 /// a panning sequence has to cost fewer bytes than the key frame that
18383 /// starts it, and the inter-block share it prints has to be non-zero --
18384 /// a search that never picks an inter mode would still pass a rate gate
18385 /// on a picture with no motion in it (the class this repo calls
18386 /// gate-blind-to-feature), so the share is printed even though it is not
18387 /// asserted on beyond being reachable at all.
18388 #[test]
18389 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
18390 let _knobs = crate::speed::knob_read();
18391 let fctx = &crate::decode::FrameCtx::for_encoder();
18392 let (width, height) = (256usize, 128usize);
18393 let pictures: Vec<Picture> = (0..5)
18394 .map(|i| panned_test_card(width, height, i * 2))
18395 .collect();
18396 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18397
18398 let key_bytes = encoded.frames[0].stream.len();
18399 eprintln!("frame bytes inter share");
18400 for (i, frame) in encoded.frames.iter().enumerate() {
18401 eprintln!(
18402 "{i:5} {:5} {:11.2}",
18403 frame.stream.len(),
18404 frame.inter_block_share
18405 );
18406 }
18407 assert!(
18408 encoded.frames[1..]
18409 .iter()
18410 .any(|f| f.stream.len() < key_bytes),
18411 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
18412 );
18413 assert!(
18414 encoded.frames[1..]
18415 .iter()
18416 .any(|f| f.inter_block_share > 0.0),
18417 "no inter frame coded a single inter block -- the search never fired"
18418 );
18419 }
18420
18421 /// A manual perf probe, not a gate: prints where a key frame's and an
18422 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
18423 /// measures before it optimizes rather than guessing. Run with
18424 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
18425 #[test]
18426 #[ignore = "a perf probe, not a gate"]
18427 fn stage_timing_breakdown() {
18428 let _knobs = crate::speed::knob_read();
18429 let fctx = &crate::decode::FrameCtx::for_encoder();
18430 use std::time::Instant;
18431
18432 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
18433 let picture = test_card(width, height);
18434
18435 let t = Instant::now();
18436 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
18437 let dc_only_t = t.elapsed();
18438
18439 let t = Instant::now();
18440 let non_directional =
18441 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
18442 let non_directional_t = t.elapsed();
18443
18444 let t = Instant::now();
18445 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18446 let all_modes_t = t.elapsed();
18447
18448 eprintln!(
18449 "\n=== key frame {width}x{height} ===\n\
18450 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
18451 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
18452 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
18453 dc_only.stream.len(),
18454 non_directional.stream.len(),
18455 all_modes.stream.len(),
18456 );
18457
18458 // One inter frame predicting off the key frame's own
18459 // reconstruction, the (256, 256)-padded surface encode_sequence
18460 // itself would hand encode_inter_frame.
18461 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
18462 let padded_pic = picture.padded_to(SUPERBLOCK);
18463 let t = Instant::now();
18464 let inter =
18465 encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[]).unwrap();
18466 let inter_t = t.elapsed();
18467 eprintln!(
18468 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
18469 {:.2})",
18470 inter.stream.len(),
18471 inter.inter_block_share
18472 );
18473 }
18474
18475 // Isolated per-call cost of the trial pipeline's own stages, at both
18476 // transform sizes the search runs, averaged over enough calls to
18477 // rise above `Instant::now`'s own noise.
18478 for side in [16usize, 32] {
18479 const N: u32 = 20_000;
18480 let residual: Vec<i32> = (0..side * side)
18481 .map(|i| ((i * 37 % 61) as i32) - 30)
18482 .collect();
18483
18484 let t = Instant::now();
18485 let mut levels = Vec::new();
18486 for _ in 0..N {
18487 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
18488 }
18489 let forward_t = t.elapsed() / N;
18490
18491 let t = Instant::now();
18492 for _ in 0..N {
18493 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
18494 }
18495 let inverse_t = t.elapsed() / N;
18496
18497 let set = if side == 32 {
18498 crate::cdf_state::TxbSet::Luma32
18499 } else {
18500 crate::cdf_state::TxbSet::Luma16
18501 };
18502 let t = Instant::now();
18503 for _ in 0..N {
18504 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
18505 }
18506 let entropy_t = t.elapsed() / N;
18507
18508 let above = vec![128u8; side * 2];
18509 let left = vec![128u8; side * 2];
18510 let mut prediction = vec![0u8; side * side];
18511 let t = Instant::now();
18512 for _ in 0..N {
18513 intra_predict_u8(
18514 D45_PRED,
18515 0,
18516 Some(&above),
18517 Some(&left),
18518 Some(128),
18519 side,
18520 side,
18521 false,
18522 false,
18523 &mut prediction, fctx,
18524 );
18525 }
18526 let predict_t = t.elapsed() / N;
18527
18528 eprintln!(
18529 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
18530 predict (1 directional mode): {predict_t:>9.2?}\n\
18531 forward_and_quantize: {forward_t:>9.2?}\n\
18532 dequant_and_inverse: {inverse_t:>9.2?}\n\
18533 coeff_bits: {entropy_t:>9.2?}"
18534 );
18535 }
18536 }
18537
18538 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
18539 /// (motion search, [`crate::mc::predict`], transform+quantize,
18540 /// `coeff_bits`), plus what is left over once those are subtracted --
18541 /// the thirteen-mode intra-candidate loop `search_inter_block` still
18542 /// runs on every inter block (its own transform/quant/entropy calls are
18543 /// already inside buckets 2/3, so "left over" here is everything NOT
18544 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
18545 /// symbol-cost lookups outside `coeff_bits`).
18546 ///
18547 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
18548 #[test]
18549 #[ignore = "a perf probe, not a gate"]
18550 fn stage_timing_breakdown_inter() {
18551 let _knobs = crate::speed::knob_read();
18552 let fctx = &crate::decode::FrameCtx::for_encoder();
18553 use std::time::Instant;
18554
18555 let (width, height) = (1280usize, 720);
18556 let picture = test_card(width, height);
18557 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18558 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
18559 let padded_pic = picture.padded_to(SUPERBLOCK);
18560
18561 stage_reset();
18562 let t = Instant::now();
18563 let inter =
18564 encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[]).unwrap();
18565 let total_t = t.elapsed();
18566 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
18567 let accounted = motion_search + transform_quant + entropy;
18568 // motion_search already contains interpolation's own time (every
18569 // candidate the search costs calls crate::mc::predict), so it is not
18570 // added again here -- interpolation is reported alongside as "of
18571 // which interpolation", not as a fifth additive bucket.
18572 let other = total_t.saturating_sub(accounted);
18573
18574 eprintln!(
18575 "\n=== inter frame {width}x{height}, one frame ===\n\
18576 total: {total_t:>9.2?} ({} bytes)\n\
18577 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
18578 {interpolation:>9.2?})\n\
18579 transform + quantize: {transform_quant:>9.2?}\n\
18580 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
18581 everything else (13-mode intra {other:>9.2?}\n\
18582 candidate loop's own predict/bookkeeping, NEARESTMV's own \
18583 predict, RD glue):",
18584 inter.stream.len(),
18585 );
18586 }
18587
18588 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
18589 /// frames (a dark/flat one, a detailed one, a normal film one) at two
18590 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
18591 /// None`, the baseline this same build produces without
18592 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
18593 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
18594 /// go in the lane report, which is where "ship as default" is decided --
18595 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
18596 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
18597 #[test]
18598 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
18599 fn prune_k_quality_sweep() {
18600 let _knobs = crate::speed::knob_read();
18601 let fctx = &crate::decode::FrameCtx::for_encoder();
18602 if !have_ffmpeg() {
18603 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
18604 return;
18605 }
18606 let (width, height) = (640usize, 352usize);
18607 let frames: &[(&str, &str, &str)] = &[
18608 // (label, clip, seek) -- a near-black scene, a busy one, and an
18609 // ordinary film frame, each from a different real file.
18610 (
18611 "dark/flat",
18612 "/home/user/Videos/reela.mp4",
18613 "3",
18614 ),
18615 (
18616 "detailed",
18617 "/home/user/Downloads/reelb.mkv",
18618 "1200",
18619 ),
18620 (
18621 "film",
18622 "/home/user/Videos/Films/reelc.mkv",
18623 "600",
18624 ),
18625 ];
18626 for &(label, clip, skip) in frames {
18627 if !std::path::Path::new(clip).exists() {
18628 eprintln!("SKIP {label}: {clip} not present on this machine");
18629 continue;
18630 }
18631 let picture = clip_frame(clip, skip, width, height);
18632 for &q in &[60u8, 150] {
18633 // SAFETY (not literally unsafe, just process-global): this is
18634 // a single-threaded #[ignore] probe, run by hand, never
18635 // alongside other tests that read Search::top_k.
18636 set_test_top_k_override(None);
18637 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18638 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
18639 eprint!(
18640 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
18641 baseline.stream.len(),
18642 baseline_psnr
18643 );
18644 for &k in &[3usize, 4, 6] {
18645 set_test_top_k_override(Some(k));
18646 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18647 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
18648 eprint!(
18649 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
18650 pruned.stream.len(),
18651 pruned_psnr,
18652 pruned_psnr - baseline_psnr
18653 );
18654 }
18655 eprintln!();
18656 }
18657 }
18658 set_test_top_k_override(None);
18659 }
18660
18661 /// Two consecutive decoded frames from one clip, for an inter-frame
18662 /// sweep -- [`clip_frame`] alone only ever gives one.
18663 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
18664 let out = Command::new("ffmpeg")
18665 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
18666 .args(["-vf", &format!("scale={width}:{height}")])
18667 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
18668 .output()
18669 .expect("ffmpeg failed to run");
18670 assert!(
18671 out.status.success(),
18672 "ffmpeg: {}",
18673 String::from_utf8_lossy(&out.stderr)
18674 );
18675 let (luma, chroma) = (width * height, width * height / 4);
18676 let frame_len = luma + 2 * chroma;
18677 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
18678 std::array::from_fn(|i| {
18679 let bytes = &out.stdout[i * frame_len..][..frame_len];
18680 Picture {
18681 width,
18682 height,
18683 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
18684 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
18685 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
18686 }
18687 })
18688 }
18689
18690 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
18691 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
18692 /// then one inter frame off it (`search_inter_block`'s own intra
18693 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
18694 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
18695 /// padding step complicates the comparison. Prints bytes and luma PSNR
18696 /// for the inter frame alone, unpruned vs each `K`.
18697 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
18698 #[test]
18699 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
18700 fn prune_k_quality_sweep_inter() {
18701 let _knobs = crate::speed::knob_read();
18702 let fctx = &crate::decode::FrameCtx::for_encoder();
18703 if !have_ffmpeg() {
18704 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
18705 return;
18706 }
18707 let (width, height) = (1280usize, 704usize);
18708 let frames: &[(&str, &str, &str)] = &[
18709 (
18710 "dark/flat",
18711 "/home/user/Videos/reela.mp4",
18712 "3",
18713 ),
18714 (
18715 "detailed",
18716 "/home/user/Downloads/reelb.mkv",
18717 "1200",
18718 ),
18719 (
18720 "film",
18721 "/home/user/Videos/Films/reelc.mkv",
18722 "600",
18723 ),
18724 ];
18725 for &(label, clip, skip) in frames {
18726 if !std::path::Path::new(clip).exists() {
18727 eprintln!("SKIP {label}: {clip} not present on this machine");
18728 continue;
18729 }
18730 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
18731 for &q in &[60u8, 150] {
18732 // SAFETY (not literally unsafe, just process-global): a
18733 // single-threaded #[ignore] probe, run by hand, never
18734 // alongside other tests that read Search::top_k.
18735 set_test_top_k_override_inter(None);
18736 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
18737 let baseline = encode_inter_frame(
18738 &inter_source,
18739 &key.reconstruction,
18740 q,
18741 0.5,
18742 1,
18743 flat_order_hints(1, 0, false),
18744 (width, height), None, None, None, None, fctx, None, &[],
18745 )
18746 .unwrap();
18747 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
18748 eprint!(
18749 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
18750 baseline.stream.len(),
18751 baseline_psnr
18752 );
18753 for &k in &[3usize, 4, 6] {
18754 set_test_top_k_override_inter(Some(k));
18755 let pruned = encode_inter_frame(
18756 &inter_source,
18757 &key.reconstruction,
18758 q,
18759 0.5,
18760 1,
18761 flat_order_hints(1, 0, false),
18762 (width, height), None, None, None, None, fctx, None, &[],
18763 )
18764 .unwrap();
18765 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
18766 eprint!(
18767 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
18768 pruned.stream.len(),
18769 pruned_psnr,
18770 pruned_psnr - baseline_psnr
18771 );
18772 }
18773 eprintln!();
18774 }
18775 }
18776 set_test_top_k_override_inter(None);
18777 }
18778
18779 /// `frames` consecutive pictures out of a real clip, scaled to a whole
18780 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
18781 /// to an arbitrary count for the fixture regression gate below.
18782 fn clip_frames(
18783 clip: &str,
18784 skip: &str,
18785 width: usize,
18786 height: usize,
18787 frames: usize,
18788 ) -> Vec<Picture> {
18789 clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames)
18790 }
18791
18792 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
18793 /// for a native-resolution CROP instead of a downscale (the downscale is
18794 /// what destroys a screen capture's exact repeats -- class
18795 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
18796 fn clip_frames_vf(
18797 clip: &str,
18798 skip: &str,
18799 vf: &str,
18800 width: usize,
18801 height: usize,
18802 frames: usize,
18803 ) -> Vec<Picture> {
18804 // ONE definition of the gate's loader recipe, shared with
18805 // `examples/enc_probe` so the instrument cannot arm a different source
18806 // than the gate it reports on (class `instrument disagrees with the
18807 // gate`; lane-probe).
18808 crate::probe::source(clip, skip, vf, width, height, frames)
18809 }
18810
18811 /// The standing regression gate on real content: 12 frames of a real
18812 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
18813 /// this crate's own input regardless of its own source codec), encoded
18814 /// as an AV1 GOP and checked against three numeric floors so a
18815 /// compatibility or quality regression fails the suite instead of
18816 /// waiting for a downstream repo's gate to catch it (as happened for a
18817 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
18818 /// refusal, both caught only that way).
18819 ///
18820 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
18821 /// that geometry is already covered elsewhere), chosen only so encode
18822 /// time and gate numbers are not muddied by an edge-block class this
18823 /// test is not about.
18824 ///
18825 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
18826 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
18827 /// below carry a margin off those measured numbers (PSNR floor =
18828 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
18829 #[test]
18830 fn real_clip_encodes_within_its_quality_and_size_budget() {
18831 let _knobs = crate::speed::knob_read();
18832 let fctx = &crate::decode::FrameCtx::for_encoder();
18833 if !have_ffmpeg() {
18834 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
18835 return;
18836 }
18837 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18838 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
18839 if !clip.exists() {
18840 eprintln!(
18841 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
18842 clip.display()
18843 );
18844 return;
18845 }
18846 let (width, height, frame_count) = (640usize, 384usize, 12usize);
18847 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
18848 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18849 assert_eq!(encoded.frames.len(), frame_count);
18850
18851 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
18852 // stream and hands back every frame -- a stream a downstream
18853 // decoder refuses is the exact class of regression this gate
18854 // exists for.
18855 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
18856 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
18857
18858 // Gate 2: quality vs the source did not silently collapse.
18859 let mean_psnr: f64 = decoded
18860 .iter()
18861 .zip(&source)
18862 .map(|(d, s)| psnr(&d.y, &s.y))
18863 .sum::<f64>()
18864 / frame_count as f64;
18865 assert!(
18866 mean_psnr >= 44.91,
18867 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
18868 );
18869
18870 // Gate 3: the stream did not silently bloat.
18871 assert!(
18872 encoded.stream.len() <= 80_340,
18873 "stream grew to {} bytes, over the 80340-byte ceiling",
18874 encoded.stream.len()
18875 );
18876 }
18877
18878 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
18879 /// straddle size: 640x384 is exact on both axes (32-aligned), so
18880 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
18881 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
18882 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
18883 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
18884 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
18885 /// card; this one is the real-clip gate, same three floors.
18886 ///
18887 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
18888 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
18889 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
18890 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
18891 #[test]
18892 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
18893 let _knobs = crate::speed::knob_read();
18894 let fctx = &crate::decode::FrameCtx::for_encoder();
18895 if !have_ffmpeg() {
18896 eprintln!(
18897 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
18898 no ffmpeg"
18899 );
18900 return;
18901 }
18902 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18903 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
18904 if !clip.exists() {
18905 eprintln!(
18906 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
18907 {} missing",
18908 clip.display()
18909 );
18910 return;
18911 }
18912 let (width, height, frame_count) = (704usize, 400usize, 8usize);
18913 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
18914 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18915 assert_eq!(encoded.frames.len(), frame_count);
18916
18917 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
18918 // stream and hands back every frame.
18919 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
18920 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
18921
18922 // Gate 2: quality vs the source did not silently collapse.
18923 let mean_psnr: f64 = decoded
18924 .iter()
18925 .zip(&source)
18926 .map(|(d, s)| psnr(&d.y, &s.y))
18927 .sum::<f64>()
18928 / frame_count as f64;
18929 assert!(
18930 mean_psnr >= 44.98,
18931 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
18932 );
18933
18934 // Gate 3: the stream did not silently bloat.
18935 assert!(
18936 encoded.stream.len() <= 62_703,
18937 "stream grew to {} bytes, over the 62703-byte ceiling",
18938 encoded.stream.len()
18939 );
18940 }
18941
18942 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
18943 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
18944 /// facade -- timed end to end, so the edith export-time projection is a
18945 /// real number rather than a guess from the isolated key/inter numbers
18946 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
18947 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
18948 #[test]
18949 #[ignore = "a perf probe, not a gate"]
18950 fn sequence_bench_sanity() {
18951 let _knobs = crate::speed::knob_read();
18952 let fctx = &crate::decode::FrameCtx::for_encoder();
18953 use std::time::Instant;
18954 let (width, height) = (1280usize, 720usize);
18955 let pictures: Vec<Picture> = (0..24)
18956 .map(|i| panned_test_card(width, height, i * 3))
18957 .collect();
18958 let t = Instant::now();
18959 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18960 let elapsed = t.elapsed();
18961 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
18962 eprintln!(
18963 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
18964 elapsed / 24
18965 );
18966 }
18967
18968 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
18969 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
18970 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
18971 /// -- --ignored --nocapture`.
18972 #[test]
18973 #[ignore = "a calibration probe, not a gate"]
18974 fn calibration_sweep_base_q_idx() {
18975 let _knobs = crate::speed::knob_read();
18976 let fctx = &crate::decode::FrameCtx::for_encoder();
18977 if !have_ffmpeg() {
18978 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
18979 return;
18980 }
18981 let (width, height, frames) = (640usize, 384usize, 12usize);
18982 for clip in [
18983 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
18984 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
18985 ] {
18986 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18987 .join("../../fixtures/video")
18988 .join(clip);
18989 if !path.exists() {
18990 eprintln!("SKIP {clip}: fixture missing");
18991 continue;
18992 }
18993 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
18994 eprintln!("--- {clip} ---");
18995 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
18996 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
18997 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
18998 let mean_psnr: f64 = decoded
18999 .iter()
19000 .zip(&source)
19001 .map(|(d, s)| psnr(&d.y, &s.y))
19002 .sum::<f64>()
19003 / frames as f64;
19004 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
19005 eprintln!(
19006 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
19007 encoded.stream.len()
19008 );
19009 }
19010 }
19011 }
19012
19013 // -----------------------------------------------------------------------
19014 // The encoder's standing BD-rate baseline against libaom and rav1e.
19015 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
19016 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
19017 // agreeing with our encoder proves nothing about the bitstream.
19018 // -----------------------------------------------------------------------
19019
19020 /// All-plane PSNR of a decoded picture against its source, on the same
19021 /// 8-bit scale [`psnr`] uses.
19022 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
19023 let cat = |p: &Picture| {
19024 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
19025 v.extend_from_slice(&p.y);
19026 v.extend_from_slice(&p.u);
19027 v.extend_from_slice(&p.v);
19028 v
19029 };
19030 psnr(&cat(decoded), &cat(source))
19031 }
19032
19033 /// The pictures back as the planar 8-bit bytes an encoder reads.
19034 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
19035 let mut raw = Vec::new();
19036 for p in source {
19037 for plane in [&p.y, &p.u, &p.v] {
19038 raw.extend(plane.iter().map(|&s| s as u8));
19039 }
19040 }
19041 raw
19042 }
19043
19044 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
19045 /// through ffmpeg: one point per entry of `points`, each a quality flag
19046 /// set. Returns the ladder ordered by fidelity and the total encode wall
19047 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
19048 /// so both curves are measured by the same decoder.
19049 fn external_ladder(
19050 source: &[Picture],
19051 width: usize,
19052 height: usize,
19053 encoder: &str,
19054 points: &[Vec<String>],
19055 ) -> (Vec<(f64, f64)>, f64) {
19056 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
19057 let dir = std::env::temp_dir();
19058 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
19059 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
19060 let mut ladder = Vec::new();
19061 let mut wall = 0.0;
19062 for (i, params) in points.iter().enumerate() {
19063 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
19064 let start = std::time::Instant::now();
19065 let out = Command::new("ffmpeg")
19066 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
19067 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
19068 .arg(&raw_path)
19069 .args(["-an", "-threads", "1"])
19070 .args(["-g", &source.len().to_string(), "-c:v", encoder])
19071 .args(params)
19072 .args(["-f", "obu"])
19073 .arg(&obu)
19074 .output()
19075 .expect("ffmpeg failed to run");
19076 wall += start.elapsed().as_secs_f64();
19077 assert!(
19078 out.status.success(),
19079 "{encoder} {params:?}: {}",
19080 String::from_utf8_lossy(&out.stderr)
19081 );
19082 let stream = std::fs::read(&obu).expect("reference stream");
19083 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
19084 // lane-dkey: every reference point must also decode through OUR
19085 // decoder, sample-exact against ffmpeg's decode of the same bytes.
19086 // A BD table computed off streams we cannot read is a table about
19087 // an encoder we cannot check; this is the assertion that would
19088 // have caught the `force_integer_mv` defect (its stream decoded to
19089 // 25 dB garbage while this gate stayed green) and the crf-5 key
19090 // frame desync. A failure names the encoder, the point's flags and
19091 // the first differing frame/plane/sample.
19092 // lane-dpm1: a failing reference point is COLLECTED, not panicked
19093 // on, so one run still prints the whole BD table and names every
19094 // bad point instead of stopping at the first. The collection is
19095 // asserted empty by [`assert_ladder_decodes`] at the end of each
19096 // gate.
19097 match crate::stream::decode_stream(&stream) {
19098 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
19099 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
19100 ours.len(),
19101 decoded.len(),
19102 )),
19103 Ok(ours) => {
19104 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
19105 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
19106 note_ladder_failure(format!(
19107 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
19108 decoder decoded {got}, ffmpeg {want}"
19109 ));
19110 break;
19111 }
19112 }
19113 }
19114 Err(e) => note_ladder_failure(format!(
19115 "{encoder} {params:?}: our decoder refused the stream ({e})"
19116 )),
19117 }
19118 let mean: f64 = decoded
19119 .iter()
19120 .zip(source)
19121 .map(|(d, s)| psnr_all(d, s))
19122 .sum::<f64>()
19123 / source.len() as f64;
19124 ladder.push((mean, (stream.len() as f64).log10()));
19125 let _ = std::fs::remove_file(&obu);
19126 }
19127 let _ = std::fs::remove_file(&raw_path);
19128 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19129 (ladder, wall)
19130 }
19131
19132 /// Every reference ladder point that did not decode sample-exactly
19133 /// through our own decoder, collected across a whole gate run so the BD
19134 /// table still prints and EVERY bad point is named
19135 /// (`encoder params frame plane sample`) instead of only the first.
19136 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
19137
19138 fn note_ladder_failure(msg: String) {
19139 eprintln!("LADDER DECODE FAILURE: {msg}");
19140 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
19141 }
19142
19143 /// Fail the gate at its END on everything [`external_ladder`] collected.
19144 fn assert_ladder_decodes() {
19145 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
19146 assert!(
19147 failures.is_empty(),
19148 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
19149 failures.len(),
19150 failures.join("\n"),
19151 );
19152 }
19153
19154 /// First differing sample between two pictures, as
19155 /// `(plane, index, left, right)` -- so a gate failure names the plane and
19156 /// the sample instead of just "differs". A length difference counts as a
19157 /// mismatch of that plane at the first index past the shorter one.
19158 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
19159 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
19160 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
19161 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
19162 }
19163 if l.len() != r.len() {
19164 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
19165 }
19166 }
19167 None
19168 }
19169
19170 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
19171 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
19172 /// stream is decoded twice -- by ffmpeg and by our own
19173 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
19174 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
19175 /// in Y, U and V over every shown frame in display order. That is itself
19176 /// a gate: it proves the bitstream says what the encoder thinks, in the
19177 /// only two decoders that read it.
19178 fn our_ladder(
19179 name: &str,
19180 source: &[Picture],
19181 width: usize,
19182 height: usize,
19183 fctx: &crate::decode::FrameCtx,
19184 ) -> (Vec<(f64, f64)>, f64) {
19185 let mut ladder = Vec::new();
19186 let mut wall = 0.0;
19187 for &q in &[150u8, 120, 90, 60] {
19188 let start = std::time::Instant::now();
19189 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
19190 // the gate has to be able to re-sweep it. 0.5 is the shipped one
19191 // (`crate::encoder::DEADZONE`).
19192 let deadzone = std::env::var("EC_AV1_DEADZONE")
19193 .ok()
19194 .and_then(|v| v.parse().ok())
19195 .unwrap_or(0.5);
19196 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
19197 wall += start.elapsed().as_secs_f64();
19198 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
19199 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19200 assert_eq!(
19201 ours.len(),
19202 source.len(),
19203 "{name} q={q}: our decoder's display-order frame count"
19204 );
19205 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
19206 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
19207 panic!(
19208 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
19209 {got}, the encoder reconstructed {want}"
19210 );
19211 }
19212 }
19213 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
19214 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
19215 panic!(
19216 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
19217 {got}, the encoder reconstructed {want}"
19218 );
19219 }
19220 }
19221 let per_frame: Vec<f64> = decoded.iter().zip(source).map(|(d, s)| psnr_all(d, s)).collect();
19222 // lane-txrd: does a tool's loss start at the FIRST inter frame
19223 // (a local mispricing) or grow down the GOP (propagation into
19224 // the reference chain)? One line per q point answers it.
19225 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
19226 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
19227 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
19228 // lane-txrd: per PLANE, because an all-plane mean hides a
19229 // collapse in one of them (class `metric blind to a plane`).
19230 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
19231 let v: Vec<String> = decoded
19232 .iter()
19233 .zip(source)
19234 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
19235 .collect();
19236 v.join(" ")
19237 };
19238 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
19239 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
19240 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
19241 }
19242 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
19243 ladder.push((mean, (encoded.stream.len() as f64).log10()));
19244 }
19245 // What this clip asked for and what the content gate left it coding
19246 // under: a screen clip requests a pyramid and codes flat, and that
19247 // difference is what keeps its row identical to the flat baseline
19248 // (class `gate-blind-to-feature`).
19249 eprintln!(
19250 "{name}: sequence, pyramid requested {:?} effective {:?}",
19251 crate::encoder::Pyramid::from_env(),
19252 last_sequence_pyramid(),
19253 );
19254 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19255 (ladder, wall)
19256 }
19257
19258 /// [`our_ladder`] through the streaming facade — the surface the editor's
19259 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
19260 /// each stream is also reordered (hidden `ALTREF` first,
19261 /// `show_existing_frame` last per group) and each level is coded at its
19262 /// own quantizer offset; without one it is the flat ladder, which
19263 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
19264 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
19265 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
19266 /// the whole ladder how many frames and how many bytes it spent, and the
19267 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
19268 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
19269 /// flat path, so a requested pyramid can come back `None` here.
19270 fn our_ladder_facade(
19271 name: &str,
19272 source: &[Picture],
19273 width: usize,
19274 height: usize,
19275 pyramid: Option<crate::encoder::Pyramid>,
19276 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) {
19277 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
19278 let slot = |l: Level| match l {
19279 Level::Key => 0,
19280 Level::Arf => 1,
19281 Level::Leaf => 2,
19282 Level::ShowExisting => 3,
19283 };
19284 let mut ladder = Vec::new();
19285 let mut wall = 0.0;
19286 let mut effective = None;
19287 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
19288 for &q in &[150u8, 120, 90, 60] {
19289 let config = EncoderConfig {
19290 width,
19291 height,
19292 base_q_idx: q,
19293 gop: source.len(),
19294 colour: Colour::Unspecified,
19295 tile_cols_log2: 0,
19296 tile_rows_log2: 0,
19297 };
19298 let start = std::time::Instant::now();
19299 let mut enc = match pyramid {
19300 None => Av1Encoder::new(config).unwrap(),
19301 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
19302 };
19303 let mut packets = Vec::new();
19304 for picture in source {
19305 packets.extend(enc.encode_frames(picture).unwrap());
19306 }
19307 packets.extend(enc.flush().unwrap());
19308 wall += start.elapsed().as_secs_f64();
19309 effective = enc.pyramid();
19310 let mut stream = Vec::new();
19311 for p in &packets {
19312 counts[slot(p.level)] += 1;
19313 bytes[slot(p.level)] += p.data.len();
19314 stream.extend_from_slice(&p.data);
19315 }
19316 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
19317 // correct if the DISPLAY-order output still has one frame per
19318 // source picture, in the right order -- checked against our own
19319 // decoder as well as ffmpeg's, both below.
19320 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
19321 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
19322 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
19323 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
19324 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
19325 panic!(
19326 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
19327 decoded {got}, our decoder decoded {want}"
19328 );
19329 }
19330 }
19331 let mean: f64 = decoded
19332 .iter()
19333 .zip(source)
19334 .map(|(d, s)| psnr_all(d, s))
19335 .sum::<f64>()
19336 / source.len() as f64;
19337 ladder.push((mean, (stream.len() as f64).log10()));
19338 }
19339 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19340 (ladder, wall, counts, bytes, effective)
19341 }
19342
19343 /// Byte-exactness gate for encoder work that is meant to change only
19344 /// how long the encoder takes.
19345 ///
19346 /// The BD gate above measures quality, which a speed lane can move by a
19347 /// hair without failing anything; this pins the streams themselves.
19348 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
19349 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
19350 /// in the tile) and again on lane-av1mv's merge of it: an extra
19351 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
19352 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
19353 /// prices coefficients against the tables the frame's writer really
19354 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
19355 /// decision change the BD gate judges. Re-pinned again on
19356 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
19357 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
19358 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
19359 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
19360 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
19361 /// by default ([`warp_on`], a sequence/frame header bit and a new
19362 /// motion_mode symbol on eligible blocks) and
19363 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
19364 /// every inter frame's superblocks now code at their own lambda
19365 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
19366 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
19367 /// and the two var-tx depth searches ([`tx32_depth_search`],
19368 /// [`compound_var_tx`]) are on by default, all three re-judged on the
19369 /// native gate's real film rows.
19370 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
19371 /// every block whose chroma takes it codes a different mode symbol, two
19372 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
19373 /// restores the previous streams. Re-pinned again in the same lane once
19374 /// directional luma winners searched their `angle_delta_y`
19375 /// (`EC_AV1_ANGLE=0` restores that half).
19376 #[test]
19377 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
19378 // These are DEFAULT-PRESET pins: a speed preset switches search levers
19379 // off, so it legitimately moves every byte. Encode at speed 0 whatever
19380 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
19381 let _knobs = crate::speed::knob_write();
19382 let was = crate::speed::speed();
19383 crate::speed::set_speed(0);
19384 if !have_ffmpeg() {
19385 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
19386 return;
19387 }
19388 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19389 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
19390 if !clip.exists() {
19391 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
19392 return;
19393 }
19394 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
19395 // FNV-1a over the stream: a witness that every coded bit is where it
19396 // was, which a byte count alone is not.
19397 let fnv = |b: &[u8]| {
19398 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
19399 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
19400 })
19401 };
19402 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
19403 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
19404 // of 4, its leaves at q+8 and a `show_existing_frame` header per
19405 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
19406 // four frames; four pictures is one short mini-GOP, which is the
19407 // shape that pays least (the ARF's own quality has no later group to
19408 // carry it), so this is not the BD gate's number.
19409 // Re-taken again on lane-av1cfl: the chroma search offers
19410 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
19411 // so every block taking either codes different syntax and different
19412 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
19413 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
19414 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
19415 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
19416 // so these four pictures code as one truncated group -- a hidden
19417 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
19418 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
19419 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
19420 // Re-taken on lane-fintra: the sequence header sets
19421 // `enable_filter_intra`, so every DC_PRED intra block of at most
19422 // 32x32 without a luma palette carries a `use_filter_intra` flag and
19423 // the blocks that take one code a filter-intra mode, a different
19424 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
19425 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
19426 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
19427 // (default pyramid `8:-32:16`, one truncated group of 8 with its
19428 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
19429 // root can code a REAL residual now (one TX_64X64 luma transform and
19430 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
19431 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
19432 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
19433 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
19434 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
19435 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
19436 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
19437 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
19438 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
19439 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
19440 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
19441 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
19442 // these four pictures -- offers every superblock a 64x64 intra root
19443 // now. `EC_AV1_I64=0` restores 8557 / 33345.
19444 // Re-taken on lane-pricer: the inter RD search prices a single
19445 // reference through the tree and the neighbour contexts the writer
19446 // really codes it with, so every inter picture's reference decisions
19447 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
19448 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
19449 // for `skip`/`is_inter` and for the whole compound reference tree, so
19450 // every inter block's cost -- and with it the skip and reference
19451 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
19452 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
19453 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
19454 // single and compound are priced against the same syntax -- 8311 ->
19455 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
19456 // Re-taken on lane-newmv: the motion search charges its own rate term
19457 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
19458 // and each subpel stage re-runs from its own winner
19459 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
19460 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
19461 // and 33014 -> 33090 at q=60.
19462 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
19463 // from libaom's objective tpl mapping, so every inter picture's
19464 // quantizer grid -- and every decision priced against it -- moved
19465 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
19466 // at the merge of both lanes.
19467 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
19468 // per-superblock `delta_qindex` at 1.5x the preset's strength
19469 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
19470 // grids -- and every decision priced against them -- moved:
19471 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
19472 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
19473 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
19474 // pixels -- and the leaves that predict from them -- moved:
19475 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
19476 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
19477 // the shipped stream did not move.
19478 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
19479 // picture is coded in 128x128 superblocks now, the inter ones
19480 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
19481 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
19482 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
19483 // by default, on top of the ARF temporal filter).
19484 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
19485 // candidates the 64 root already did ([`b128_compound`]), so every
19486 // inter frame that carries `reference_select` codes different blocks
19487 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
19488 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
19489 // Re-taken on lane-arftf: that filter's strength swept on the deciding
19490 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
19491 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
19492 // 33017 at q=60 (the same LENGTH, different bytes).
19493 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
19494 // lane-rlclamp onto the 128 compound default.
19495 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
19496 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
19497 // so every inter frame whose RD takes one codes a different partition
19498 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
19499 // quantizer the rect cut never wins its own comparison on this clip.
19500 // `EC_AV1_B128HV=0` restores 8290 exactly.
19501 let pins: [(u8, usize, u64); 2] = [(150, 8291, 0x1f00bb0eb099a27f), (60, 33227, 0x57ee6b1f8eacd881)];
19502 let coded: Vec<(u8, usize, u64)> = pins
19503 .iter()
19504 .map(|&(q, _, _)| {
19505 let e = encode_sequence(&source, q, 0.5).unwrap();
19506 (q, e.stream.len(), fnv(&e.stream))
19507 })
19508 .collect();
19509 crate::speed::set_speed(was);
19510 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
19511 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
19512 }
19513 }
19514
19515 /// A ladder is only a ladder if both axes rise together.
19516 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
19517 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
19518 for w in ladder.windows(2) {
19519 assert!(
19520 w[1].0 > w[0].0 && w[1].1 > w[0].1,
19521 "{name}: not monotone, {ladder:?}"
19522 );
19523 }
19524 }
19525
19526 /// The sweep behind [`screen_content`]'s constants
19527 /// (`unswept-decision-constants`), on the SAME five clips
19528 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
19529 /// same native crop: for each colour bound N the share of 16x16 luma
19530 /// blocks with 2..=N distinct colours, and the share of those whose
19531 /// per-pixel variance also clears a floor V -- libaom's
19532 /// `av1_set_screen_content_options` counts the variance-cleared blocks
19533 /// too (its `counts_2`, which gates intrabc), and without that term a
19534 /// smooth dark film frame reads as screen content.
19535 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
19536 #[test]
19537 #[ignore = "reads the real library"]
19538 fn probe_screen_detect() {
19539 let _knobs = crate::speed::knob_read();
19540 if !have_ffmpeg() {
19541 eprintln!("SKIP probe_screen_detect: no ffmpeg");
19542 return;
19543 }
19544 let limits = [4usize, 8, 16, 32, 64, 128];
19545 let floors = [0u64, 4, 16, 64, 256];
19546 // The census of one clip at one size: mean share, over the frames, of
19547 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
19548 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
19549 let mut acc = [[0f64; 5]; 6];
19550 for picture in frames {
19551 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
19552 let mut hit = [[0usize; 5]; 6];
19553 let mut blocks = 0usize;
19554 for by in (0..ch).step_by(16) {
19555 for bx in (0..cw).step_by(16) {
19556 let mut seen = [false; 256];
19557 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
19558 for row in 0..16 {
19559 for col in 0..16 {
19560 let v = y[(by + row) * cw + bx + col];
19561 sum += u64::from(v);
19562 sq += u64::from(v) * u64::from(v);
19563 if !seen[usize::from(v)] {
19564 seen[usize::from(v)] = true;
19565 colors += 1;
19566 }
19567 }
19568 }
19569 let var = (sq - sum * sum / 256) / 256;
19570 blocks += 1;
19571 for (li, &limit) in limits.iter().enumerate() {
19572 if colors > 1 && colors <= limit {
19573 for (fi, &floor) in floors.iter().enumerate() {
19574 hit[li][fi] += usize::from(var > floor);
19575 }
19576 }
19577 }
19578 }
19579 }
19580 for li in 0..6 {
19581 for fi in 0..5 {
19582 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
19583 }
19584 }
19585 }
19586 let n = frames.len().max(1) as f64;
19587 eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len());
19588 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>());
19589 for (li, &limit) in limits.iter().enumerate() {
19590 eprintln!(
19591 " {limit:>5} |{}",
19592 (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>()
19593 );
19594 }
19595 };
19596 for (name, path, seek) in native_gate_clips() {
19597 let Some((nw, nh)) = probe_dims(&path) else {
19598 eprintln!("SKIP {name}: ffprobe gave no size");
19599 continue;
19600 };
19601 let cw = nw.min(1920) / 128 * 128;
19602 let ch = nh.min(1024) / 128 * 128;
19603 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
19604 let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12);
19605 census(&name, &frames, cw, ch);
19606 // The 640x384 gate scales instead of cropping, and the scaling
19607 // changes the census (bars smooth out): the constants have to
19608 // separate at BOTH sizes.
19609 let small = clip_frames(&path, &seek, 640, 384, 12);
19610 census(&name, &small, 640, 384);
19611 }
19612 }
19613
19614 /// The detector against the WHOLE real library (class
19615 /// `unswept-decision-constants`, user rule "his data is the gate"):
19616 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
19617 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
19618 /// duration, four frames each, 8-bit 4:2:0, at native size or a
19619 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
19620 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
19621 /// Prints per file and offset the share of qualifying 16x16 blocks, the
19622 /// [`screen_content`] verdict and a content hint (mean luma, luma
19623 /// standard deviation, inter MAD), then sweeps the colour bound against
19624 /// the variance floor over the whole library: for each (N, V) the worst
19625 /// (highest) share among the camera/film rows against the best (lowest)
19626 /// among the screen-recording rows, so the rule with the widest gap can
19627 /// be read off. Rows carry the manifest index, codec and size only --
19628 /// no titles, no home paths.
19629 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
19630 #[test]
19631 #[ignore = "reads the real library"]
19632 fn probe_screen_library() {
19633 let _knobs = crate::speed::knob_read();
19634 if !have_ffmpeg() {
19635 eprintln!("SKIP probe_screen_library: no ffmpeg");
19636 return;
19637 }
19638 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
19639 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
19640 eprintln!("SKIP probe_screen_library: no real-library manifest");
19641 return;
19642 };
19643 let limits = [4usize, 8, 16, 32, 64];
19644 let floors = [0u64, 4, 8, 16, 32, 64, 128];
19645 // Whatever ffmpeg gave us, without the exact-count assertion the
19646 // gate loaders make: a seek near the end of a clip returns fewer
19647 // frames, and that is a row to print, not a panic.
19648 let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
19649 let out = Command::new("ffmpeg")
19650 .args(["-v", "error", "-ss", seek, "-i", clip])
19651 .args(["-frames:v", &n.to_string()])
19652 .args(["-vf", vf])
19653 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
19654 .output();
19655 let Ok(out) = out else { return Vec::new() };
19656 if !out.status.success() {
19657 return Vec::new();
19658 }
19659 let (luma, chroma) = (w * h, w * h / 4);
19660 let frame_len = luma + 2 * chroma;
19661 (0..out.stdout.len() / frame_len)
19662 .map(|i| {
19663 let b = &out.stdout[i * frame_len..][..frame_len];
19664 Picture {
19665 width: w,
19666 height: h,
19667 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
19668 u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
19669 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
19670 }
19671 })
19672 .collect()
19673 };
19674 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
19675 // variance > V, for every (N, V) of the sweep grid, over one frame.
19676 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
19677 let mut hit = [[0usize; 7]; 5];
19678 let mut blocks = 0usize;
19679 for by in (0..h).step_by(16) {
19680 for bx in (0..w).step_by(16) {
19681 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
19682 let mut seen = [false; 256];
19683 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
19684 for row in 0..bh {
19685 for col in 0..bw {
19686 let v = y[(by + row) * w + bx + col];
19687 sum += u64::from(v);
19688 sq += u64::from(v) * u64::from(v);
19689 if !seen[usize::from(v)] {
19690 seen[usize::from(v)] = true;
19691 colors += 1;
19692 }
19693 }
19694 }
19695 let n = (bh * bw) as u64;
19696 let var = (sq - sum * sum / n) / n;
19697 blocks += 1;
19698 for (li, &limit) in limits.iter().enumerate() {
19699 if colors > 1 && colors <= limit {
19700 for (fi, &floor) in floors.iter().enumerate() {
19701 hit[li][fi] += usize::from(var > floor);
19702 }
19703 }
19704 }
19705 }
19706 }
19707 let mut out = [[0f64; 7]; 5];
19708 for li in 0..5 {
19709 for fi in 0..7 {
19710 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
19711 }
19712 }
19713 out
19714 };
19715 // (index, label, path, duration, screen-by-its-own-content). The
19716 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
19717 // are desktop recordings; everything else in this library is camera
19718 // or film material.
19719 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
19720 for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] {
19721 let path = fixtures.join("video").join(file);
19722 if path.exists() {
19723 rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false));
19724 }
19725 }
19726 for (i, line) in manifest.lines().skip(1).enumerate() {
19727 let f: Vec<&str> = line.split('\t').collect();
19728 if f.len() < 10 {
19729 continue;
19730 }
19731 let (path, codec) = (f[0], f[2]);
19732 if codec == "-" || codec.is_empty() {
19733 continue;
19734 }
19735 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
19736 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
19737 continue;
19738 };
19739 if !std::path::Path::new(path).exists() {
19740 eprintln!("SKIP {}: file is gone", i + 1);
19741 continue;
19742 }
19743 let name = path.rsplit('/').next().unwrap_or(path);
19744 let is_capture = path.contains("/OBS/")
19745 || (name.len() > 19
19746 && name.as_bytes()[4] == b'-'
19747 && name.as_bytes()[7] == b'-'
19748 && name.as_bytes()[10] == b' '
19749 && name.as_bytes()[13] == b'-');
19750 rows.push((
19751 format!("{}", i + 1),
19752 format!("{codec} {w}x{h}"),
19753 path.to_string(),
19754 f[8].parse::<f64>().unwrap_or(0.0),
19755 is_capture,
19756 ));
19757 }
19758 // Per (N, V): the worst camera/film row and the best screen row, so
19759 // the separation of the whole library is one subtraction.
19760 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
19761 eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |");
19762 for (idx, label, path, dur, is_capture) in &rows {
19763 let Some((nw, nh)) = probe_dims(path) else {
19764 eprintln!("SKIP {idx}: ffprobe gave no size");
19765 continue;
19766 };
19767 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
19768 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
19769 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
19770 let mut file_grid = [[0f64; 7]; 5];
19771 let mut file_frames = 0usize;
19772 for pct in [10u32, 50, 90] {
19773 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
19774 let frames = decode(path, &seek, &vf, cw, ch, 4);
19775 if frames.is_empty() {
19776 eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" });
19777 continue;
19778 }
19779 let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64);
19780 let mut prev: Option<Vec<u8>> = None;
19781 for picture in &frames {
19782 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
19783 let grid = census(&y, cw, ch);
19784 for li in 0..5 {
19785 for fi in 0..7 {
19786 file_grid[li][fi] += grid[li][fi];
19787 }
19788 }
19789 file_frames += 1;
19790 // The shipped rule is (16 colours, var > 16): grid row 2,
19791 // floor 16 is column 3.
19792 share += grid[2][3];
19793 yes += usize::from(screen_content(&y, cw, cw, ch));
19794 let n = y.len() as f64;
19795 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
19796 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
19797 mean += sum / n;
19798 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
19799 if let Some(p) = &prev {
19800 mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n;
19801 }
19802 prev = Some(y);
19803 }
19804 let f = frames.len() as f64;
19805 eprintln!(
19806 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
19807 if *is_capture { "screen" } else { "camera" },
19808 share / f,
19809 if yes * 2 > frames.len() { "SCREEN" } else { "camera" },
19810 frames.len(),
19811 mean / f,
19812 sd / f,
19813 mad / (f - 1.0).max(1.0),
19814 );
19815 }
19816 if file_frames == 0 {
19817 continue;
19818 }
19819 for li in 0..5 {
19820 for fi in 0..7 {
19821 let s = file_grid[li][fi] / file_frames as f64;
19822 match is_capture {
19823 true => scr_min[li][fi] = scr_min[li][fi].min(s),
19824 false => cam_max[li][fi] = cam_max[li][fi].max(s),
19825 }
19826 }
19827 }
19828 }
19829 eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):");
19830 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>());
19831 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
19832 for (li, &limit) in limits.iter().enumerate() {
19833 let mut row = String::new();
19834 for fi in 0..7 {
19835 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
19836 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
19837 if s - c > best {
19838 best = s - c;
19839 best_rule = (limit, floors[fi]);
19840 }
19841 }
19842 eprintln!(" {limit:>5} |{row}");
19843 }
19844 // The threshold sits at the midpoint of the widest gap; the shipped
19845 // constant is its reciprocal in whole parts of the frame.
19846 let (li, fi) = (
19847 limits.iter().position(|&l| l == best_rule.0).unwrap(),
19848 floors.iter().position(|&f| f == best_rule.1).unwrap(),
19849 );
19850 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
19851 eprintln!(
19852 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
19853 best_rule.0,
19854 best_rule.1,
19855 best,
19856 cam_max[li][fi],
19857 scr_min[li][fi],
19858 mid,
19859 (100.0 / mid.max(0.1)).round() as usize,
19860 );
19861 }
19862
19863 /// The missing instrument: what this encoder costs against libaom and
19864 /// rav1e at matched fidelity, and how long it takes to get there.
19865 ///
19866 /// Recipe, identical on all three sides: 12 consecutive frames of each
19867 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
19868 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
19869 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
19870 /// it by default), 4:2:0 8-bit in and out. Reference points:
19871 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
19872 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
19873 /// tile_cols=1:tile_rows=1:threads=1`
19874 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
19875 /// ffmpeg-decoded frames of each encoder's own stream.
19876 ///
19877 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
19878 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
19879 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
19880 /// four encodes of that ladder together):
19881 ///
19882 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
19883 /// |---|---|---|---|---|
19884 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
19885 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
19886 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
19887 ///
19888 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
19889 /// the encoder takes -- every stream it writes is byte-identical, so the
19890 /// BD columns are this box's own re-run of the same recipe rather than a
19891 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
19892 /// rav1e). What moved is the wall of the four encodes:
19893 ///
19894 /// | clip | wall ours before | after | instructions:u before -> after |
19895 /// |---|---|---|---|
19896 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
19897 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
19898 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
19899 ///
19900 /// Three exact steps, none of which touches a coded bit: the coefficient
19901 /// rate pricer stopped rebuilding every CDF table per candidate
19902 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
19903 /// tile once per candidate (`decode::FilterReplay`), and the forward
19904 /// transform stopped transforming the all-zero residual that 70% of its
19905 /// calls carry.
19906 ///
19907 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
19908 ///
19909 /// | step | 1080p | 2160p | screen |
19910 /// |---|---|---|---|
19911 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
19912 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
19913 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
19914 ///
19915 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
19916 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
19917 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
19918 /// -- all three decided on the REAL film rows of
19919 /// [`bd_rate_screen_native`], which this downscaled recipe does not
19920 /// carry:
19921 ///
19922 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
19923 /// |---|---|---|---|
19924 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
19925 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
19926 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
19927 ///
19928 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
19929 /// DEFAULT of the sequence path this gate codes through -- the bars are
19930 /// non-screen so they take it, the capture is gated flat:
19931 ///
19932 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
19933 /// |---|---|---|---|---|
19934 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
19935 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
19936 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
19937 ///
19938 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
19939 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
19940 /// facade arm -- which is what "one mini-GOP driver, two entry points"
19941 /// means here. This downscaled recipe HATES the pyramid (as it hates
19942 /// every knob the real film rows of `bd_rate_screen_native` keep, which
19943 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
19944 /// above. The capture's row is the flat row to the byte in both runs --
19945 /// that equality IS the content gate.
19946 ///
19947 /// Loop restoration is NOT in yet: it is the one filter whose parameters
19948 /// are per restoration UNIT inside the tile payload, so it needs both
19949 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
19950 /// buffer to solve against -- neither of which this frame-header-level
19951 /// search reaches.
19952 ///
19953 /// The baseline it replaced, before an inter frame's blocks chose their
19954 /// own partition, was +501.4/+504.4/+440.9 against libaom and
19955 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
19956 ///
19957 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
19958 /// fidelity, while spending far more time than either (the partition
19959 /// search's own cost, uncut: see the two intra-pruning variants measured
19960 /// and rejected in the lane report). No
19961 /// threshold is asserted yet -- this run sets the baseline; the gate
19962 /// asserts four monotone points per ladder, and at EVERY ladder point of
19963 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
19964 /// `crate::stream::decode_stream` -- and asserts the encoder's
19965 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
19966 /// and V over every shown frame in display order. A failure names the
19967 /// clip, the q, the frame, the plane and the first differing sample.
19968 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
19969 /// which exposes no per-packet reconstruction, so that path asserts the
19970 /// two decoders against each other on all three planes.)
19971 ///
19972 /// Run:
19973 /// cargo test -p ec-av1 --release --lib -- --ignored \
19974 /// bd_rate_vs_libaom_and_rav1e --nocapture
19975 #[test]
19976 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
19977 fn bd_rate_vs_libaom_and_rav1e() {
19978 let _knobs = crate::speed::knob_write();
19979 if !have_ffmpeg() {
19980 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
19981 return;
19982 }
19983 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
19984 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
19985 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
19986 // rows for real content (the real rows live in the native gate).
19987 for (label, name) in [
19988 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
19989 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
19990 ] {
19991 let path = fixtures.join("video").join(name);
19992 if path.exists() {
19993 clips.push((label.to_string(), path));
19994 } else {
19995 eprintln!("SKIP clip {name}: missing");
19996 }
19997 }
19998 // Screen capture: the repo carries no screen-capture fixture, so take
19999 // the first OBS recording the real-library manifest names.
20000 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
20001 Ok(manifest) => {
20002 let screen = manifest
20003 .lines()
20004 .skip(1)
20005 .filter_map(|l| l.split('\t').next())
20006 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
20007 match screen {
20008 Some(p) => clips.push((
20009 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
20010 std::path::PathBuf::from(p),
20011 )),
20012 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
20013 }
20014 }
20015 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
20016 }
20017 assert!(!clips.is_empty(), "no source clip available");
20018
20019 let (width, height, frames) = (640usize, 384usize, 12usize);
20020 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
20021 .iter()
20022 .map(|q| {
20023 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
20024 .map(String::from)
20025 .to_vec()
20026 })
20027 .collect();
20028 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
20029 .iter()
20030 .map(|q| {
20031 vec![
20032 "-rav1e-params".to_string(),
20033 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
20034 ]
20035 })
20036 .collect();
20037 println!(
20038 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
20039 );
20040 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
20041 println!("|---|---|---|---|---|");
20042 for (name, path) in &clips {
20043 let fctx = &crate::decode::FrameCtx::for_encoder();
20044 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
20045 let _ = take_partition_hits();
20046 let _ = crate::tile::take_palette_hits();
20047 SCREEN_FRAMES.iter().for_each(|c| {
20048 c.store(0, std::sync::atomic::Ordering::Relaxed);
20049 });
20050 let _ = take_uv_mode_hits();
20051 let _ = crate::tile::take_inter_mode_hits();
20052 let _ = crate::tile::take_drl_hits();
20053 let _ = crate::tile::take_ref_hits();
20054 let _ = crate::tile::take_compound_mode_hits();
20055 let _ = crate::tile::take_compound_pair_hits();
20056 let _ = crate::tile::take_compound_size_hits();
20057 let _ = crate::tile::take_compound_leaf_mode_hits();
20058 let _ = take_b64_root_hits();
20059 let _ = take_b64_residual_hits();
20060 let _ = take_b64_compound_hits();
20061 let _ = crate::motion::take_census();
20062 // The entry-surface arm: run the SAME ladder through the
20063 // streaming facade the editor's export calls, which must print
20064 // the same BD numbers as the sequence path -- byte for byte the
20065 // same stream now that both drive one mini-GOP driver
20066 // (lane-av1pyrdef).
20067 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
20068 let (ours, ours_wall) = match facade {
20069 false => our_ladder(name, &source, width, height, fctx),
20070 true => {
20071 let pyramid = crate::encoder::Pyramid::from_env();
20072 let (ladder, wall, counts, bytes, effective) =
20073 our_ladder_facade(name, &source, width, height, pyramid);
20074 eprintln!(
20075 "{name}: facade, pyramid requested {pyramid:?} effective \
20076 {effective:?} -- frames key {} arf {} leaf {} \
20077 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
20078 counts[0], counts[1], counts[2], counts[3],
20079 bytes[0], bytes[1], bytes[2], bytes[3],
20080 );
20081 (ladder, wall)
20082 }
20083 };
20084 // How often the inter split actually fired over this clip's four
20085 // encodes, against the whole 32x32 that was the only outcome
20086 // before (gate-blind-to-feature).
20087 let [whole32, split32, whole16, split16] = take_partition_hits();
20088 // Which inter modes actually fired over this clip's four encodes,
20089 // and at which DRL index -- a mode nobody picks is a mode the BD
20090 // number cannot be crediting (gate-blind-to-feature).
20091 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
20092 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
20093 let refs = crate::tile::take_ref_hits();
20094 let modes_total = (nearest + near + global + new).max(1);
20095 eprintln!(
20096 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
20097 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
20098 {drl0}/{drl1}/{drl2}/{drl3}",
20099 100.0 * nearest as f64 / modes_total as f64,
20100 100.0 * near as f64 / modes_total as f64,
20101 100.0 * global as f64 / modes_total as f64,
20102 100.0 * new as f64 / modes_total as f64,
20103 );
20104 // The compound census: what share of the coded inter blocks took
20105 // a compound reference at all, which compound mode they took, and
20106 // which pair (gate-blind-to-feature -- a compound mode nobody
20107 // picks cannot be what a BD number credits).
20108 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
20109 // superblocks were left whole at all, and how many of those coded
20110 // a residual or took a compound reference.
20111 let (roots, root_res, root_comp) = (
20112 take_b64_root_hits(),
20113 take_b64_residual_hits(),
20114 take_b64_compound_hits(),
20115 );
20116 eprintln!(
20117 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
20118 );
20119 let comp_modes = crate::tile::take_compound_mode_hits();
20120 let comp_pairs = crate::tile::take_compound_pair_hits();
20121 let comp_sizes = crate::tile::take_compound_size_hits();
20122 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
20123 let comp_total: usize = comp_modes.iter().sum();
20124 eprintln!(
20125 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
20126 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
20127 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
20128 modes_total + comp_total,
20129 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
20130 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
20131 comp_modes[6], comp_modes[7],
20132 comp_pairs[3], comp_pairs[6],
20133 );
20134 eprintln!(
20135 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
20136 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
20137 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6],
20138 comp_leaf[7],
20139 );
20140 eprintln!(
20141 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
20142 comp_sizes[1], comp_sizes[2], comp_sizes[3],
20143 );
20144 // Where the wall-owning stage actually goes: how many candidate
20145 // evaluations (one `mc::predict` + SAD each) a search spends, how
20146 // many of them are subpel, and how often the winner is the seed
20147 // it started from -- the census the seeded search is judged by.
20148 let [calls, evals, subpel, rounds, near_pred, unmoved, widest, widest_moves] =
20149 crate::motion::take_census();
20150 let per = |n: u64| n as f64 / calls.max(1) as f64;
20151 eprintln!(
20152 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
20153 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
20154 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
20155 per(evals),
20156 100.0 * subpel as f64 / evals.max(1) as f64,
20157 per(rounds),
20158 100.0 * near_pred as f64 / calls.max(1) as f64,
20159 100.0 * unmoved as f64 / calls.max(1) as f64,
20160 );
20161 // lane-newmv, class `instrument at bound`: how often the winner
20162 // was walked to at the log stage's own WIDEST step -- a high
20163 // share means the search stops where its step lets it, not where
20164 // the content is.
20165 eprintln!(
20166 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
20167 100.0 * widest as f64 / calls.max(1) as f64,
20168 per(widest_moves),
20169 );
20170 eprintln!(
20171 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
20172 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
20173 );
20174 eprintln!(
20175 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
20176 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
20177 whole32 + split32,
20178 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
20179 whole16 + split16,
20180 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
20181 );
20182 // The deblocking level each of this clip's frames chose
20183 // (lane-av1filt): 0 everywhere would mean the filter never fires.
20184 let levels = crate::filter_search::take_chosen_levels();
20185 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
20186 let mean = |f: fn(&Chosen) -> u8| {
20187 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
20188 };
20189 eprintln!(
20190 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
20191 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
20192 levels.len(),
20193 mean(|l| l.0.0),
20194 mean(|l| l.0.1),
20195 mean(|l| l.1.0),
20196 mean(|l| l.1.1),
20197 mean(|l| l.2.0),
20198 mean(|l| l.2.1),
20199 );
20200 // How many strength presets each frame's CDEF list carried and
20201 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
20202 // everywhere would mean the per-unit choice never fires.
20203 let presets = crate::filter_search::take_cdef_presets();
20204 let mut by_bits = [0usize; 4];
20205 for (b, _) in &presets {
20206 by_bits[usize::from(*b)] += 1;
20207 }
20208 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
20209 let on_extra: usize = presets
20210 .iter()
20211 .flat_map(|(_, c)| c.iter().skip(1))
20212 .sum();
20213 eprintln!(
20214 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
20215 on a non-default preset ({:.1}%)",
20216 by_bits[0],
20217 by_bits[1],
20218 by_bits[2],
20219 by_bits[3],
20220 on_extra,
20221 units,
20222 100.0 * on_extra as f64 / units.max(1) as f64
20223 );
20224 // How the 64x64 luma restoration units split between
20225 // RESTORE_NONE and Wiener (lane-av1lr).
20226 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
20227 eprintln!(
20228 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
20229 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
20230 );
20231 // Which chroma modes the search actually wins with, against the
20232 // unconditional DC_PRED that was the only outcome before
20233 // (gate-blind-to-feature).
20234 // Screen-content detection and the palette it turns on
20235 // (gate-blind-to-feature): how many frames set
20236 // `allow_screen_content_tools`, how many blocks took a palette,
20237 // and of what size. A film clip must print `screen frames on=0`.
20238 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20239 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
20240 // Which tables the SEARCH priced against, per frame arming
20241 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
20242 // real starting ones. A film clip must show every inter arming on
20243 // the real side, a screen clip none of them.
20244 let (price_default, price_real) = crate::tile::take_pricing_hits();
20245 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
20246 let palette = crate::tile::take_palette_hits();
20247 eprintln!(
20248 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
20249 palette[0],
20250 (2..=8)
20251 .filter(|&n| palette[n] > 0)
20252 .map(|n| format!("{n}={}", palette[n]))
20253 .collect::<Vec<_>>()
20254 .join(" ")
20255 );
20256 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
20257 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
20258 // only ever fires at one magnitude is a search that never left
20259 // its first candidate (gate-blind-to-feature).
20260 // The luma angle-delta histogram (lane-av1cfl): how many
20261 // directional blocks won at each delta. All-zero would mean the
20262 // refinement never beat the base angle.
20263 let deltas = take_angle_delta_hits();
20264 if deltas.iter().sum::<usize>() > 0 {
20265 eprintln!(
20266 "{name}: angle_delta_y {}",
20267 deltas
20268 .iter()
20269 .enumerate()
20270 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
20271 .collect::<Vec<_>>()
20272 .join(" ")
20273 );
20274 }
20275 let alphas = take_cfl_alpha_hits();
20276 if alphas.iter().sum::<usize>() > 0 {
20277 eprintln!(
20278 "{name}: cfl |alpha| {}",
20279 alphas
20280 .iter()
20281 .enumerate()
20282 .filter(|&(_, &n)| n > 0)
20283 .map(|(a, &n)| format!("{a}={n}"))
20284 .collect::<Vec<_>>()
20285 .join(" ")
20286 );
20287 }
20288 let palette_uv = crate::tile::take_palette_uv_hits();
20289 eprintln!(
20290 "{name}: chroma palette blocks {} sizes {}",
20291 palette_uv[0],
20292 (2..=8)
20293 .filter(|&n| palette_uv[n] > 0)
20294 .map(|n| format!("{n}={}", palette_uv[n]))
20295 .collect::<Vec<_>>()
20296 .join(" ")
20297 );
20298 let uv = take_uv_mode_hits();
20299 let uv_total: usize = uv.iter().sum();
20300 eprintln!(
20301 "{name}: uv modes {}",
20302 uv.iter()
20303 .enumerate()
20304 .filter(|&(_, &n)| n > 0)
20305 .map(|(m, &n)| format!(
20306 "{}={n} ({:.1}%)",
20307 UV_MODE_NAMES[m],
20308 100.0 * n as f64 / uv_total.max(1) as f64
20309 ))
20310 .collect::<Vec<_>>()
20311 .join(" ")
20312 );
20313 // Which transform depth the intra blocks of this clip's key
20314 // frames resolved to (lane-av1tx): depth 0 is one transform over
20315 // the whole block, 1 and 2 its halvings.
20316 let depths = take_tx_depth_hits();
20317 let depth_total: usize = depths.iter().sum();
20318 eprintln!(
20319 "{name}: intra tx depths {}",
20320 depths
20321 .iter()
20322 .enumerate()
20323 .map(|(d, &n)| format!(
20324 "{d}={n} ({:.1}%)",
20325 100.0 * n as f64 / depth_total.max(1) as f64
20326 ))
20327 .collect::<Vec<_>>()
20328 .join(" ")
20329 );
20330 print_inter_tx_census(name);
20331 // lane-av1obmc: how many blocks actually CODED a motion_mode
20332 // symbol and which value they took, by footprint -- "OBMC is on"
20333 // as a measurement rather than a claim (class
20334 // `gate-blind-to-feature`).
20335 let mm = crate::tile::take_motion_mode_hits();
20336 eprintln!(
20337 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
20338 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
20339 eligible)",
20340 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
20341 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20342 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20343 mm.iter().sum::<usize>(),
20344 );
20345 let (aom, aom_wall) =
20346 external_ladder(&source, width, height, "libaom-av1", &aom_points);
20347 let (rav1e, rav1e_wall) =
20348 external_ladder(&source, width, height, "librav1e", &rav1e_points);
20349 assert_monotone(&format!("{name}: ours"), &ours);
20350 assert_monotone(&format!("{name}: libaom"), &aom);
20351 assert_monotone(&format!("{name}: rav1e"), &rav1e);
20352 let points = ours
20353 .iter()
20354 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20355 .collect::<Vec<_>>()
20356 .join(", ");
20357 println!(
20358 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
20359 bd_rate(&aom, &ours) * 100.0,
20360 bd_rate(&rav1e, &ours) * 100.0,
20361 );
20362 println!(
20363 "| references | libaom {} | rav1e {} | | |",
20364 aom.iter()
20365 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20366 .collect::<Vec<_>>()
20367 .join(", "),
20368 rav1e
20369 .iter()
20370 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20371 .collect::<Vec<_>>()
20372 .join(", "),
20373 );
20374 }
20375 assert_ladder_decodes();
20376 }
20377 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
20378 /// split by block class in lane-av1txdepth): depth 0 is one transform over
20379 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
20380 /// leaves and the 32x32 root, each single-reference or compound. A class
20381 /// with no counts at all never reached `commit_inter_luma` -- which is
20382 /// what its knob being off looks like (class `gate-blind-to-feature`).
20383 fn print_inter_tx_census(name: &str) {
20384 let splits = take_inter_tx_split_hits();
20385 let total: usize = splits.iter().sum();
20386 let row = |label: &str, base: usize| {
20387 let (n0, n1) = (splits[base], splits[base + 1]);
20388 format!(
20389 "{label} 0={n0} 1={n1} ({:.1}% split)",
20390 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
20391 )
20392 };
20393 eprintln!(
20394 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
20395 row("leaf single", 0),
20396 row("leaf compound", 2),
20397 row("32x32 single", 4),
20398 row("32x32 compound", 6),
20399 );
20400 // lane-txrd: which types the two searches actually COMMITTED over
20401 // this row's four encodes -- the gate could not say whether a type
20402 // search fired at all (class `gate-blind-to-feature`).
20403 const NAMES: [&str; 16] = [
20404 "IDTX", "DCT_DCT", "ADST_ADST", "ADST_DCT", "DCT_ADST", "V_DCT", "H_DCT",
20405 "FLIPADST_DCT", "DCT_FLIPADST", "FLIPADST_FLIPADST", "ADST_FLIPADST",
20406 "FLIPADST_ADST", "V_ADST", "H_ADST", "V_FLIPADST", "H_FLIPADST",
20407 ];
20408 let name_of = |t: usize| NAMES[t];
20409 for (label, hits) in [("inter", take_inter_tx_type_hits()), ("intra", take_tx_type_hits())] {
20410 let total: usize = hits.iter().sum();
20411 let live: Vec<String> = hits
20412 .iter()
20413 .enumerate()
20414 .filter(|&(_, &n)| n > 0)
20415 .map(|(t, &n)| format!("{}={n} ({:.1}%)", name_of(t), 100.0 * n as f64 / total.max(1) as f64))
20416 .collect();
20417 eprintln!("{name}: {label} tx_type of {total} units -- {}", live.join(" "));
20418 }
20419 let t = take_txrd_stats();
20420 if t[0] > 0 {
20421 eprintln!(
20422 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
20423 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
20424 t[0], t[1], t[3] as f64 / 64.0, t[2], t[4] as f64 / 64.0,
20425 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
20426 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
20427 );
20428 eprintln!(
20429 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
20430 flat: dsse {:+.2}%, dbits {:+.2}%)",
20431 t[5], t[6] as f64 / 64.0,
20432 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
20433 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
20434 );
20435 }
20436 }
20437
20438 /// The video stream's coded size, from ffprobe.
20439 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
20440 crate::probe::dims(clip)
20441 }
20442
20443 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
20444 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
20445 /// superblock-aligned one, still centred and still even for 4:2:0.
20446 ///
20447 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
20448 /// superblocks by design, so no default gate row has a block the frame
20449 /// edge cuts through -- while every arbitrary export size does (3840x1608
20450 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
20451 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
20452 /// read on.
20453 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
20454 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
20455 let (w, h) = spec.split_once('x').expect("EC_AV1_NATIVE_CROP is <width>x<height>");
20456 let (cw, ch): (usize, usize) =
20457 (w.parse().expect("crop width"), h.parse().expect("crop height"));
20458 let (nw, nh) = crate::probe::dims(clip)?;
20459 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
20460 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
20461 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
20462 }
20463
20464 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
20465 /// with `probe_screen_detect` so the detector sweep measures exactly the
20466 /// clips the keep table is read off. Selector env vars as documented on
20467 /// the gate; a missing clip prints a SKIP and drops its row.
20468 fn native_gate_clips() -> Vec<(String, String, String)> {
20469 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
20470 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
20471 let (film, film4k, screen) = (
20472 on("EC_AV1_NATIVE_FILM"),
20473 on("EC_AV1_NATIVE_FILM4K"),
20474 on("EC_AV1_NATIVE_SCREEN"),
20475 );
20476 // No selector at all means every clip; any selector means that subset.
20477 let all = !(film || film4k || screen);
20478 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
20479 // not film -- they print as "bars" so no reader takes them for real
20480 // content -- and the two rows below them are the real AV1 films.
20481 let mut clips: Vec<(String, String, String)> = Vec::new();
20482 for (want, label, file) in [
20483 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
20484 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
20485 ] {
20486 if !want {
20487 continue;
20488 }
20489 let path = fixtures.join("video").join(file);
20490 match path.exists() {
20491 true => {
20492 clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into()))
20493 }
20494 false => eprintln!("SKIP {label}: {file} missing"),
20495 }
20496 }
20497 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
20498 // The real films, taken out of the real-library manifest by codec and
20499 // coded width so no title and no home path lives in this file. Each
20500 // seek is PINNED (class `seeded fixture not reproducible`) at a
20501 // moving, non-black window -- a black leader would make every arm
20502 // read +0.000 (class `flat sample window`). Both sources are 10-bit
20503 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
20504 // what all three encoders see, so the comparison stays
20505 // encoder-vs-encoder.
20506 let pick = |width: &str| -> Option<String> {
20507 let m = manifest.as_ref().ok()?;
20508 m.lines()
20509 .skip(1)
20510 .map(|l| l.split('\t').collect::<Vec<_>>())
20511 .find(|f| {
20512 f.len() > 4
20513 && f[2] == "av1"
20514 && f[3] == width
20515 && std::path::Path::new(f[0]).exists()
20516 })
20517 .map(|f| f[0].to_string())
20518 };
20519 for (want, label, width, seek) in [
20520 (all || film, "film A (1080p source)", "1920", "00:35:00"),
20521 (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"),
20522 ] {
20523 if !want {
20524 continue;
20525 }
20526 match pick(width) {
20527 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
20528 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
20529 }
20530 }
20531 if all || screen {
20532 match &manifest {
20533 Ok(manifest) => match manifest
20534 .lines()
20535 .skip(1)
20536 .filter_map(|l| l.split('\t').next())
20537 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
20538 {
20539 Some(p) => clips.push((
20540 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
20541 p.to_string(),
20542 "0".into(),
20543 )),
20544 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
20545 },
20546 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
20547 }
20548 }
20549 clips
20550 }
20551
20552 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
20553 /// downscales the OBS capture to 640x384, which destroys exactly the
20554 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
20555 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
20556 /// on that recipe is taken on content the tool cannot serve. This arm
20557 /// crops -- never scales -- a superblock-aligned window out of the middle
20558 /// of the capture at its own resolution (at most 1920x1024, so the wall
20559 /// stays in the minutes) and runs the same 12-frame, four-quantizer
20560 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
20561 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
20562 /// sample-exactness assertion `our_ladder` makes.
20563 ///
20564 /// It is its own `--ignored` test so the default gate's wall does not
20565 /// grow. Every variant is an environment knob, and each of those is a
20566 /// `OnceLock` read once per process, so a variant is a separate run:
20567 ///
20568 /// cargo test -p ec-av1 --release --lib -- --ignored \
20569 /// bd_rate_screen_native --nocapture # baseline
20570 /// EC_AV1_INTRABC=1 ... same command # intra block copy
20571 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
20572 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
20573 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
20574 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
20575 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
20576 ///
20577 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
20578 /// through (lane-av1pyrdef); the run prints the requested and the
20579 /// effective pyramid per clip, and a screen clip's effective one is
20580 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
20581 /// streaming facade instead, which prints the per-level frame and byte
20582 /// census and asserts ffmpeg's decode against our own decoder on all
20583 /// three planes in display order; both arms code the same bytes
20584 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
20585 ///
20586 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
20587 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
20588 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
20589 /// cost -- so every "film" column in the historical tables of this file
20590 /// is that generator, not film. The real content is `film A`, `film B`
20591 /// (native crops out of the two AV1 films the real-library manifest
20592 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
20593 /// decision only the bars rows support is not supported.
20594 ///
20595 /// Measured 2026-09-07, the five rows before and after the screen
20596 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
20597 /// BOTH real films were classified as screen content on 48/48 frames, so
20598 /// their coefficients were priced against the DEFAULT CDFs and the
20599 /// palette search ran over film; after, both are non-screen (0/48) and
20600 /// the capture is unchanged at 48/48:
20601 ///
20602 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
20603 /// |---|---|---|---|
20604 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
20605 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
20606 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
20607 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
20608 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
20609 ///
20610 /// Both bars rows and the capture are byte-identical across that change
20611 /// (their classification never moved); the palette search over film was
20612 /// costing roughly a tenth of the film rows' wall.
20613 ///
20614 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
20615 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
20616 /// the capture is gated flat and does not move a byte:
20617 ///
20618 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
20619 /// |---|---|---|---|---|
20620 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
20621 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
20622 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
20623 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
20624 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
20625 ///
20626 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
20627 /// which is the point of the shared driver: the two entry points code one
20628 /// stream. The bars rows are fixtures (recorded, never a decision); the
20629 /// two real films are what the pyramid ships for.
20630 ///
20631 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
20632 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
20633 /// setting any one of them keeps only the selected rows (the two 1080p
20634 /// rows, the two 2160p rows, the capture row respectively). A missing
20635 /// real film SKIPs its row; it never fails the gate.
20636 #[test]
20637 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
20638 fn bd_rate_screen_native() {
20639 let _knobs = crate::speed::knob_read();
20640 native_bd_arm("bd_rate_screen_native", 12, false);
20641 }
20642
20643 /// The LONG-GOP arm of the native BD gate: the same recipe as
20644 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
20645 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
20646 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
20647 /// reaches libaom as `--kf-max-dist=48` and rav1e as
20648 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
20649 /// inter pictures.
20650 ///
20651 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
20652 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
20653 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
20654 /// above 12 codes the same stream there -- the shipped `16` was measured
20655 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
20656 /// group (class `instrument at bound` / `gate blind to feature`). The
20657 /// user's exports are long GOPs, so the pyramid shape is decided here.
20658 ///
20659 /// cargo test -p ec-av1 --release --lib -- --ignored \
20660 /// bd_rate_film_long_gop --nocapture
20661 ///
20662 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
20663 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
20664 /// Read every row off the log's own "pyramid requested/effective" print,
20665 /// never off the argument order of the runs (lane-pyr3 misattributed
20666 /// three rows that way).
20667 ///
20668 /// Table: `lanes/pyr4.sweep.txt`.
20669 #[test]
20670 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
20671 fn bd_rate_film_long_gop() {
20672 let _knobs = crate::speed::knob_write();
20673 native_bd_arm("bd_rate_film_long_gop", 48, true);
20674 }
20675
20676 /// The shared driver of the two native BD arms above: `frames` pictures
20677 /// per row (the sequence's `gop` is the same number, so one key frame),
20678 /// four quantizers, `films_only` dropping every row but the two real
20679 /// films.
20680 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
20681 if !have_ffmpeg() {
20682 eprintln!("SKIP {label}: no ffmpeg");
20683 return;
20684 }
20685 let mut clips = native_gate_clips();
20686 if films_only {
20687 clips.retain(|(name, _, _)| name.starts_with("film "));
20688 }
20689 if clips.is_empty() {
20690 eprintln!("SKIP {label}: no clip");
20691 return;
20692 }
20693
20694 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
20695 .iter()
20696 .map(|q| {
20697 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
20698 .map(String::from)
20699 .to_vec()
20700 })
20701 .collect();
20702 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
20703 .iter()
20704 .map(|q| {
20705 vec![
20706 "-rav1e-params".to_string(),
20707 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
20708 ]
20709 })
20710 .collect();
20711 println!(
20712 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
20713 intrabc {}, palette maxcolors {}",
20714 armed_tiles(),
20715 crate::par::tile_threads(),
20716 intrabc_enabled(),
20717 palette_max_colors(),
20718 );
20719 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |");
20720 println!("|---|---|---|---|---|");
20721 for (name, path, seek) in &clips {
20722 let fctx = &crate::decode::FrameCtx::for_encoder();
20723 if probe_dims(path).is_none() {
20724 eprintln!("SKIP {name}: ffprobe gave no size");
20725 continue;
20726 }
20727 // A whole number of 128-wide superblocks, at most 1920x1024, out
20728 // of the middle of the frame; the offsets stay even for 4:2:0.
20729 // ONE definition, shared with `examples/enc_probe` so the probe
20730 // cannot measure a different window than this gate (lane-probe).
20731 let (vf, cw, ch) = match native_crop_override(path) {
20732 Some(over) => over,
20733 None => crate::probe::gate_crop(path),
20734 };
20735 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
20736 SCREEN_FRAMES.iter().for_each(|c| {
20737 c.store(0, std::sync::atomic::Ordering::Relaxed);
20738 });
20739 let _ = crate::tile::take_palette_hits();
20740 let _ = crate::tile::take_palette_uv_hits();
20741 let _ = crate::tile::take_intrabc_hits();
20742 let _ = take_intrabc_search();
20743 let _ = crate::tile::take_filter_intra_hits();
20744 let _ = take_edge_census();
20745 // The sequence path itself codes the pyramid now
20746 // (lane-av1pyrdef), and prints what it requested and what the
20747 // content gate left effective.
20748 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
20749 // lane-sse: the blocks the true frame edge cuts through, and how
20750 // much of their RAW squared error sat in the padding the encoder
20751 // invented past it -- what the inside-only score stopped ranking
20752 // on. Empty on a superblock-aligned crop, which is every default
20753 // gate row (class `gate-blind-to-feature`).
20754 if edge_census() {
20755 for (side, n, inside, padding) in take_edge_census() {
20756 eprintln!(
20757 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
20758 padding_sse={padding} ({:.1}% of raw)",
20759 100.0 * padding as f64 / (inside + padding).max(1) as f64,
20760 );
20761 }
20762 }
20763 // gate-blind-to-feature: what the screen tools actually did at
20764 // native resolution, over this clip's four encodes.
20765 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20766 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
20767 // Which tables the SEARCH priced against, per frame arming
20768 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
20769 // real starting ones. A film clip must show every inter arming on
20770 // the real side, a screen clip none of them.
20771 let (price_default, price_real) = crate::tile::take_pricing_hits();
20772 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
20773 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
20774 // superblocks stayed whole, and how many of those coded a
20775 // residual, split that residual's luma, or took a compound
20776 // reference (class `gate-blind-to-feature`).
20777 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
20778 // the superblocks offered the trial were coded whole.
20779 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
20780 eprintln!(
20781 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
20782 {i64_edge} on a superblock the frame edge cuts",
20783 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
20784 );
20785 eprintln!(
20786 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
20787 {} (search) / {} (writer); rect/AB pieces with a residual \
20788 {} (search) / {} (writer)",
20789 take_b128_none_hits(),
20790 crate::tile::take_sb128_none_hits(),
20791 take_b128_residual_hits(),
20792 crate::tile::take_sb128_residual_hits(),
20793 take_b128_rectres_hits(),
20794 crate::tile::take_sb128_rectres_hits(),
20795 );
20796 eprintln!(
20797 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
20798 take_b64_root_hits(),
20799 take_b64_residual_hits(),
20800 take_b64_var_tx_hits(),
20801 take_b64_compound_hits(),
20802 );
20803 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
20804 // of every priced block): what the deadzone quantiser handed the
20805 // RDOQ pass and what the pass changed, over every TRIAL block of
20806 // this row's four encodes -- not over the coded stream, so it is
20807 // the bits AT STAKE in the search, not in the bitstream.
20808 let rq = crate::tile::take_rdoq_stats();
20809 if rq[0] > 0 {
20810 eprintln!(
20811 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
20812 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
20813 rq[0],
20814 rq[1],
20815 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
20816 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
20817 rq[4],
20818 rq[5],
20819 rq[7] as f64 / 64.0,
20820 rq[6] as f64 / 64.0,
20821 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
20822 );
20823 }
20824 // lane-av1obmc2: the same motion_mode census the 640x384 gate
20825 // prints (class `gate-blind-to-feature`) -- how many blocks coded
20826 // the symbol at each footprint and how many took OBMC. Without it
20827 // the native table, which is the standing keep table, could not
20828 // say whether the tool fired at all.
20829 let mm = crate::tile::take_motion_mode_hits();
20830 eprintln!(
20831 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
20832 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
20833 eligible)",
20834 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
20835 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20836 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20837 mm.iter().sum::<usize>(),
20838 );
20839 print_inter_tx_census(name);
20840 // lane-last2 (class `gate-blind-to-feature`): which reference the
20841 // 32x32-and-below inter blocks of this clip's four encodes chose.
20842 // The native table is the standing keep table, so a second past
20843 // reference that never won a block has to be visible HERE and not
20844 // only in a synthetic witness.
20845 let rh = crate::encode::take_ref_frame_hits();
20846 let rtot: usize = rh.iter().sum();
20847 eprintln!(
20848 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
20849 (LAST2 {:.1}%)",
20850 rh[1], rh[2], rh[4], rh[7], rtot,
20851 100.0 * rh[2] as f64 / rtot.max(1) as f64,
20852 );
20853 let palette = crate::tile::take_palette_hits();
20854 let palette_uv = crate::tile::take_palette_uv_hits();
20855 let ibc = crate::tile::take_intrabc_hits();
20856 let search = take_intrabc_search();
20857 eprintln!(
20858 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
20859 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
20860 won {})",
20861 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
20862 palette[0],
20863 palette_uv[0],
20864 ibc[0],
20865 search[0],
20866 search[1],
20867 search[2],
20868 );
20869 // gate-blind-to-feature: how often the five recursive filter-intra
20870 // modes actually won a block over this clip's four encodes -- a
20871 // tool that never fires is not measured by the row above it.
20872 let fi = crate::tile::take_filter_intra_hits();
20873 eprintln!(
20874 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
20875 filter_intra_on(),
20876 fi[0],
20877 fi[1],
20878 fi[2],
20879 fi[3],
20880 fi[4],
20881 fi[5],
20882 );
20883 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
20884 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
20885 assert_monotone(&format!("{name}: ours"), &ours);
20886 assert_monotone(&format!("{name}: libaom"), &aom);
20887 assert_monotone(&format!("{name}: rav1e"), &rav1e);
20888 let points = ours
20889 .iter()
20890 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20891 .collect::<Vec<_>>()
20892 .join(", ");
20893 println!(
20894 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
20895 bd_rate(&aom, &ours) * 100.0,
20896 bd_rate(&rav1e, &ours) * 100.0,
20897 );
20898 // lane-pareto2: the two references at THEIR fast presets, plus
20899 // SVT-AV1, measured in the SAME arm as the row above -- the only
20900 // way the wall column of a Pareto table means anything (class:
20901 // wall tables are comparable only inside one interleaved batch).
20902 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
20903 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
20904 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
20905 [50, 100, 150, 200]
20906 .iter()
20907 .map(|q| {
20908 vec![
20909 "-rav1e-params".to_string(),
20910 format!(
20911 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
20912 ),
20913 ]
20914 })
20915 .collect()
20916 };
20917 let aom_at = |cu: u32| -> Vec<Vec<String>> {
20918 [5, 20, 35, 45]
20919 .iter()
20920 .map(|q| {
20921 vec![
20922 "-cpu-used".to_string(),
20923 cu.to_string(),
20924 "-b:v".to_string(),
20925 "0".to_string(),
20926 "-crf".to_string(),
20927 q.to_string(),
20928 ]
20929 })
20930 .collect()
20931 };
20932 let svt_at = |pr: u32| -> Vec<Vec<String>> {
20933 [20, 35, 45, 55]
20934 .iter()
20935 .map(|q| {
20936 vec![
20937 "-preset".to_string(),
20938 pr.to_string(),
20939 "-crf".to_string(),
20940 q.to_string(),
20941 "-svtav1-params".to_string(),
20942 "lp=1".to_string(),
20943 ]
20944 })
20945 .collect()
20946 };
20947 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
20948 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
20949 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
20950 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
20951 ];
20952 if have_encoder("libsvtav1") {
20953 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
20954 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
20955 } else {
20956 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
20957 }
20958 for (label, encoder, points) in arms {
20959 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
20960 // A REFERENCE stream our decoder cannot read is a note in
20961 // this table, not a gate failure: these rows exist to
20962 // price the references, and `assert_ladder_decodes` keeps
20963 // its teeth for the two ladders the keep table is read off.
20964 let notes =
20965 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
20966 if !notes.is_empty() {
20967 eprintln!("{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)", notes.len());
20968 }
20969 assert_monotone(&format!("{name}: {label}"), &lad);
20970 println!(
20971 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
20972 bd_rate(&aom, &lad) * 100.0,
20973 bd_rate(&rav1e, &lad) * 100.0,
20974 );
20975 }
20976 }
20977 }
20978 assert_ladder_decodes();
20979 }
20980
20981 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
20982 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
20983 /// on the two film clips at their native gate crop. The 2160p clip loses
20984 /// at every arm of the propagating map and the named suspect was that its
20985 /// heavily filtered flat cells give a tiny denominator, so the dependence
20986 /// ratio explodes exactly where coding is cheap; this prints the numbers
20987 /// that confirm or refute it.
20988 #[test]
20989 #[ignore = "needs ffmpeg and the film fixtures"]
20990 fn tpl_intra_denominator_histogram() {
20991 let _knobs = crate::speed::knob_read();
20992 if !have_ffmpeg() {
20993 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
20994 return;
20995 }
20996 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
20997 for (label, file) in [
20998 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
20999 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
21000 ] {
21001 let path = fixtures.join("video").join(file);
21002 if !path.exists() {
21003 eprintln!("SKIP {label}: {file} missing");
21004 continue;
21005 }
21006 let path = path.to_str().unwrap();
21007 let Some((nw, nh)) = probe_dims(path) else {
21008 eprintln!("SKIP {label}: ffprobe gave no size");
21009 continue;
21010 };
21011 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
21012 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21013 let source =
21014 clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
21015 let mut costs: Vec<f64> = Vec::new();
21016 for pic in &source {
21017 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
21018 costs.extend(
21019 super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)),
21020 );
21021 }
21022 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
21023 let mut sorted = costs.clone();
21024 sorted.sort_by(f64::total_cmp);
21025 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
21026 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
21027 eprintln!(
21028 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
21029 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
21030 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
21031 below 1.0x {} ({:.1}%)",
21032 costs.len(),
21033 q(0.0),
21034 q(0.01),
21035 q(0.05),
21036 q(0.25),
21037 q(0.50),
21038 q(0.75),
21039 q(0.99),
21040 q(1.0),
21041 below(0.25),
21042 100.0 * below(0.25) as f64 / costs.len() as f64,
21043 below(0.5),
21044 100.0 * below(0.5) as f64 / costs.len() as f64,
21045 below(1.0),
21046 100.0 * below(1.0) as f64 / costs.len() as f64,
21047 );
21048 }
21049 }
21050
21051 /// The probe arms the gate's source (lane-probe, class `instrument
21052 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
21053 /// command line and had no `-ss`, so it read film B from frame 0 -- a
21054 /// black leader -- and coded 59 kB where the gate's own ladder point
21055 /// coded 89 kB of the same title; every census taken through it was
21056 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
21057 /// the shared loader honours the seek (arming the probe's way and the
21058 /// gate's way gives byte-identical streams, and dropping the seek does
21059 /// not), on a synthetic clip whose content moves over time.
21060 #[test]
21061 fn the_probe_arms_the_gates_source() {
21062 let _knobs = crate::speed::knob_write();
21063 if !have_ffmpeg() {
21064 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
21065 return;
21066 }
21067 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
21068 std::fs::create_dir_all(&dir).unwrap();
21069 let clip = dir.join("testsrc2.y4m");
21070 // 384x202: neither side is a multiple of 128, so the gate's centre
21071 // window is a real derivation and not the frame itself -- exactly the
21072 // shape film B has (3840x1608, never 3840x2160).
21073 let ok = Command::new("ffmpeg")
21074 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"])
21075 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
21076 .arg(&clip)
21077 .status()
21078 .expect("ffmpeg failed to run")
21079 .success();
21080 assert!(ok, "ffmpeg could not write the synthetic clip");
21081 let path = clip.to_str().unwrap();
21082
21083 // The window: superblock-aligned, centred, even offsets.
21084 let (vf, w, h) = crate::probe::gate_crop(path);
21085 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
21086
21087 let (seek, q) = ("00:00:01", 150u8);
21088 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
21089 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
21090 assert!(
21091 gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
21092 "the probe's source differs from the gate's at the same window"
21093 );
21094 let bytes = |src: &[Picture]| {
21095 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
21096 .unwrap()
21097 .stream
21098 };
21099 assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes");
21100 // The two witnesses that both halves of the arming reach ffmpeg: the
21101 // seek, and the crop's own offset (the film-B defect in miniature --
21102 // the probe was reading `crop=..:568` of a 1608-high frame).
21103 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
21104 assert_ne!(
21105 bytes(&gate),
21106 bytes(&unseeked),
21107 "seeked and unseeked arming coded the same bytes -- the seek is inert"
21108 );
21109 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
21110 assert_ne!(
21111 bytes(&gate),
21112 bytes(&offset),
21113 "centred and top-aligned windows coded the same bytes -- the crop is inert"
21114 );
21115 std::fs::remove_dir_all(&dir).ok();
21116 }
21117
21118 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
21119 /// point inside the test binary, to compare against `examples/enc_probe`.
21120 #[test]
21121 #[ignore = "diagnostic: needs ffmpeg and a clip"]
21122 fn probe_parity_point() {
21123 let _knobs = crate::speed::knob_write();
21124 let g = |k: &str| std::env::var(k).unwrap();
21125 let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap();
21126 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
21127 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
21128 let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames);
21129 let fctx = &crate::decode::FrameCtx::for_encoder();
21130 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
21131 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
21132 for &b in &e.stream {
21133 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
21134 }
21135 eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
21136 e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid());
21137 }
21138 /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The
21139 /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`):
21140 /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in
21141 /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32
21142 /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags
21143 /// the census's far row measures were already banked by `arf_altref`.
21144 /// This census stays the PRICING arm (class `gate-blind-to-feature`): its
21145 /// best-of-two SAD shares are read against the fire share the gate census
21146 /// prints (`references ... LAST2 n (n%)`) and the refutation in
21147 /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the
21148 /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off
21149 /// `LAST`, the backward `ALTREF`, and the rate term price in.
21150 ///
21151 /// The measurement is on the gate's own window and loader (`gate_crop`,
21152 /// 12 pictures) of the two real films: every 16x16 luma block of every
21153 /// picture gets one full-pel diamond search against the NEAR reference
21154 /// and the same search against the FAR one, at the two lags the pyramid
21155 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
21156 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
21157 /// reference wins at all and by more than 10%, and -- the number the
21158 /// decision is taken on -- the total SAD of best-of-{near, far} against
21159 /// the total SAD of near alone, which is the prediction energy a second
21160 /// reference could remove before any rate is paid for naming it.
21161 ///
21162 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
21163 #[test]
21164 #[ignore = "reads the real films"]
21165 fn last2_census() {
21166 if !have_ffmpeg() {
21167 eprintln!("SKIP last2_census: no ffmpeg");
21168 return;
21169 }
21170 const SIDE: usize = 16;
21171 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
21172 // `None` when the displaced block leaves the picture.
21173 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
21174 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
21175 if sy < 0 || sx < 0 {
21176 return None;
21177 }
21178 let (sy, sx) = (sy as usize, sx as usize);
21179 if sy + SIDE > r.height || sx + SIDE > r.width {
21180 return None;
21181 }
21182 let mut acc = 0u64;
21183 for row in 0..SIDE {
21184 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
21185 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
21186 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
21187 }
21188 Some(acc)
21189 };
21190 // A log-step diamond from the zero motion vector: the cheapest search
21191 // that still finds real pans. Both references get exactly this one,
21192 // so the comparison is search-fair.
21193 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
21194 let mut best = (sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX), (0isize, 0isize));
21195 let mut step = 16isize;
21196 while step >= 1 {
21197 let centre = best.1;
21198 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
21199 let mv = (centre.0 + dy * step, centre.1 + dx * step);
21200 if let Some(s) = sad(cur, r, bx, by, mv) {
21201 if s < best.0 {
21202 best = (s, mv);
21203 }
21204 }
21205 }
21206 step /= 2;
21207 }
21208 best.0
21209 };
21210 println!("| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |");
21211 println!("|---|---|---|---|---|---|---|---|");
21212 for (name, path, seek) in native_gate_clips() {
21213 if !name.starts_with("film ") {
21214 continue;
21215 }
21216 let (vf, cw, ch) = crate::probe::gate_crop(&path);
21217 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
21218 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
21219 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
21220 let (mut near_sad, mut best_sad) = (0u64, 0u64);
21221 for i in far..pictures.len() {
21222 let cur = &pictures[i];
21223 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
21224 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
21225 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
21226 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
21227 blocks += 1;
21228 wins += u64::from(f < n);
21229 big += u64::from(f as f64 * 1.1 < n as f64);
21230 near_sad += n;
21231 best_sad += n.min(f);
21232 }
21233 }
21234 }
21235 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
21236 println!(
21237 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
21238 pct(wins),
21239 pct(big),
21240 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
21241 );
21242 }
21243 }
21244 }
21245
21246 /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
21247 /// temporal filter of its SOURCE would take off it, priced before any
21248 /// encoder change (class `gate-blind-to-feature`).
21249 ///
21250 /// The stream census says our top ARF costs 6992 B a frame against
21251 /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
21252 /// quality, and that 61% of the gap is residual, not syntax. Two
21253 /// explanations are separable here without an encoder: our anchor
21254 /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
21255 /// the residual it codes at that lag is dominated by film grain, which no
21256 /// motion search can predict (source noise). So, per ARF position of the
21257 /// gate's own 48-picture window:
21258 ///
21259 /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
21260 /// * the same at lag 8 with the CURRENT picture temporally filtered --
21261 /// a libaom-shaped motion-compensated average of the +-2 display
21262 /// neighbours, weights `exp(-mse / strength)` -- which is the residual
21263 /// energy an ARF temporal filter would remove, and
21264 /// * PSNR of that filtered picture against the unfiltered one, the
21265 /// CEILING the filtered ARF's own PSNR is then measured under (the
21266 /// BD gate scores against the unfiltered source).
21267 ///
21268 /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
21269 /// --ignored arf_pred_census --nocapture
21270 #[test]
21271 #[ignore = "reads the real films"]
21272 fn arf_pred_census() {
21273 if !have_ffmpeg() {
21274 eprintln!("SKIP arf_pred_census: no ffmpeg");
21275 return;
21276 }
21277 const SIDE: usize = 16;
21278 let strength: f64 = std::env::var("EC_ARF_TF_S")
21279 .ok()
21280 .and_then(|v| v.parse().ok())
21281 .unwrap_or(30.0);
21282 let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
21283 // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
21284 // when the displaced block leaves the picture.
21285 let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
21286 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
21287 if sy < 0 || sx < 0 {
21288 return None;
21289 }
21290 let (sy, sx) = (sy as usize, sx as usize);
21291 if sy + SIDE > r.height || sx + SIDE > r.width {
21292 return None;
21293 }
21294 let mut acc = 0u64;
21295 for row in 0..SIDE {
21296 let c = &cur[row * cw..][..SIDE];
21297 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
21298 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
21299 }
21300 Some((acc, (sy, sx)))
21301 };
21302 // The same log-step diamond `last2_census` uses, so the two censuses'
21303 // SADs are comparable.
21304 let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
21305 let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
21306 Some(v) => v,
21307 None => return (u64::MAX, (by, bx)),
21308 };
21309 let mut centre = (0isize, 0isize);
21310 let mut step = 16isize;
21311 while step >= 1 {
21312 let from = centre;
21313 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
21314 let mv = (from.0 + dy * step, from.1 + dx * step);
21315 if let Some(s) = at(cur, cw, r, bx, by, mv) {
21316 if s.0 < best.0 {
21317 best = s;
21318 centre = mv;
21319 }
21320 }
21321 }
21322 step /= 2;
21323 }
21324 best
21325 };
21326 println!(
21327 "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
21328 );
21329 println!("|---|---|---|---|---|---|---|");
21330 for (name, path, seek) in native_gate_clips() {
21331 if !name.starts_with("film ") {
21332 continue;
21333 }
21334 let (vf, cw, ch) = crate::probe::gate_crop(&path);
21335 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
21336 let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
21337 let (mut tf_sse, mut tf_px) = (0f64, 0u64);
21338 for i in (8..pictures.len()).step_by(8) {
21339 arfs += 1;
21340 let cur = &pictures[i];
21341 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
21342 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
21343 let block: Vec<u16> = (0..SIDE)
21344 .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
21345 .collect();
21346 n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
21347 n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
21348 // The temporal filter: each +-2 display neighbour is
21349 // motion-compensated onto this block and averaged in
21350 // with libaom's shape, a weight that falls with the
21351 // match's own mean squared error.
21352 let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
21353 let mut wsum = 1.0f64;
21354 // `EC_ARF_TF_PAST=1` restricts the filter to the
21355 // DISPLAY-PAST neighbours -- the only ones the
21356 // encoder's own group buffer holds when it codes its
21357 // top ARF (the group's future is not buffered yet).
21358 let offs: &[isize] = match past {
21359 true => &[-2, -1],
21360 false => &[-2, -1, 1, 2],
21361 };
21362 for &d in offs {
21363 let j = i as isize + d;
21364 let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
21365 else {
21366 continue;
21367 };
21368 let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
21369 let mut sse = 0f64;
21370 for row in 0..SIDE {
21371 for col in 0..SIDE {
21372 let d = f64::from(block[row * SIDE + col])
21373 - f64::from(nb.y[(sy + row) * nb.width + sx + col]);
21374 sse += d * d;
21375 }
21376 }
21377 let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp();
21378 for row in 0..SIDE {
21379 for col in 0..SIDE {
21380 acc[row * SIDE + col] +=
21381 w * f64::from(nb.y[(sy + row) * nb.width + sx + col]);
21382 }
21383 }
21384 wsum += w;
21385 }
21386 let filtered: Vec<u16> = acc
21387 .iter()
21388 .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16)
21389 .collect();
21390 for (a, b) in filtered.iter().zip(&block) {
21391 let d = f64::from(*a) - f64::from(*b);
21392 tf_sse += d * d;
21393 }
21394 tf_px += (SIDE * SIDE) as u64;
21395 ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0;
21396 px += (SIDE * SIDE) as u64;
21397 }
21398 }
21399 }
21400 let per = |v: u64| v as f64 / px.max(1) as f64;
21401 let mse = tf_sse / tf_px.max(1) as f64;
21402 println!(
21403 "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |",
21404 per(n8),
21405 per(n4),
21406 per(ntf),
21407 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64,
21408 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(),
21409 );
21410 }
21411 }
21412
21413 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
21414 /// hardwire the REGULAR kernel, so the encoder could not have coded a
21415 /// SMOOTH or SHARP frame even if the header had said so -- the search,
21416 /// the trials, the recon and the frame header now all read
21417 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
21418 /// distinct stream (a filter that never reached the prediction would code
21419 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
21420 /// reconstructs every frame of each of them exactly, which is what proves
21421 /// the header and the prediction agree.
21422 #[test]
21423 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
21424 let _knobs = crate::speed::knob_write();
21425 if !have_ffmpeg() {
21426 eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg");
21427 return;
21428 }
21429 let (width, height) = (256usize, 128usize);
21430 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
21431 // all three kernels would code the same bytes and the test would pass
21432 // on a wiring that does nothing (class `fixture proves the symbol, not
21433 // the signal`). `panned_test_card` shifts by whole pixels, so the
21434 // search finds the sub-pel positions off the reconstruction instead:
21435 // three frames of a slow diagonal pan.
21436 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
21437 let mut streams = Vec::new();
21438 for filter in [
21439 ec_av1_syntax::InterpolationFilter::Eighttap,
21440 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
21441 ec_av1_syntax::InterpolationFilter::EighttapSharp,
21442 ] {
21443 set_frame_interp(Some(filter));
21444 let fctx = &crate::decode::FrameCtx::for_encoder();
21445 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
21446 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
21447 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
21448 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
21449 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
21450 assert_eq!(decoded.y, frame.reconstruction.y, "{filter:?} frame {i}: luma");
21451 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
21452 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
21453 }
21454 streams.push((filter, encoded.stream));
21455 }
21456 set_frame_interp(None);
21457 for (i, (fa, a)) in streams.iter().enumerate() {
21458 for (fb, b) in &streams[i + 1..] {
21459 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
21460 }
21461 }
21462 }
21463
21464
21465 /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
21466 /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
21467 /// residual outright (`round_to_valid_mv` rounds it away first), so the
21468 /// finest vector the encoder could commit to was a quarter pel. With the
21469 /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
21470 /// non-zero component and the search's fourth stage refines to the
21471 /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
21472 /// on arm, and -- the part that makes it a signal rather than a symbol
21473 /// count (class `fixture proves the symbol, not the signal`) -- that some
21474 /// of them come out ZERO, i.e. name a vector the off arm cannot code at
21475 /// all. Both streams are decoded by ffmpeg AND by this crate's own
21476 /// decoder and asserted sample-exact against the encoder's own
21477 /// reconstruction, which is what proves the header bit and the symbols
21478 /// agree.
21479 #[test]
21480 fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
21481 let _knobs = crate::speed::knob_write();
21482 if !have_ffmpeg() {
21483 eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg");
21484 return;
21485 }
21486 let (width, height) = (256usize, 128usize);
21487 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
21488 let mut arms = Vec::new();
21489 for hp in [false, true] {
21490 set_high_precision_mv(Some(hp));
21491 let _ = crate::tile::take_hp_symbols();
21492 let fctx = &crate::decode::FrameCtx::for_encoder();
21493 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
21494 .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
21495 let (symbols, eighth) = crate::tile::take_hp_symbols();
21496 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
21497 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
21498 assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
21499 assert_eq!(ours.len(), pictures.len(), "hp={hp}: our decoder frame count");
21500 for (i, e) in encoded.frames.iter().enumerate() {
21501 for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
21502 if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction)
21503 {
21504 panic!(
21505 "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
21506 the encoder reconstructed {want}"
21507 );
21508 }
21509 }
21510 }
21511 arms.push((symbols, eighth, encoded.stream));
21512 }
21513 set_high_precision_mv(None);
21514 let (off, on) = (&arms[0], &arms[1]);
21515 assert_eq!(off.0, 0, "a frame without the header bit codes no hp symbol");
21516 assert!(on.0 > 0, "a high-precision frame codes hp symbols (got {})", on.0);
21517 assert!(
21518 on.1 > 0,
21519 "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
21520 on.0
21521 );
21522 assert_ne!(off.2, on.2, "the two arms coded the same bytes");
21523 println!(
21524 "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
21525 off.0,
21526 off.2.len(),
21527 on.0,
21528 on.1,
21529 on.2.len()
21530 );
21531 }
21532}