forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB70849e0Tahinli2 months ago3122 commits

encode.rs21527 lines, 979.6 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,
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 );
3036 #[cfg(test)]
3037 stage_since(2, t);
3038 let reconstruction: Vec<u8> = if coded.is_empty() {
3039 prediction.to_vec()
3040 } else {
3041 prediction
3042 .iter()
3043 .zip(&coded)
3044 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
3045 .collect()
3046 };
3047 let sse = self.block_sse(x, y, side, &reconstruction);
3048 // A 64-point transform codes only its top-left 32x32 corner (spec
3049 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
3050 // key frame writer takes a 32x32 level grid for one). The inverse
3051 // above reads the whole 64x64 array, but the price below and the
3052 // levels the writer takes are that corner.
3053 let levels = if side > BLOCK {
3054 coded_corner(&levels, side, BLOCK)
3055 } else {
3056 levels
3057 };
3058 #[cfg(test)]
3059 let t = stage_start();
3060 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
3061 levels
3062 .iter()
3063 .filter(|&&level| level != 0)
3064 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
3065 .sum()
3066 } else if let Some(bits) = rdoq_bits {
3067 bits
3068 } else {
3069 {
3070 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3071 crate::tile::coeff_bits_typed(
3072 &levels,
3073 set,
3074 crate::decode::q_ctx_of(base_q_idx),
3075 skip_ctx,
3076 sign_ctx,
3077 tx_type,
3078 )
3079 }
3080 };
3081 #[cfg(test)]
3082 stage_since(3, t);
3083 Trial {
3084 levels,
3085 reconstruction,
3086 sse,
3087 bits,
3088 }
3089 }
3090
3091 /// Codes this block's luma at transform depth `depth`: the
3092 /// `(side >> depth)^2` transform units in raster order, each predicted
3093 /// from the reconstruction the units before it left behind -- exactly
3094 /// what the decoder's multi-transform-unit branch does (decode.rs
3095 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
3096 /// reconstructed on its own. Commits the result and hands back the
3097 /// block-coordinate levels, the block's squared error and what its
3098 /// coefficients cost.
3099 #[allow(clippy::too_many_arguments)]
3100 fn code_tx_depth(
3101 &mut self,
3102 at: At,
3103 mode: u8,
3104 angle_delta: i32,
3105 depth: usize,
3106 // This block's `filter_intra_mode` when it is coded with one, in
3107 // which case every transform unit predicts recursively off the
3108 // reconstruction the units before it left -- what the decoder does
3109 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
3110 // `filter_intra`), not once over the whole block.
3111 filter_intra: Option<u8>,
3112 search: &Search, fctx: &crate::decode::FrameCtx,
3113 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
3114 let At { x, y, side, reach, .. } = at;
3115 let tx = side >> depth;
3116 let n = 1usize << depth;
3117 let set = luma_set_for(
3118 match tx {
3119 32 => TxbSet::Luma32,
3120 16 => TxbSet::Luma16,
3121 8 => TxbSet::Luma8,
3122 _ => TxbSet::Luma4,
3123 },
3124 search.screen,
3125 );
3126 let mut levels = vec![0i32; side * side];
3127 census_add(4, n * n);
3128 // A unit smaller than its block reads the neighbour magnitude table
3129 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
3130 self.ctx.tu_split = n > 1;
3131 let (mut sse, mut bits) = (0.0, 0.0);
3132 // One entry per unit at its own `tu_row * n + tu_col`, which is how
3133 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
3134 // frame edge cuts away is never coded there, so a compacted list
3135 // would slide every later unit's type onto the wrong transform.
3136 let mut tx_types = vec![TxType::DctDct; n * n];
3137 for tu_row in 0..n {
3138 for tu_col in 0..n {
3139 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3140 let tu = At {
3141 x: x + col_off,
3142 y: y + row_off,
3143 side: tx,
3144 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
3145 set,
3146 };
3147 let trial = match filter_intra {
3148 Some(fi) => {
3149 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3150 let (above, left, corner) =
3151 self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf);
3152 let mut prediction = vec![0u8; tx * tx];
3153 filter_intra_predict_u8(
3154 usize::from(fi),
3155 above,
3156 left,
3157 corner,
3158 tx,
3159 &mut prediction,
3160 fctx,
3161 );
3162 self.code_from_prediction(
3163 tu.x,
3164 tu.y,
3165 tx,
3166 &prediction,
3167 false,
3168 search.base_q_idx,
3169 search.deadzone,
3170 set,
3171 )
3172 }
3173 None => {
3174 // lane-txset: the unit picks its own transform type
3175 // out of the set the writer can name it in, priced
3176 // through the same RDOQ'd trial path (its `bits`
3177 // already carry the `tx_type` symbol itself).
3178 let mut best: Option<(f64, TxType, Trial)> = None;
3179 for &tx_type in tx_type_candidates(set, search.screen) {
3180 let candidate = self.trial_typed(
3181 tu, mode, angle_delta, search.base_q_idx, search.deadzone,
3182 tx_type, fctx,
3183 );
3184 // lane-txi: a non-`DCT_DCT` type is charged its
3185 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
3186 // search's weight (default 1 = unchanged). The
3187 // film rows buy 0.04 dB for 1.2% more bytes at
3188 // weight 1 on every frame and every PLANE, key
3189 // frame included -- a rate term this decision
3190 // under-charges (class
3191 // `rd-rate-term-calibration`), not the
3192 // propagation loss the leaves would have shown.
3193 let cost = candidate.sse
3194 + search.lambda * candidate.bits
3195 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
3196 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
3197 best = Some((cost, tx_type, candidate));
3198 }
3199 }
3200 let (_, tx_type, trial) =
3201 best.expect("the candidate list is never empty");
3202 tx_types[tu_row * n + tu_col] = tx_type;
3203 TX_TYPE_HITS[tx_type as usize]
3204 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3205 trial
3206 }
3207 };
3208 sse += trial.sse;
3209 bits += trial.bits;
3210 self.commit(tu.x, tu.y, tx, &trial);
3211 for row in 0..tx {
3212 levels[(row_off + row) * side + col_off..][..tx]
3213 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3214 }
3215 }
3216 }
3217 self.ctx.tu_split = false;
3218 (levels, sse, bits, tx_types)
3219 }
3220
3221 /// Writes a trial's reconstruction back into the plane, and the
3222 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
3223 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
3224 for row in 0..side {
3225 self.reconstruction[(y + row) * self.width + x..][..side]
3226 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
3227 }
3228 self.commit_ctx(x, y, side, &trial.levels);
3229 }
3230
3231 /// Publishes one committed transform's own context over every 4x4 cell it
3232 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
3233 /// which is what the writer will read when it reaches the next block.
3234 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
3235 if self.ctx.cells.is_empty() {
3236 self.ctx.stride = self.width.div_ceil(4);
3237 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
3238 }
3239 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
3240 let state = CoefCtx {
3241 level: cul,
3242 dc: match levels[0].signum() {
3243 0 => 0,
3244 -1 => -1,
3245 _ => 1,
3246 },
3247 };
3248 let n = (side / 4).max(1);
3249 // Only up to the frame's TRUE extent: the writer's own
3250 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
3251 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
3252 // and leaves the cells past it uncoded even mid-block, so a
3253 // straddling block publishes context for its inside part only.
3254 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
3255 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
3256 for row in 0..rows {
3257 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3258 let end = (start + cols).min(self.ctx.cells.len());
3259 if start < end {
3260 self.ctx.cells[start..end].fill(state);
3261 }
3262 }
3263 }
3264
3265 /// A block committed without any residual at all ([`ibc_commit`]): the
3266 /// cells it covers coded nothing, and leaving an earlier trial's state
3267 /// there would price its neighbours off a block that was never coded.
3268 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
3269 self.commit_ctx(x, y, side, &[0i32]);
3270 }
3271
3272 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
3273 /// plane reads, off what the blocks before it in coding order committed
3274 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
3275 /// the above/left neighbours coded anything (tile.rs
3276 /// `write_block_planes`), luma reads context 0 when its transform covers
3277 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
3278 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
3279 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
3280 /// the same neighbours (tile.rs `dc_sign_ctx`).
3281 ///
3282 /// A neighbour outside this plane's own TILE does not exist, exactly as
3283 /// the writer's per-tile `Neighbours` bands start blank.
3284 ///
3285 /// CLOSED (lane-av1straddle): the decisions this price changes used to
3286 /// make `decode_stream_round_trips_an_odd_size_gop` and
3287 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
3288 /// fail at 216x96. Never this map: the writer coded the phantom
3289 /// transform units of a right-edge-straddling 32x32 (tile.rs
3290 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
3291 /// like decode.rs and libaom), which libdav1d and libaom both refused
3292 /// outright while a decision change was what first walked into it.
3293 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
3294 if self.ctx.cells.is_empty() {
3295 return (0, 0);
3296 }
3297 let n = (side / 4).max(1);
3298 let (cx, cy) = (x / 4, y / 4);
3299 let (mut top, mut left) = (0u8, 0u8);
3300 let mut vote = 0i32;
3301 if y > self.tile_y0 && cy > 0 {
3302 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
3303 top |= cell.level;
3304 vote += i32::from(cell.dc);
3305 }
3306 }
3307 if x > self.tile_x0 && cx > 0 {
3308 for row in 0..n {
3309 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
3310 left |= cell.level;
3311 vote += i32::from(cell.dc);
3312 }
3313 }
3314 let skip_ctx = if set.is_chroma() {
3315 usize::from(top != 0) + usize::from(left != 0)
3316 } else if self.ctx.tu_split {
3317 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3318 } else {
3319 0
3320 };
3321 let sign_ctx = match vote.signum() {
3322 0 => 0,
3323 -1 => 1,
3324 _ => 2,
3325 };
3326 (skip_ctx, sign_ctx)
3327 }
3328
3329 /// The source samples of one square, contiguous — what a motion search
3330 /// compares its candidates' predictions against ([`motion::search`]'s
3331 /// `source`), since [`Self::source`] itself is the whole plane, strided
3332 /// by [`Self::width`].
3333 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
3334 rows_of(self.source, self.width, x, y, side)
3335 }
3336
3337 /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
3338 /// root's own HORZ/VERT motion search.
3339 fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
3340 let mut out = vec![0u8; w * h];
3341 for row in 0..h {
3342 out[row * w..][..w]
3343 .copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3344 }
3345 out
3346 }
3347
3348 /// The reconstructed samples of one square, so that a partition trial can
3349 /// be undone.
3350 /// The reconstructed samples of one square AND the coefficient contexts
3351 /// its cells hold, so that a partition trial can be undone whole: a
3352 /// losing trial that left its own nz/DC state behind would price the
3353 /// blocks after it off a block the tile writer never codes.
3354 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
3355 (
3356 rows_of(&self.reconstruction, self.width, x, y, side),
3357 self.ctx_rows(x, y, side),
3358 )
3359 }
3360
3361 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
3362 if self.ctx.cells.is_empty() {
3363 return Vec::new();
3364 }
3365 let n = (side / 4).max(1);
3366 (0..n)
3367 .flat_map(|row| {
3368 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3369 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
3370 })
3371 .collect()
3372 }
3373
3374 /// Puts a snapshot back.
3375 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
3376 for row in 0..side {
3377 self.reconstruction[(y + row) * self.width + x..][..side]
3378 .copy_from_slice(&saved.0[row * side..][..side]);
3379 }
3380 if saved.1.is_empty() {
3381 return;
3382 }
3383 let n = (side / 4).max(1);
3384 for row in 0..n {
3385 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3386 let end = (start + n).min(self.ctx.cells.len());
3387 if start < end {
3388 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
3389 }
3390 }
3391 }
3392
3393 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
3394 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
3395 /// prescreen by the identical rule rather than a second one that could
3396 /// drift from it.
3397 fn intra_scores(
3398 &self,
3399 at: At,
3400 modes: &[u8],
3401 mode_bits: &[f64; 13],
3402 lambda: f64, fctx: &crate::decode::FrameCtx,
3403 ) -> Vec<(f64, u8)> {
3404 let At {
3405 x, y, side, reach, ..
3406 } = at;
3407 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3408 let (above, left, corner) =
3409 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3410 modes
3411 .iter()
3412 .map(|&mode| {
3413 let mut prediction = vec![0u8; side * side];
3414 intra_predict_u8(
3415 mode,
3416 0,
3417 above,
3418 left,
3419 corner,
3420 side,
3421 side,
3422 false,
3423 false,
3424 &mut prediction, fctx,
3425 );
3426 let sad = self.block_sad(x, y, side, &prediction);
3427 (sad + lambda * mode_bits[usize::from(mode)], mode)
3428 })
3429 .collect()
3430 }
3431
3432 /// Codes one block under every mode the search offers (or, when
3433 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
3434 /// pre-pass plus DC) and commits the one whose squared error and
3435 /// estimated rate come out cheapest.
3436 ///
3437 /// The prediction is built once per mode regardless -- the full RD trial
3438 /// needs it too -- so ranking modes by SAD on that same prediction before
3439 /// running the expensive part (forward transform, quantize, reconstruct,
3440 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
3441 /// only to sum.
3442 fn search_block(
3443 &mut self,
3444 at: At,
3445 search: &Search,
3446 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
3447 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
3448 let At {
3449 x, y, side, reach, ..
3450 } = at;
3451 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3452 let (above, left, corner) =
3453 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3454 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
3455 // the census reports it), so summing it under the default unpruned
3456 // search is `side * side` absolute differences per mode spent on a
3457 // number no one reads.
3458 let want_sad = search.top_k.is_some() || census_on();
3459 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
3460 .modes
3461 .iter()
3462 .map(|&mode| {
3463 let mut prediction = vec![0u8; side * side];
3464 intra_predict_u8(
3465 mode,
3466 0,
3467 above,
3468 left,
3469 corner,
3470 side,
3471 side,
3472 false,
3473 false,
3474 &mut prediction, fctx,
3475 );
3476 let sad = if want_sad {
3477 self.block_sad(x, y, side, &prediction)
3478 } else {
3479 0.0
3480 };
3481 (
3482 sad + search.lambda * mode_bits[usize::from(mode)],
3483 mode,
3484 prediction,
3485 )
3486 })
3487 .collect();
3488 if let Some(k) = search.top_k {
3489 if k < scored.len() {
3490 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
3491 let dc_entry = dc_pos.map(|i| scored.remove(i));
3492 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3493 scored.truncate(if dc_entry.is_some() {
3494 k.saturating_sub(1)
3495 } else {
3496 k
3497 });
3498 if let Some(dc_entry) = dc_entry {
3499 scored.push(dc_entry);
3500 }
3501 }
3502 }
3503 let ranking: Vec<(f64, u8)> = if census_on() {
3504 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
3505 } else {
3506 Vec::new()
3507 };
3508 census_add(0, 1);
3509 census_add(1, scored.len());
3510 let mut best: Option<(f64, u8, Trial)> = None;
3511 for (_, mode, prediction) in scored {
3512 let trial = self.code_from_prediction(
3513 x,
3514 y,
3515 side,
3516 &prediction,
3517 false,
3518 search.base_q_idx,
3519 search.deadzone,
3520 at.set,
3521 );
3522 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
3523 if best
3524 .as_ref()
3525 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
3526 {
3527 best = Some((cost, mode, trial));
3528 }
3529 }
3530 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
3531 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
3532 // directional modes each carry a -3..=3 delta, three degrees a step,
3533 // which the writer has always coded as ZERO because nothing searched
3534 // it. Refined on the winning mode only -- libaom's own ordering, and
3535 // six extra trials on the directional blocks instead of on every
3536 // block times every mode. The edges are the ones the base angle
3537 // already read (`enable_intra_edge_filter` is off in this encoder's
3538 // sequence header, so no delta changes which samples exist), and the
3539 // predictor is the decoder's, `angle_delta` argument and all.
3540 let mut angle_delta = 0i32;
3541 // Not on a screen frame: measured on the 5-row native gate, the
3542 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
3543 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
3544 // synthetic edges land on the base angles, so every delta there buys
3545 // a symbol and no prediction. Same `search.screen` gate palette and
3546 // intrabc already stand behind.
3547 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
3548 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
3549 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
3550 let mut prediction = vec![0u8; side * side];
3551 for delta in [-3i32, -2, -1, 1, 2, 3] {
3552 intra_predict_u8(
3553 mode,
3554 delta,
3555 above,
3556 left,
3557 corner,
3558 side,
3559 side,
3560 false,
3561 false,
3562 &mut prediction, fctx,
3563 );
3564 let candidate = self.code_from_prediction(
3565 x,
3566 y,
3567 side,
3568 &prediction,
3569 false,
3570 search.base_q_idx,
3571 search.deadzone,
3572 at.set,
3573 );
3574 let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3575 - zero_bits;
3576 let cost_d = candidate.sse
3577 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
3578 if cost_d < cost {
3579 cost = cost_d;
3580 angle_delta = delta;
3581 trial = candidate;
3582 }
3583 }
3584 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
3585 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3586 }
3587 // lane-txset: the block's own transform type, searched on the mode
3588 // and angle the trials above settled -- the same ordering the angle
3589 // refinement uses, and the same RD terms.
3590 let mut tx_type = TxType::DctDct;
3591 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
3592 let candidate = self.trial_typed(
3593 at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx,
3594 );
3595 let cost_t =
3596 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3597 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3598 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3599 // block's true one for the caller's own decision.
3600 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3601 cost = cost_t;
3602 tx_type = candidate_type;
3603 trial = candidate;
3604 }
3605 }
3606 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3607 if census_on() {
3608 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
3609 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3610 }
3611 self.commit(x, y, side, &trial);
3612 // A 64-point transform codes only its top-left 32x32 corner, which is
3613 // the grid `code_from_prediction` hands back (lane-i64).
3614 (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type)
3615 }
3616}
3617
3618/// Where one block sits in its plane, and how far past its own edges its
3619/// prediction may read.
3620#[derive(Clone, Copy)]
3621struct At {
3622 x: usize,
3623 y: usize,
3624 side: usize,
3625 reach: Reach,
3626 /// Which of the tile writer's coefficient tables this block's levels are
3627 /// coded with, and so which the search prices them through.
3628 set: TxbSet,
3629}
3630
3631/// Which of the samples past a block's own edges the decoder has decoded by
3632/// the time it predicts the block, and so which a directional mode may read.
3633///
3634/// The decoder derives these from its `BlockDecoded` flags, which are cleared
3635/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
3636/// that map, this reads the answer the same way libaom and rav1e do: for a
3637/// block whose transform covers it whole, whether the samples above its right
3638/// (or below its left) are decoded depends only on where the block sits inside
3639/// its 64x64 superblock, which is a pinned table per block size.
3640#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3641pub(crate) struct Reach {
3642 pub(crate) above_right: bool,
3643 pub(crate) below_left: bool,
3644}
3645
3646/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
3647/// libaom): for a block that is neither in the superblock's top row nor its
3648/// rightmost column, whether the block above and to its right is coded before
3649/// it. Indexed by the block's position in the superblock, in blocks of its own
3650/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
3651/// 128, not this crate's 64 superblock -- bit by bit from the low end.
3652const HAS_TOP_RIGHT: [&[u8]; 4] = [
3653 &[255, 85, 119, 85, 127, 85, 119, 85],
3654 &[95, 87],
3655 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
3656 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
3657 &[
3658 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
3659 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
3660 ],
3661
3662 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
3663 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
3664 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
3665 // with side 4 outside a TX4 split; without their own row they clamped
3666 // into the 8x8 table and read above-right samples the decoder has not
3667 // written yet (all-zero pixels in the bottom-right triangle of a
3668 // directional 4x4 leaf).
3669 &[
3670 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
3671 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
3672 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
3673 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
3674 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
3675 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
3676 119, 119, 119, 119, 85, 85, 85, 85,
3677 ],
3678];
3679
3680/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
3681/// left.
3682const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
3683 &[84, 16, 84, 0, 84, 16, 84, 0],
3684 &[4, 4],
3685 // has_bl_8x8 (libaom av1/common/reconintra.c)
3686 &[
3687 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
3688 84, 85, 16, 17, 84, 85, 0, 0,
3689 ],
3690
3691 // has_bl_4x4 (same source, same order).
3692 &[
3693 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
3694 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,
3695 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
3696 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,
3697 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
3698 85, 85, 0, 0, 0, 0,
3699 ],
3700];
3701
3702/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
3703/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
3704/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
3705/// rather than in raster order, so the bottom-left square's top-right
3706/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
3707/// libaom switches tables on the partition type (`get_has_tr_table`); the
3708/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
3709/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
3710/// lane-part32 r5 caught reading undecoded samples.
3711const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
3712 // has_tr_vert_16x16
3713 &[255, 0, 119, 0, 127, 0, 119, 0],
3714 // has_tr_vert_32x32
3715 &[15, 7],
3716 // has_tr_vert_8x8
3717 &[
3718 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
3719 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
3720 ],
3721];
3722
3723/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
3724const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
3725 // has_bl_vert_16x16
3726 &[254, 16, 254, 0, 254, 16, 254, 0],
3727 // has_bl_vert_32x32
3728 &[14, 14],
3729 // has_bl_vert_8x8
3730 &[
3731 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
3732 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
3733 ],
3734];
3735
3736thread_local! {
3737 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
3738 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
3739 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
3740 /// threading one bool through this crate's already twenty-argument
3741 /// `decode_block` would touch every call site instead of the two arms
3742 /// that need it.
3743 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3744}
3745
3746/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
3747pub(crate) struct VertAbGuard(bool);
3748
3749impl Drop for VertAbGuard {
3750 fn drop(&mut self) {
3751 VERT_AB_PARTITION.with(|c| c.set(self.0));
3752 }
3753}
3754
3755/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
3756/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
3757/// so no byte is retyped). Each is indexed by
3758/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
3759/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
3760/// superblock grid; on this crate's 64-pixel superblock the highest index a
3761/// shape can reach stays inside its own table, so no wrap is involved.
3762///
3763/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
3764/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
3765/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
3766/// 10 of the 21 reachable superblock positions for above-right and 7 for
3767/// below-left.
3768/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3769const 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];
3770/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3771const 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];
3772/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3773const 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];
3774/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3775const 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];
3776/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3777const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
3778/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3779const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
3780/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3781const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
3782/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3783const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
3784/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3785const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
3786/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3787const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
3788/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3789const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
3790/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3791const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
3792/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3793const HAS_TR_32X64: [u8; 1] = [127];
3794/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3795const HAS_BL_32X64: [u8; 1] = [0];
3796/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3797const HAS_TR_64X32: [u8; 1] = [19];
3798/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3799const HAS_BL_64X32: [u8; 1] = [34];
3800/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3801const 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];
3802/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3803const 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];
3804/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3805const 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];
3806/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3807const 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];
3808/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3809const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
3810/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3811const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
3812/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3813const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
3814/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3815const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
3816/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3817const HAS_TR_16X64: [u8; 2] = [255, 127];
3818/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3819const HAS_BL_16X64: [u8; 2] = [0, 0];
3820/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3821const HAS_TR_64X16: [u8; 2] = [3, 1];
3822/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3823const HAS_BL_64X16: [u8; 2] = [42, 42];
3824
3825/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
3826fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
3827 match (bw, bh) {
3828 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
3829 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
3830 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
3831 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
3832 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
3833 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
3834 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
3835 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
3836 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
3837 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
3838 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
3839 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
3840 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
3841 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
3842 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
3843 }
3844}
3845
3846impl Reach {
3847 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3848 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
3849 /// own answer is `block` -- a different rule from the standalone-block
3850 /// tables, because a unit's neighbours are mostly its own block's
3851 /// already-reconstructed units:
3852 /// * top-right: available while the unit to the right is still inside
3853 /// the block (`col_off + tx < bw`); otherwise only the block's top row
3854 /// of units reaches past it, through the block-level answer
3855 /// (libaom's `row_off > 0` branch returns exactly
3856 /// `col_off + txw < plane_bw`).
3857 /// * bottom-left: a unit outside the block's left column has none
3858 /// (libaom returns 0 for `col_off > 0`); inside the block
3859 /// (`row_off + tx < bh`) they are the left unit's, already
3860 /// reconstructed; the bottom row falls back to the block-level answer.
3861 pub(crate) fn of_tu(
3862 bw: usize,
3863 bh: usize,
3864 col_off: usize,
3865 row_off: usize,
3866 // The unit's own width and height in pixels; equal for a square
3867 // transform, different for the rect unit a 1:4 strip's first split
3868 // produces (lane-rectsplitx r1).
3869 tx_w: usize,
3870 tx_h: usize,
3871 block: Self,
3872 ) -> Self {
3873 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
3874 // order, so both libaom predicates special-case it (lane-sb128c r10);
3875 // without this the last unit column of every chunk of a 128x64 block
3876 // predicts from a chunk libaom has not decoded yet.
3877 let wide = bw > 64;
3878 Self {
3879 above_right: if row_off > 0 {
3880 // `has_top_right`'s `row_off > 0` branch: the offset is taken
3881 // modulo the 64-wide chunk, except for the one unit whose
3882 // top-right corner is the centre of a 128x128 block.
3883 if wide {
3884 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
3885 } else {
3886 col_off + tx_w < bw
3887 }
3888 } else if col_off + tx_w < bw {
3889 true
3890 } else {
3891 block.above_right
3892 },
3893 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
3894 // `has_bottom_left`: at the left edge of a right-hand chunk
3895 // the bottom-left pixels are in the already-coded left chunk,
3896 // provided they stay inside it.
3897 (row_off % 64) + tx_h < bh.min(64)
3898 } else if col_off > 0 {
3899 false
3900 } else if row_off + tx_h < bh {
3901 true
3902 } else {
3903 block.below_left
3904 },
3905 }
3906 }
3907
3908 /// What a block of `side` samples at `(x, y)` may read past its own edges,
3909 /// in a frame of `width` by `height`.
3910 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
3911 Self {
3912 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
3913 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
3914 }
3915 }
3916
3917 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
3918 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
3919 /// block's own width for the row stride and by its own height for the
3920 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
3921 /// unlike the square [`Self::of`] which uses one `side` for everything.
3922 pub(crate) fn of_rect(
3923 bw: usize,
3924 bh: usize,
3925 x: usize,
3926 y: usize,
3927 width: usize,
3928 height: usize, fctx: &crate::decode::FrameCtx,
3929 ) -> Self {
3930 Self {
3931 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
3932 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
3933 }
3934 }
3935
3936 /// [`Self::of`] for one transform unit of a square block whose transform
3937 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
3938 /// non-zero `row_off`/`col_off`): interior units answer from the block's
3939 /// own geometry, and only a unit on the block's top row (resp. left
3940 /// column) reaches the table -- which is the BLOCK's table read at the
3941 /// BLOCK's position, never a table row for the transform's size. Letting
3942 /// the unit stand in for a block of its own size agrees with libaom for
3943 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
3944 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
3945 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
3946 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
3947 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
3948 /// the transform covering the whole block, luma): everything before the
3949 /// table lookup is that function's own early-exit ladder.
3950 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3951 let sb_mi: usize = reach_sb_px(fctx) / 4;
3952 let (mi_row, mi_col) = (y / 4, x / 4);
3953 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3954 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3955 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3956 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3957 // Top row of the superblock: the top-right pixels are in the (already
3958 // decoded) superblock above.
3959 if blk_row == 0 {
3960 return true;
3961 }
3962 // Rightmost column: they fall in the superblock to the right.
3963 if ((blk_col + 1) << bw_log2) >= sb_mi {
3964 return false;
3965 }
3966 let table = rect_reach_tables(bw, bh).0;
3967 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
3968 }
3969
3970 /// libaom `has_top_right`'s own index arithmetic:
3971 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
3972 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
3973 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
3974 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
3975 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
3976 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
3977 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
3978 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
3979 (blk_row << (5 - bw_log2)) + blk_col
3980 }
3981
3982 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
3983 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3984 let sb_mi: usize = reach_sb_px(fctx) / 4;
3985 let (mi_row, mi_col) = (y / 4, x / 4);
3986 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3987 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3988 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3989 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3990 // Leftmost column of the superblock: the bottom-left pixels are in
3991 // the left superblock iff they stay inside its height.
3992 if blk_col == 0 {
3993 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
3994 }
3995 // Bottom row (and not the leftmost column): they fall in the
3996 // superblock below, which is not decoded yet.
3997 if ((blk_row + 1) << bh_log2) >= sb_mi {
3998 return false;
3999 }
4000 let table = rect_reach_tables(bw, bh).1;
4001 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4002 }
4003
4004 /// Marks every [`Reach::of`] made until the returned guard drops as being
4005 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
4006 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
4007 /// unaffected: libaom's own comment says vertical rectangles keep their
4008 /// non-vert table, which is what [`Reach::of_rect`] already reads.
4009 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
4010 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
4011 /// can count the sub-block work that partition creates (lane-ab16).
4012 pub(crate) fn in_vert_ab() -> bool {
4013 VERT_AB_PARTITION.with(std::cell::Cell::get)
4014 }
4015
4016 pub(crate) fn vert_ab_partition() -> VertAbGuard {
4017 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
4018 }
4019
4020 /// Neither, which is all a mode that reads no further than its own edges
4021 /// needs.
4022 pub(crate) fn none() -> Self {
4023 Self {
4024 above_right: false,
4025 below_left: false,
4026 }
4027 }
4028
4029 /// `has_top_right` for a block whose transform covers it whole: the top
4030 /// row of a superblock reads into the superblock above, which is decoded;
4031 /// the rightmost column would read into the superblock to the right, which
4032 /// is not; and everything between is the table's to answer.
4033 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4034 let (row, col, per_side) = Self::position(side, x, y, fctx);
4035 if row == 0 {
4036 return true;
4037 }
4038 if col + 1 == per_side {
4039 return false;
4040 }
4041 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4042 // (the clamp corner-cut that used to live here is gone); sides
4043 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4044 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4045 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4046 // -- a reach over-estimate (extra above-right reference pixels),
4047 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4048 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4049 // NB: named `table_row`, not `row` -- `row` above is the block's
4050 // position inside the superblock and is what the bit index below
4051 // steps by (a merge that shadowed it desynced every block size).
4052 let table_row = Self::table(side);
4053 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
4054 HAS_TOP_RIGHT_VERT[table_row]
4055 } else {
4056 HAS_TOP_RIGHT[table_row]
4057 };
4058 Self::bit(
4059 table,
4060 (row * Self::table_stride(side) + col) % (table.len() * 8),
4061 )
4062 }
4063
4064 /// `has_bottom_left` for such a block: the leftmost column of a superblock
4065 /// reads into the superblock to its left, which is decoded only as far
4066 /// down as its own bottom; the bottom row would read into the superblock
4067 /// below, which is not decoded at all; and the table answers the rest.
4068 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4069 let (row, col, per_side) = Self::position(side, x, y, fctx);
4070 if col == 0 {
4071 return row * side + side < reach_sb_px(fctx);
4072 }
4073 if row + 1 == per_side {
4074 return false;
4075 }
4076 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4077 // (the clamp corner-cut that used to live here is gone); sides
4078 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4079 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4080 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4081 // -- a reach over-estimate (extra above-right reference pixels),
4082 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4083 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4084 // NB: named `table_row`, not `row` -- `row` above is the block's
4085 // position inside the superblock and is what the bit index below
4086 // steps by (a merge that shadowed it desynced every block size).
4087 let table_row = Self::table(side);
4088 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
4089 HAS_BOTTOM_LEFT_VERT[table_row]
4090 } else {
4091 HAS_BOTTOM_LEFT[table_row]
4092 };
4093 Self::bit(
4094 table,
4095 (row * Self::table_stride(side) + col) % (table.len() * 8),
4096 )
4097 }
4098
4099 /// Where a block sits inside its superblock, in blocks of its own size,
4100 /// and how many of them a superblock is across.
4101 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
4102 let sb = reach_sb_px(fctx);
4103 ((y % sb) / side, (x % sb) / side, sb / side)
4104 }
4105
4106 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
4107 /// these tables to its compile-time maximum superblock (128, spec
4108 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
4109 /// size an encode actually uses, so a block's row in the bit index steps
4110 /// by 128 / `side` even though this crate only ever codes a 64
4111 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
4112 /// here instead indexes the wrong bit for every block size but the one
4113 /// where 64 and 128 give the same stride.
4114 fn table_stride(side: usize) -> usize {
4115 128 / side
4116 }
4117
4118 /// Which of the three block sizes the encoder codes a table row is for.
4119 fn table(side: usize) -> usize {
4120 if side == BLOCK {
4121 1
4122 } else if side == 8 {
4123 2
4124 } else if side == 4 {
4125 3
4126 } else {
4127 0
4128 }
4129 }
4130
4131 /// One bit of a table, counting from the low end of its first byte.
4132 fn bit(table: &[u8], index: usize) -> bool {
4133 (table[index / 8] >> (index % 8)) & 1 != 0
4134 }
4135}
4136
4137/// What one symbol costs against a CDF, in bits.
4138/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
4139/// search, the frame header's `allow_warped_motion` and the sequence's
4140/// `enable_warped_motion`, all three together. ON by default since
4141/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
4142/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
4143/// bits -- back off for an A/B on one build.
4144pub(crate) fn warp_on() -> bool {
4145 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4146 crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
4147 });
4148 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
4149}
4150
4151/// The smallest LEAF an OBMC candidate is offered for, so the census can
4152/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
4153/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
4154/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
4155///
4156/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
4157/// (12 frames, four quantizers, the standing keep table):
4158///
4159/// | min side | film 1080p | film 2160p | screen |
4160/// |---|---|---|---|
4161/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
4162/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
4163/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
4164/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
4165///
4166/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
4167/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
4168/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
4169/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
4170/// that wins the local RD on five blocks in six and loses ladder bytes is
4171/// the `local-RD-on-references` class again, not a missing footprint.
4172///
4173/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
4174/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
4175/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
4176/// loss on the 1080p film became a 0.3-point win and the other two rows went
4177/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
4178/// of the "local win, ladder loss" it was charged with was the rate weight.
4179/// It still does not meet the keep rule (two down, one flat, both columns).
4180/// The tool stays OFF by default; the upgrade path is the price, not the size
4181/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
4182/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
4183/// 1080p film up, i.e. the same disagreement between the two gates).
4184///
4185/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
4186/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
4187/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
4188/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
4189/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
4190/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
4191/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
4192/// the margin's gain are the same bytes. It stays OFF.
4193///
4194/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
4195/// judgement above was taken when the gate's "film" rows were the `testsrc2`
4196/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
4197/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
4198/// the standing native keep table (`bd_rate_screen_native`):
4199///
4200/// | arm | film A | film B | screen | OBMC fire A/B |
4201/// |---|---|---|---|---|
4202/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
4203/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
4204/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
4205///
4206/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
4207/// only), where the anchors' non-skip area is the known gap:
4208///
4209/// | arm | film B long GOP | wall ours |
4210/// |---|---|---|
4211/// | off (control) | +89.8 / +9.1 | 477.5s |
4212/// | min side 8 | +89.6 / +9.0 | 514.1s |
4213///
4214/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
4215/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
4216/// only at min side 16, which is exactly where film B loses 0.7 on both
4217/// columns. Nothing here meets the keep rule (both films down on both
4218/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
4219/// costs +7.7% wall. OBMC stays OFF at every preset.
4220fn obmc_min_side() -> usize {
4221 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4222 *N.get_or_init(|| {
4223 std::env::var("EC_AV1_OBMC_MIN")
4224 .ok()
4225 .and_then(|v| v.parse().ok())
4226 .unwrap_or(8)
4227 })
4228}
4229
4230/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
4231/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
4232/// same frame-CDF price the coefficients of a non-screen frame are estimated
4233/// with, not the static default table.
4234/// The same price for whichever alphabet the writer will really use for this
4235/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
4236/// (`allow_warped_motion` and at least one warp sample), otherwise the
4237/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
4238/// search pay it, so the alphabet cancels out of a comparison and only its
4239/// per-value spread decides.
4240fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
4241 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
4242 return 0.0;
4243 };
4244 match warp_alphabet {
4245 true => crate::tile::motion_mode_symbol_bits(row, motion),
4246 false => crate::tile::obmc_symbol_bits(row, motion == 1),
4247 }
4248}
4249
4250/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
4251/// candidate, the header's `allow_warped_motion` and the sequence's
4252/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
4253/// native keep table, against the same build with the knob off:
4254///
4255/// | clip | warp on | off |
4256/// |---|---|---|
4257/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
4258/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
4259/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
4260///
4261/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
4262/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
4263/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
4264/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
4265/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
4266/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
4267/// this is a measured loss, not an inert knob. Same shape as the OBMC
4268/// candidate above it (`obmc_min_side`): a local RD win that does not convert
4269/// into ladder bytes.
4270///
4271/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
4272/// because a tool whose gain is local and whose cost is the rate it adds is
4273/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
4274///
4275/// | clip | warp on | off (both at lambda 0.05) |
4276/// |---|---|---|
4277/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
4278/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
4279/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
4280///
4281/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
4282/// column inside 0.1 everywhere -- which reads as a keep rather than the
4283/// 0.7/0.9 loss it was.
4284///
4285/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
4286/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
4287/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
4288/// ran the conformance shape the lambda lane deferred: every warp stream
4289/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
4290/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
4291/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
4292/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
4293/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
4294/// `allow_warped_motion` and `enable_warped_motion` back off together.
4295///
4296/// The WARPED_CAUSAL prediction of one square single-reference block: the
4297/// decoder's own warp-sample walk (`decode::find_samples` +
4298/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
4299/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
4300/// grid -- never a second implementation of any of the three. `None` when the
4301/// block would code no motion_mode symbol at all, when it has no warp sample
4302/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
4303/// or when the projection is not filter-representable (the decoder would then
4304/// predict translationally, so the mode is pure cost).
4305#[allow(clippy::too_many_arguments)]
4306fn warp_prediction(
4307 grid: &MiGrid,
4308 (mi_row, mi_col): (usize, usize),
4309 (mi_rows, mi_cols): (usize, usize),
4310 (x, y): (usize, usize),
4311 side: usize,
4312 mv: (i32, i32),
4313 ref_frame: i8,
4314 ref_planes: [(&[u16], usize, usize, usize); 3],
4315 fctx: &crate::decode::FrameCtx,
4316) -> Option<[Vec<u8>; 3]> {
4317 let n4 = side / 4;
4318 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
4319 return None;
4320 }
4321 let mut samples = crate::decode::find_samples(
4322 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
4323 );
4324 if samples.is_empty() {
4325 return None;
4326 }
4327 if samples.len() > 1 {
4328 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
4329 }
4330 let params = crate::warp::find_projection(
4331 &samples,
4332 side as i32,
4333 side as i32,
4334 mv.1,
4335 mv.0,
4336 mi_row as i32,
4337 mi_col as i32,
4338 )?;
4339 let mut pred = [
4340 vec![0u16; side * side],
4341 vec![0u16; side * side / 4],
4342 vec![0u16; side * side / 4],
4343 ];
4344 // The translational prediction first, exactly as the decoder builds it,
4345 // then the affine one over the planes whose OWN block is at least 8x8
4346 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
4347 // 4x4 chroma stays translational).
4348 for (i, r) in ref_planes.into_iter().enumerate() {
4349 let luma_plane = i == 0;
4350 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
4351 let s = if luma_plane { side } else { side / 2 };
4352 mc::predict(
4353 r.0,
4354 r.1,
4355 r.2,
4356 r.3,
4357 mv_to_q4(px, mv.1, luma_plane),
4358 mv_to_q4(py, mv.0, luma_plane),
4359 s,
4360 s,
4361 &mut pred[i],
4362 fctx,
4363 );
4364 if crate::decode::warp_plane_allowed(s, s) {
4365 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
4366 crate::warp::warp_affine(
4367 &params,
4368 r.0,
4369 r.2 as i32,
4370 r.3 as i32,
4371 r.1 as i32,
4372 &mut pred[i],
4373 px as i32,
4374 py as i32,
4375 cside,
4376 cside,
4377 cside,
4378 sub,
4379 sub,
4380 fctx,
4381 );
4382 }
4383 }
4384 let [py_buf, pu_buf, pv_buf] = pred;
4385 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4386 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4387}
4388
4389/// What tile.rs' `write_compound_ref_frames` pays for the pair
4390/// `(ref0, ref1)`, symbol for symbol, each at the context its own
4391/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
4392/// derives from the block's above/left neighbours -- plus the `comp_mode`
4393/// symbol itself at `reference_mode_ctx`.
4394///
4395/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
4396/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
4397/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
4398/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4399pub(crate) fn compound_ref_bits(
4400 (ref0, ref1): (i8, i8),
4401 stack: &crate::mvstack::MvStack,
4402) -> f64 {
4403 use crate::mvstack::{
4404 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4405 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
4406 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
4407 uni_comp_ref_p1_ctx,
4408 };
4409 let (a, a1) = stack.above_refs;
4410 let (l, l1) = stack.left_refs;
4411 let unidir = is_uni_comp_ref(ref0, ref1);
4412 let comp_mode = symbol_bits(
4413 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4414 1,
4415 );
4416 let ref_type = symbol_bits(
4417 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
4418 usize::from(!unidir),
4419 );
4420 if unidir {
4421 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
4422 let p0 = symbol_bits(
4423 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4424 usize::from(both_backward),
4425 );
4426 if both_backward {
4427 return comp_mode + ref_type + p0;
4428 }
4429 let past_last2 = ref1 != LAST2_FRAME;
4430 let p1 = symbol_bits(
4431 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
4432 usize::from(past_last2),
4433 );
4434 let p2 = if past_last2 {
4435 symbol_bits(
4436 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4437 usize::from(ref1 == GOLDEN_FRAME),
4438 )
4439 } else {
4440 0.0
4441 };
4442 return comp_mode + ref_type + p0 + p1 + p2;
4443 }
4444 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
4445 let fwd = symbol_bits(
4446 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
4447 usize::from(far),
4448 ) + if far {
4449 symbol_bits(
4450 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4451 usize::from(ref0 == GOLDEN_FRAME),
4452 )
4453 } else {
4454 symbol_bits(
4455 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
4456 usize::from(ref0 == LAST2_FRAME),
4457 )
4458 };
4459 let is_altref = ref1 == ALTREF_FRAME;
4460 let bwd = symbol_bits(
4461 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
4462 usize::from(is_altref),
4463 ) + if is_altref {
4464 0.0
4465 } else {
4466 symbol_bits(
4467 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
4468 usize::from(ref1 == ALTREF2_FRAME),
4469 )
4470 };
4471 comp_mode + ref_type + fwd + bwd
4472}
4473
4474/// What the `skip` symbol costs at the context tile.rs really codes it with
4475/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
4476/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
4477/// exactly the difference between this symbol's two values, so the row it is
4478/// read from moves that decision (class pricer-context-zero, lane-ctx).
4479pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
4480 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
4481 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
4482}
4483
4484/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
4485/// neighbours' intra/inter state, with an out-of-tile side contributing
4486/// nothing, off the same two cells (lane-ctx).
4487pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
4488 let ctx = crate::tile::intra_inter_ctx(
4489 stack.above_nbr.is_some(),
4490 stack.left_nbr.is_some(),
4491 stack.above_nbr.is_some_and(|n| n.is_inter),
4492 stack.left_nbr.is_some_and(|n| n.is_inter),
4493 );
4494 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
4495}
4496
4497/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
4498/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
4499/// context -- zero on a frame that carries no `reference_select` bit, where
4500/// the writer codes no symbol at all.
4501fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
4502 if !reference_select() {
4503 return 0.0;
4504 }
4505 symbol_bits(
4506 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4507 0,
4508 )
4509}
4510
4511/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
4512/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
4513/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
4514/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
4515/// LAST is p1=0,p3=0,p4=0,
4516/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
4517/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
4518/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
4519/// symbols off the wrong CDFs -- which is what made the search believe an
4520/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
4521/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
4522/// paid nothing at all, so compound was overcharged by the whole symbol.
4523pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
4524 use crate::mvstack::{
4525 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4526 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4527 single_ref_p5_ctx, single_ref_p6_ctx,
4528 };
4529 let (a, a1) = stack.above_refs;
4530 let (l, l1) = stack.left_refs;
4531 let comp_mode = comp_mode_single_bits(stack);
4532 let backward = ref_frame >= BWDREF_FRAME;
4533 let p1 = symbol_bits(
4534 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4535 usize::from(backward),
4536 );
4537 if backward {
4538 let is_altref = ref_frame == ALTREF_FRAME;
4539 let p2 = symbol_bits(
4540 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
4541 usize::from(is_altref),
4542 );
4543 return comp_mode
4544 + p1
4545 + p2
4546 + if is_altref {
4547 0.0
4548 } else {
4549 symbol_bits(
4550 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
4551 usize::from(ref_frame == ALTREF2_FRAME),
4552 )
4553 };
4554 }
4555 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4556 comp_mode + p1 + symbol_bits(
4557 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4558 usize::from(far),
4559 ) + if far {
4560 symbol_bits(
4561 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4562 usize::from(ref_frame == GOLDEN_FRAME),
4563 )
4564 } else {
4565 symbol_bits(
4566 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4567 usize::from(ref_frame == LAST2_FRAME),
4568 )
4569 }
4570}
4571
4572pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
4573 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
4574 let width = cdf[symbol] - low;
4575 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
4576 // 32769 prices a symbol can carry; the `log2` behind each is computed
4577 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
4578 // profile -- this function is called for every symbol of every candidate
4579 // the RD search prices). Each entry is exactly the expression this used
4580 // to evaluate, so every price is bit-identical.
4581 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
4582 PRICES.get_or_init(|| {
4583 (0..=32768u32)
4584 .map(|w| -(f64::from(w) / 32768.0).log2())
4585 .collect()
4586 })[usize::from(width)]
4587}
4588
4589/// What the tile writer spends to say a block is coded in each of the thirteen
4590/// modes, given the modes of the blocks above it and to its left: the luma mode
4591/// symbol against the CDF those two neighbours pick, the angle delta a
4592/// directional mode carries, and the chroma mode symbol, whose CDF the luma
4593/// mode itself indexes.
4594///
4595/// Without this the search is blind to what a mode costs to name, which is not
4596/// a rounding error: a directional mode on a picture that does not run that way
4597/// is a rate loss the squared error never sees.
4598/// Codes one square of the picture as a single block: searches the luma mode,
4599/// codes both chroma planes DC, and hands back the block and what it cost --
4600/// squared error plus lambda times the bits its symbols spend.
4601/// How many halvings of a `side`-square block's transform the `tx_depth`
4602/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
4603/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
4604fn max_tx_depth(side: usize) -> usize {
4605 match side {
4606 8 => 1,
4607 16 | 32 => 2,
4608 _ => 0,
4609 }
4610}
4611
4612/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
4613/// Priced at context row 0 -- the writer picks the real row from its
4614/// neighbours' transform sizes, which the search has no view of; the term is
4615/// the same for every depth of one block either way, so it only shifts the
4616/// depth-0-versus-split margin, never the ordering between two splits.
4617fn tx_depth_bits(side: usize, depth: usize) -> f64 {
4618 match side {
4619 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
4620 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
4621 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
4622 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
4623 }
4624}
4625
4626/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4627/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4628/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4629/// (the mode search's own weight); below 1 the split trial is charged less
4630/// for its bits and fires more often.
4631///
4632/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4633/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4634/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4635/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4636/// so what is mis-calibrated is the weight the split's rate is judged under,
4637/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4638pub(crate) fn split_lambda_mult() -> f64 {
4639 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4640 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4641 .ok()
4642 .and_then(|v| v.parse().ok())
4643 .unwrap_or(SPLIT_LAMBDA)
4644 });
4645 *M
4646}
4647
4648/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4649/// the sweep that chose it.
4650const SPLIT_LAMBDA: f64 = 1.0;
4651
4652/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4653/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
4654/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
4655/// trials offered, trials the split won, then the (rate, distortion) of the
4656/// split and flat arms summed apart for the split-won and flat-won trials --
4657/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
4658static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
4659 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
4660
4661/// Whether [`SPLIT_CENSUS`] is armed, read once.
4662pub(crate) fn split_census_on() -> bool {
4663 static ON: std::sync::LazyLock<bool> =
4664 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
4665 *ON
4666}
4667
4668/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
4669/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
4670fn split_census_base(site: usize, key: bool, side: usize) -> usize {
4671 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
4672 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
4673}
4674
4675/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
4676/// `(rate in bits, distortion as squared error)`.
4677fn split_census(
4678 site: usize,
4679 key: bool,
4680 side: usize,
4681 split_won: bool,
4682 split: (f64, f64),
4683 flat: (f64, f64),
4684) {
4685 use std::sync::atomic::Ordering::Relaxed;
4686 let base = split_census_base(site, key, side);
4687 let add = |i: usize, v: u64| {
4688 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
4689 };
4690 add(0, 1);
4691 let off = if split_won {
4692 add(1, 1);
4693 2
4694 } else {
4695 6
4696 };
4697 let (win, lose) = if split_won { (split, flat) } else { (flat, split) };
4698 add(off, (win.0 * 64.0).max(0.0) as u64);
4699 add(off + 1, win.1.max(0.0) as u64);
4700 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
4701 add(off + 3, lose.1.max(0.0) as u64);
4702}
4703
4704/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
4705/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
4706/// last table a run prints is the whole encode's total (there is no flush
4707/// hook the encoder API guarantees to reach).
4708pub(crate) fn dump_split_census() {
4709 use std::sync::atomic::Ordering::Relaxed;
4710 eprintln!(
4711 "SPLITCENSUS site frame side offered split share% \
4712 win_rate win_dist lose_rate lose_dist"
4713 );
4714 for site in 0..2 {
4715 for key in [true, false] {
4716 for side_idx in 0..4 {
4717 let base = split_census_base(site, key, 8 << side_idx);
4718 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
4719 if v[0] == 0 {
4720 continue;
4721 }
4722 let (n, s) = (v[0] as f64, v[1] as f64);
4723 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
4724 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
4725 // all `n` trials, not a mean of two means.
4726 eprintln!(
4727 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
4728 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
4729 if site == 0 { "intra" } else { "inter" },
4730 if key { "key " } else { "inter" },
4731 8 << side_idx,
4732 v[0],
4733 v[1],
4734 100.0 * s / n,
4735 (v[2] + v[6]) as f64 / n / 64.0,
4736 (v[3] + v[7]) as f64 / n,
4737 (v[4] + v[8]) as f64 / n / 64.0,
4738 (v[5] + v[9]) as f64 / n,
4739 );
4740 }
4741 }
4742 }
4743}
4744
4745/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
4746/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
4747/// its mode/reference syntax and not the search's own cost function
4748/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
4749/// control; below 1 a coded vector is charged less and `NEWMV` wins more
4750/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
4751pub(crate) fn mv_lambda_mult() -> f64 {
4752 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4753 crate::envflags::var("EC_AV1_MV_LAMBDA")
4754 .ok()
4755 .and_then(|v| v.parse().ok())
4756 .unwrap_or(MV_LAMBDA)
4757 });
4758 *M
4759}
4760
4761/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
4762const MV_LAMBDA: f64 = 1.0;
4763
4764/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
4765/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
4766/// which the RD cost multiplies by lambda). Zero at the default weight.
4767fn mv_rate_surcharge(mv_bits: f64) -> f64 {
4768 (mv_lambda_mult() - 1.0) * mv_bits
4769}
4770
4771/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
4772/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
4773/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
4774/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
4775/// cost it won by, 4 the summed cost it lost by, 5 the summed
4776/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
4777/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
4778/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
4779/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
4780/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
4781static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
4782 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
4783
4784/// Whether [`NEWMV_CENSUS`] is armed, read once.
4785pub(crate) fn newmv_census_on() -> bool {
4786 static ON: std::sync::LazyLock<bool> =
4787 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
4788 *ON
4789}
4790
4791/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
4792fn newmv_census_global(i: usize) {
4793 if newmv_census_on() {
4794 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4795 }
4796}
4797
4798/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
4799/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
4800/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
4801/// candidate's own; both `f64::INFINITY` is a block that offered neither.
4802fn newmv_census_block(
4803 side: usize,
4804 offered: bool,
4805 new_cost: f64,
4806 other_cost: f64,
4807 mv: (i32, i32),
4808 nearest: (i32, i32),
4809 mv_bits: f64,
4810) {
4811 if !newmv_census_on() {
4812 return;
4813 }
4814 use std::sync::atomic::Ordering::Relaxed;
4815 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
4816 let add = |i: usize, v: u64| {
4817 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
4818 };
4819 add(0, 1);
4820 if !offered {
4821 return;
4822 }
4823 add(1, 1);
4824 if new_cost < other_cost {
4825 add(2, 1);
4826 add(3, (other_cost - new_cost).max(0.0) as u64);
4827 } else {
4828 add(4, (new_cost - other_cost).max(0.0) as u64);
4829 }
4830 add(5, ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64);
4831 if mv == nearest {
4832 add(6, 1);
4833 }
4834 add(7, (mv_bits * 64.0).max(0.0) as u64);
4835}
4836
4837/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
4838/// same guard [`dump_split_census`] rides (cumulative, so the last table a
4839/// run prints is the whole encode's).
4840pub(crate) fn dump_newmv_census() {
4841 use std::sync::atomic::Ordering::Relaxed;
4842 eprintln!(
4843 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
4844 mv_dist_q3 mv==nearest% mv_bits"
4845 );
4846 for side_idx in 0..4 {
4847 let base = side_idx * 8;
4848 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
4849 if v[0] == 0 {
4850 continue;
4851 }
4852 let off = v[1].max(1) as f64;
4853 eprintln!(
4854 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
4855 8 << side_idx,
4856 v[0],
4857 v[1],
4858 v[2],
4859 100.0 * v[2] as f64 / off,
4860 v[3] as f64 / v[2].max(1) as f64,
4861 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
4862 v[5] as f64 / off,
4863 100.0 * v[6] as f64 / off,
4864 v[7] as f64 / off / 64.0,
4865 );
4866 }
4867 // lane-hpmv: how many mv components this encode coded an eighth-pel bit
4868 // for, and how many of those named a vector no non-hp frame can code.
4869 let (hp_all, hp_eighth) = crate::tile::hp_symbols();
4870 eprintln!(
4871 "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)",
4872 100.0 * hp_eighth as f64 / hp_all.max(1) as f64,
4873 );
4874 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
4875 eprintln!(
4876 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
4877 leaf second reference {}/{} ({:.1}%)",
4878 g[1],
4879 g[0],
4880 100.0 * g[1] as f64 / g[0].max(1) as f64,
4881 g[3],
4882 g[2],
4883 100.0 * g[3] as f64 / g[2].max(1) as f64,
4884 );
4885 let [calls, evals, _subpel, rounds, near_pred, unmoved, widest, widest_moves] =
4886 crate::motion::take_census();
4887 let per = |n: u64| n as f64 / calls.max(1) as f64;
4888 eprintln!(
4889 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
4890 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
4891 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
4892 per(evals),
4893 per(rounds),
4894 100.0 * near_pred as f64 / calls.max(1) as f64,
4895 100.0 * unmoved as f64 / calls.max(1) as f64,
4896 100.0 * widest as f64 / calls.max(1) as f64,
4897 per(widest_moves),
4898 );
4899}
4900
4901/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
4902/// the intra witness's fire count stays its own.
4903pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4904 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4905
4906/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
4907/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
4908/// `0` compares types on reconstruction error alone, which is what separates
4909/// a rate-term calibration (class `rd-rate-term-calibration`) from a
4910/// distortion the trial mis-measures.
4911pub(crate) fn tx_type_lambda_mult() -> f64 {
4912 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4913 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
4914 .ok()
4915 .and_then(|v| v.parse().ok())
4916 .unwrap_or(1.0)
4917 });
4918 *M
4919}
4920
4921/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
4922/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
4923/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
4924/// question needs: at weight 1 the five-type intra search spends 1.2% more
4925/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
4926/// of the type it picks.
4927pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
4928 if tx_type == TxType::DctDct {
4929 0.0
4930 } else {
4931 lambda * (tx_type_lambda_mult() - 1.0) * bits
4932 }
4933}
4934
4935/// lane-txrd instrument: over the FLAT inter luma decision, the summed
4936/// reconstruction error and priced bits of the type the search chose against
4937/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
4938/// integer counter. `EC_AV1_TXRD_CENSUS`.
4939pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
4940 std::sync::atomic::AtomicU64::new(0),
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];
4948
4949/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
4950/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
4951#[cfg(test)]
4952pub(crate) fn take_txrd_stats() -> [u64; 7] {
4953 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4954}
4955
4956/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
4957#[cfg(test)]
4958pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
4959 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4960}
4961
4962/// How many luma transform units resolved to each [`TxType`], indexed by the
4963/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
4964/// and the instrument that says which types the search actually reaches.
4965pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4966 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4967
4968/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
4969/// counts to its own encode.
4970#[cfg(test)]
4971pub(crate) fn take_tx_type_hits() -> [usize; 16] {
4972 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4973}
4974
4975/// How many blocks resolved to each `tx_depth`, the fire count that says
4976/// whether the depth search below reaches its candidates at all.
4977static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
4978 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
4979
4980/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
4981/// to its own encode.
4982#[cfg(test)]
4983pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
4984 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
4985}
4986
4987/// How many inter blocks resolved to each var-tx depth (0 = one transform
4988/// over the whole block, 1 = its four halves), the fire count a gate prints
4989/// to see the split search reach its candidates at all. Indexed
4990/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
4991/// says which of the four block classes the split reaches -- the 32x32 root
4992/// and the compound blocks are this lane's two new ones.
4993static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
4994 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
4995
4996/// Whether a 32x32 inter winner searches its own var-tx depth (the four
4997/// 16x16 units against the flat transform) instead of coding depth 0 blind.
4998/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
4999///
5000/// Rejected three times on the bars rows of the native gate (flat to +0.3).
5001/// lane-av1resweep re-judged it on the two REAL film crops at
5002/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
5003/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
5004///
5005/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
5006/// |---|---|---|---|
5007/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
5008/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
5009/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
5010/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
5011/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
5012///
5013/// The bars rows are ~90% zero-intra-cost cells, so the split never had
5014/// residual to reach there -- the tool was being judged on content that
5015/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
5016fn tx32_depth_search() -> bool {
5017 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5018 crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5019 });
5020 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
5021}
5022
5023/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
5024/// trial units have to be predicted from BOTH references
5025/// ([`mc_trial_compound`]) or the split would re-predict them by single-
5026/// reference translation, which is not what the decoder reconstructs.
5027/// ON by default (the table on [`tx32_depth_search`]: on real film it is
5028/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
5029/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
5030/// `EC_AV1_COMP_VARTX`.
5031fn compound_var_tx() -> bool {
5032 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5033 crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5034 });
5035 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
5036}
5037
5038/// How many 32x32-and-below inter blocks each reference frame won, indexed by
5039/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
5040/// fire count a gate prints to see an extra reference reach a block at all
5041/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
5042/// chosen is a pyramid that costs bytes and buys nothing).
5043static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
5044 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5045
5046/// Reads [`REF_FRAME_HITS`] and zeroes it.
5047#[cfg(test)]
5048pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
5049 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
5050}
5051
5052/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
5053#[cfg(test)]
5054pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
5055 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5056}
5057
5058/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
5059/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
5060/// is one flag, depth 1 is a split root plus one unsplit flag per child
5061/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
5062/// or a 4x4 sub-size).
5063fn txfm_split_bits(side: usize, depth: usize) -> f64 {
5064 let max_tx = side.min(64);
5065 let ctx = |tx: usize| {
5066 crate::decode::txfm_partition_ctx_rect(
5067 crate::decode::TXFM_CTX_INIT,
5068 crate::decode::TXFM_CTX_INIT,
5069 side,
5070 tx,
5071 tx,
5072 )
5073 };
5074 if depth == 0 {
5075 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
5076 }
5077 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
5078 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
5079}
5080
5081/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
5082/// type is never coded -- the decoder takes the LUMA type of the block's
5083/// chroma-reference position and reduces it to the set the chroma size allows
5084/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
5085/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
5086/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
5087/// basis they were never produced for: on the bars gate row the luma of the
5088/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
5089/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
5090/// collapse two lanes attributed to the type PRICE (class
5091/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
5092/// field the encoder never mirrored).
5093///
5094/// Re-codes the two chroma planes of a committed inter block at the type the
5095/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
5096/// the trials the caller already holds are right.
5097#[allow(clippy::too_many_arguments)]
5098fn recode_inter_chroma(
5099 chroma: &[Plane; 2],
5100 (x, y): (usize, usize),
5101 side: usize,
5102 mv: (i32, i32),
5103 refs: [(&[u16], usize, usize, usize); 2],
5104 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
5105 search: &Search,
5106 set: TxbSet,
5107 luma_tx_type: TxType,
5108 fctx: &crate::decode::FrameCtx,
5109) -> Option<[Trial; 2]> {
5110 let c = side / 2;
5111 let tx = crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
5112 if tx == TxType::DctDct {
5113 return None;
5114 }
5115 Some([0usize, 1].map(|p| match second {
5116 Some((mv1, r1)) => mc_trial_compound_typed(
5117 &chroma[p], x / 2, y / 2, c, (mv, mv1), false, refs[p], r1[p], search.base_q_idx,
5118 search.deadzone, set, tx, fctx,
5119 ),
5120 None => mc_trial_typed(
5121 &chroma[p], x / 2, y / 2, c, mv, false, refs[p].0, refs[p].1, refs[p].2, refs[p].3,
5122 false, search.base_q_idx, search.deadzone, set, tx, fctx,
5123 ),
5124 }))
5125}
5126
5127/// The inter block's own var-tx decision, once its motion vector is settled:
5128/// its residual as ONE transform over the whole block, or as the four
5129/// transforms of half the side the tree's first halving names. The prediction
5130/// is the same motion compensation either way, so the split trial
5131/// re-transforms the identical residual in four pieces -- it wins where four
5132/// small transforms carry a locally varying residual cheaper than one big
5133/// one. Commits the winner into `luma` and hands back its block-coordinate
5134/// levels, the depth the writer codes and the cost the winner adds to (or
5135/// takes off) the caller's already-computed flat cost.
5136///
5137/// Only for a block wholly inside the frame: past the true edge the reader's
5138/// var-tx recursion skips the units that fall outside
5139/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
5140/// leave the residual units this writes unpaired.
5141#[allow(clippy::too_many_arguments)]
5142fn commit_inter_luma(
5143 luma: &mut Plane,
5144 (x, y): (usize, usize),
5145 side: usize,
5146 mv: (i32, i32),
5147 reference: (&[u16], usize, usize, usize),
5148 search: &Search,
5149 flat: &Trial,
5150 skip: bool,
5151 // A COMPOUND winner's second half: the vector and reference planes the
5152 // trial units are blended from ([`mc_trial_compound`], the decoder's own
5153 // `comp_group_idx == 0` average). `None` is the single-reference block.
5154 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
5155 fctx: &crate::decode::FrameCtx,
5156) -> (Vec<i32>, u8, f64, Vec<TxType>) {
5157 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
5158 // type out of the two-type inter set the writer already codes a symbol
5159 // for, priced the same way the intra search is (sse + lambda * bits, the
5160 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
5161 // block codes no residual and the 64-point transform names no type.
5162 let mut flat_typed: Option<Trial> = None;
5163 let mut flat_type = TxType::DctDct;
5164 if !skip {
5165 // lane-intertx: on a `reduced_tx_set = 0` frame the search names the
5166 // Set1 alphabet the writer codes into ([`luma_set_for`], the shape
5167 // the intra search already takes), which is what makes the wider
5168 // seven-type candidate list below reachable -- and prices every
5169 // candidate, `IDTX` included, in the alphabet its symbol is really
5170 // coded into.
5171 if let Some(fset) =
5172 inter_luma_set(side).map(|set| luma_set_for(set, search.screen))
5173 {
5174 let lambda = search.lambda * tx_type_lambda_mult();
5175 let cost = |t: &Trial| t.sse + lambda * t.bits;
5176 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
5177 if tx_type == TxType::DctDct {
5178 continue;
5179 }
5180 let candidate = match second {
5181 Some((mv1, ref1)) => mc_trial_compound_typed(
5182 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5183 search.deadzone, fset, tx_type, fctx,
5184 ),
5185 None => mc_trial_typed(
5186 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5187 reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type,
5188 fctx,
5189 ),
5190 };
5191 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
5192 flat_type = tx_type;
5193 flat_typed = Some(candidate);
5194 }
5195 }
5196 }
5197 }
5198 // Counted at the return points, so the census names the types the block
5199 // really CODES -- a split unit's winner that the flat cost then beats was
5200 // never written (class `counter from refused stream`).
5201 let count = |types: &[TxType]| {
5202 for &t in types {
5203 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5204 }
5205 };
5206 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
5207 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
5208 use std::sync::atomic::Ordering::Relaxed;
5209 TXRD_STATS[0].fetch_add(1, Relaxed);
5210 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
5211 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
5212 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
5213 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
5214 // Is the `DCT_DCT` baseline the search compares against the trial
5215 // THIS function would build for the same block? A stale or
5216 // differently-predicted baseline is what would let a candidate win on
5217 // both terms at once (class `local-rd-on-references` vs a real
5218 // pricing defect); re-predicting it here is the only way to tell.
5219 if let Some(fset) = inter_luma_set(side) {
5220 let here = match second {
5221 Some((mv1, ref1)) => mc_trial_compound_typed(
5222 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5223 search.deadzone, fset, TxType::DctDct, fctx,
5224 ),
5225 None => mc_trial_typed(
5226 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5227 reference.3, false, search.base_q_idx, search.deadzone, fset,
5228 TxType::DctDct, fctx,
5229 ),
5230 };
5231 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
5232 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
5233 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
5234 let n = TXRD_STATS[0].load(Relaxed);
5235 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
5236 eprintln!(
5237 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
5238 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
5239 sse={:.0} bits={:.1}",
5240 second.is_some(), flat.sse, flat.bits, here.sse, here.bits,
5241 flat_ref.sse, flat_ref.bits,
5242 );
5243 }
5244 }
5245 }
5246 // What the caller's already-counted `flat` cost has to be corrected by
5247 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
5248 let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits)
5249 - (flat.sse + search.lambda * flat.bits);
5250 let eligible = tx_select()
5251 && tx_select_inter()
5252 && !skip
5253 && side >= 16
5254 && (second.is_none() || compound_var_tx())
5255 && (side != BLOCK || tx32_depth_search())
5256 && x + side <= luma.true_width
5257 && y + side <= luma.true_height;
5258 if !eligible {
5259 luma.commit(x, y, side, flat_ref);
5260 count(&[flat_type]);
5261 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
5262 }
5263 let tx = side / 2;
5264 let set = luma_set_for(
5265 if tx >= 32 {
5266 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
5267 TxbSet::Luma32Inter
5268 } else if tx >= 16 {
5269 TxbSet::Luma16Inter
5270 } else {
5271 TxbSet::Luma8Inter
5272 },
5273 search.screen,
5274 );
5275 let mut levels = vec![0i32; side * side];
5276 let (mut sse, mut bits) = (0.0, 0.0);
5277 let mut units = Vec::with_capacity(4);
5278 // The split units are smaller than their block, so their `txb_skip`
5279 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
5280 // each unit's own commit publishes what the next one reads, coding order.
5281 luma.ctx.tu_split = true;
5282 // One type per unit in the writer's own raster order (tile.rs
5283 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
5284 let mut split_types = vec![TxType::DctDct; 4];
5285 for tu_row in 0..2 {
5286 for tu_col in 0..2 {
5287 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
5288 let unit = |tx_type: TxType| match second {
5289 Some((mv1, ref1)) => mc_trial_compound_typed(
5290 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
5291 search.base_q_idx, search.deadzone, set, tx_type, fctx,
5292 ),
5293 None => mc_trial_typed(
5294 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
5295 reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx,
5296 ),
5297 };
5298 let mut best: Option<(f64, TxType, Trial)> = None;
5299 for &tx_type in inter_tx_type_candidates(set, search.screen) {
5300 let candidate = unit(tx_type);
5301 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
5302 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
5303 best = Some((cost, tx_type, candidate));
5304 }
5305 }
5306 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
5307 split_types[tu_row * 2 + tu_col] = tx_type;
5308 sse += trial.sse;
5309 bits += trial.bits;
5310 for row in 0..tx {
5311 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
5312 .copy_from_slice(&trial.levels[row * tx..][..tx]);
5313 }
5314 units.push((tu_x, tu_y, trial));
5315 }
5316 }
5317 luma.ctx.tu_split = false;
5318 let split_rate = bits + txfm_split_bits(side, 1);
5319 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
5320 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
5321 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
5322 if split_census_on() {
5323 split_census(1, false, side, split_cost < flat_cost, (split_rate, sse), (flat_rate, flat_ref.sse));
5324 }
5325 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
5326 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
5327 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
5328 // in the leaf row (class `gate-blind-to-feature`).
5329 let counted = side <= BLOCK;
5330 if split_cost < flat_cost {
5331 for (tu_x, tu_y, trial) in &units {
5332 luma.commit(*tu_x, *tu_y, tx, trial);
5333 }
5334 if counted {
5335 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5336 }
5337 count(&split_types);
5338 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
5339 }
5340 if counted {
5341 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5342 }
5343 luma.commit(x, y, side, flat_ref);
5344 count(&[flat_type]);
5345 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
5346}
5347
5348/// The largest distinct-colour count a block may hold and still be offered a
5349/// palette candidate at all: past it the k-means quantisation costs more
5350/// error than the map saves rate, and every trial is wasted wall.
5351///
5352/// Swept on the gate's own screen capture (lane-av1pal2, the
5353/// `unswept-decision-constants` class): 32 (the value this lane inherited)
5354/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
5355/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
5356/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
5357/// binds on nothing this content holds. 128 ships: best BD against both
5358/// references and no wall cost at all (6.1s, the same as at 32, because the
5359/// blocks it newly admits are ones the RD then keeps).
5360/// `EC_AV1_PAL_MAXCOLORS`.
5361fn palette_max_colors() -> usize {
5362 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5363 *N.get_or_init(|| {
5364 std::env::var("EC_AV1_PAL_MAXCOLORS")
5365 .ok()
5366 .and_then(|v| v.parse().ok())
5367 .unwrap_or(128)
5368 })
5369}
5370
5371/// The palettes worth trying for one block's luma, in the shape libaom's
5372/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
5373/// distinct colours takes them ALL (the prediction is then exact and the
5374/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
5375/// one-dimensional Lloyd iteration seeded evenly across its range -- both
5376/// offered, because which wins is an RD question the caller answers.
5377/// `block` is `side*side` source samples, row-major.
5378fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
5379 let mut histogram = [0u32; 256];
5380 for &v in block {
5381 histogram[usize::from(v)] += 1;
5382 }
5383 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
5384 if present.len() < 2 {
5385 return Vec::new();
5386 }
5387 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
5388 let mut base = [0u16; 8];
5389 base[..colors.len()].copy_from_slice(colors);
5390 let map = block
5391 .iter()
5392 .map(|&v| {
5393 colors
5394 .iter()
5395 .enumerate()
5396 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
5397 .map(|(i, _)| i as u8)
5398 .expect("a palette holds at least two colours")
5399 })
5400 .collect();
5401 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
5402 };
5403 if present.len() <= 8 {
5404 return vec![exact(&present)];
5405 }
5406 if present.len() > palette_max_colors() {
5407 return Vec::new();
5408 }
5409 let (lo, hi) = (
5410 i32::from(present[0]),
5411 i32::from(present[present.len() - 1]),
5412 );
5413 let mut out = Vec::with_capacity(2);
5414 for n in [8usize, 4] {
5415 // Even seeding across the block's own range, then four Lloyd passes
5416 // over the histogram (256 bins, not `side*side` pixels).
5417 let mut centres: Vec<f64> = (0..n)
5418 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
5419 .collect();
5420 for _ in 0..4 {
5421 let mut sums = vec![0f64; n];
5422 let mut counts = vec![0u32; n];
5423 for (v, &count) in histogram.iter().enumerate() {
5424 if count == 0 {
5425 continue;
5426 }
5427 let k = (0..n)
5428 .min_by(|&a, &b| {
5429 (centres[a] - v as f64)
5430 .abs()
5431 .total_cmp(&(centres[b] - v as f64).abs())
5432 })
5433 .expect("n >= 2");
5434 sums[k] += (v as u32 * count) as f64;
5435 counts[k] += count;
5436 }
5437 for k in 0..n {
5438 if counts[k] > 0 {
5439 centres[k] = sums[k] / f64::from(counts[k]);
5440 }
5441 }
5442 }
5443 let mut colors: Vec<u16> = centres
5444 .iter()
5445 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
5446 .collect();
5447 colors.sort_unstable();
5448 colors.dedup();
5449 if colors.len() >= 2 {
5450 out.push(exact(&colors));
5451 }
5452 }
5453 out
5454}
5455
5456#[allow(clippy::too_many_arguments)]
5457// ---------------------------------------------------------------------------
5458// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
5459// validity). A key frame that detected screen content and finds enough exact
5460// repeats in its own source sets `allow_intrabc`, which the spec forces every
5461// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
5462// its place when the copied blocks pay back the deblock/CDEF/LR the frame
5463// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
5464// ---------------------------------------------------------------------------
5465
5466/// Whether intra block copy is offered at all. **Off by default** --
5467/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
5468/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
5469/// but on the gate's real screen capture it MEASURED WORSE: setting
5470/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
5471/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
5472/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
5473/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
5474/// that detected no screen content.
5475fn intrabc_enabled() -> bool {
5476 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
5477 return forced;
5478 }
5479 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5480 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
5481}
5482
5483thread_local! {
5484 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
5485 /// probe runs both arms in one process, and the suite is one process, so
5486 /// an environment variable cannot separate them (same reason
5487 /// [`SCREEN_FORCE`] exists).
5488 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
5489}
5490
5491#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5492pub(crate) fn force_intrabc(value: Option<bool>) {
5493 INTRABC_FORCE.with(|c| c.set(value));
5494}
5495
5496/// How many of a screen frame's 16x16 blocks must have an exact repeat
5497/// somewhere else in the source before `allow_intrabc` is worth the in-loop
5498/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
5499/// constant class: `probe_intrabc_threshold` measures the arm at several
5500/// values.
5501fn intrabc_pct() -> usize {
5502 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5503 *N.get_or_init(|| {
5504 std::env::var("EC_AV1_INTRABC_PCT")
5505 .ok()
5506 .and_then(|v| v.parse().ok())
5507 .unwrap_or(10)
5508 })
5509}
5510
5511/// The pixel grid intrabc source positions are hashed on
5512/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
5513/// which keeps the block-hash table (and so the search) linear in the frame
5514/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
5515/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
5516/// bilinear interpolation decode.rs applies but this encoder does not.
5517fn intrabc_step() -> usize {
5518 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5519 *N.get_or_init(|| {
5520 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
5521 .ok()
5522 .and_then(|v| v.parse().ok())
5523 .unwrap_or(4);
5524 if n % 2 == 0 { n.max(2) } else { 4 }
5525 })
5526}
5527
5528/// The side of the luma square the block-hash table is keyed on.
5529const IBC_HASH: usize = 16;
5530
5531/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
5532/// the current one the source's bottom-right corner must already be. Under
5533/// 128 superblocks the same 256 pixels are two superblocks, which
5534/// [`Ibc::dv_valid`] derives from the size itself.
5535const INTRABC_DELAY_SB64: i32 = 4;
5536
5537/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
5538fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
5539 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
5540 for row in 0..IBC_HASH {
5541 let base = (y + row) * width + x;
5542 for &v in &plane[base..base + IBC_HASH] {
5543 h ^= u64::from(v);
5544 h = h.wrapping_mul(0x100_0000_01b3);
5545 }
5546 }
5547 h
5548}
5549
5550/// Every `intrabc_step()`-aligned position of `plane` inside
5551/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
5552fn ibc_index(
5553 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
5554 plane: &[u8],
5555 width: usize,
5556 (x0, y0): (usize, usize),
5557 (x1, y1): (usize, usize),
5558) {
5559 let step = intrabc_step();
5560 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
5561 return;
5562 }
5563 let mut y = y0.next_multiple_of(step);
5564 while y + IBC_HASH <= y1 {
5565 let mut x = x0.next_multiple_of(step);
5566 while x + IBC_HASH <= x1 {
5567 table
5568 .entry(ibc_hash(plane, width, x, y))
5569 .or_default()
5570 .push((x as u32, y as u32));
5571 x += step;
5572 }
5573 y += step;
5574 }
5575}
5576
5577/// Whether `screen`-detected source `y` repeats itself enough to be worth
5578/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
5579/// content appears at some other position, against [`intrabc_pct`]. Returns
5580/// the share as well, for the gate's own print.
5581fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
5582 if true_width < 4 * 64 || true_height < 2 * 64 {
5583 return (false, 0.0);
5584 }
5585 let mut table = std::collections::HashMap::new();
5586 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
5587 let (mut total, mut matched) = (0usize, 0usize);
5588 let mut by = 0;
5589 while by + IBC_HASH <= true_height {
5590 let mut bx = 0;
5591 while bx + IBC_HASH <= true_width {
5592 total += 1;
5593 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
5594 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
5595 matched += 1;
5596 }
5597 }
5598 bx += IBC_HASH;
5599 }
5600 by += IBC_HASH;
5601 }
5602 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
5603 (share * 100.0 >= intrabc_pct() as f64, share)
5604}
5605
5606/// One tile's intrabc search state: a block-hash table over the part of the
5607/// tile's own reconstruction that is already final (whole superblock rows --
5608/// the in-loop filters are off on this frame, so a coded superblock row never
5609/// changes again), plus the last DV chosen, which the RD price uses as its
5610/// predictor estimate.
5611struct Ibc {
5612 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
5613 /// source repeats exactly where a lossily coded reconstruction only
5614 /// nearly does, so an exact-match table over the reconstruction finds
5615 /// almost nothing. The candidate is then SCORED against the
5616 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
5617 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
5618 /// The tile's own luma rect, in samples.
5619 tile: (usize, usize, usize, usize),
5620 /// The DV the previous intrabc block of this tile took -- the *estimate*
5621 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
5622 /// against. The writer computes the true predictor off its own mi grid
5623 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
5624 /// a slightly mispriced candidate, never a wrong bitstream.
5625 last_dv: Option<(i32, i32)>,
5626 /// How many blocks took intrabc, and how many hash lookups found at least
5627 /// one valid candidate -- the gate's own fire counts.
5628 hits: usize,
5629 lookups: usize,
5630 found: usize,
5631}
5632
5633impl Ibc {
5634 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
5635 let mut table = std::collections::HashMap::new();
5636 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
5637 Self {
5638 table,
5639 tile,
5640 last_dv: None,
5641 hits: 0,
5642 lookups: 0,
5643 found: 0,
5644 }
5645 }
5646
5647 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
5648 /// (1/8 pel), with this lane's own extra restriction on top: the source
5649 /// must lie entirely in a COMPLETED superblock row, which is exactly the
5650 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
5651 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
5652 /// wavefront's own diagonal) are legal and not searched; the upgrade path
5653 /// is to index the current row's finished superblocks too.
5654 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
5655 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
5656 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
5657 return false;
5658 }
5659 let (tx0, ty0, tx1, ty1) = (
5660 self.tile.0 as i32,
5661 self.tile.1 as i32,
5662 self.tile.2 as i32,
5663 self.tile.3 as i32,
5664 );
5665 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
5666 let (w, h) = (w as i32, h as i32);
5667 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
5668 return false;
5669 }
5670 // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
5671 // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
5672 // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
5673 // Counting 64s under a 128 superblock let the search take a source
5674 // from a 64 row the 128 visit order had not reconstructed yet.
5675 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
5676 let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 };
5677 let active_sb_row = (y as i32 - ty0) >> sb_log2;
5678 let active_sb_col = (x as i32 - tx0) >> sb_log2;
5679 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
5680 let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
5681 // This lane's own restriction (see the doc comment).
5682 if src_sb_row >= active_sb_row {
5683 return false;
5684 }
5685 let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
5686 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
5687 return false;
5688 }
5689 // libaom's wavefront: only the top-left cone of the frame is legal.
5690 let wf = (1 + delay) * (active_sb_row - src_sb_row);
5691 src_sb_col < active_sb_col - delay + wf
5692 }
5693}
5694
5695/// How many block searches ran, how many found at least one VALID candidate,
5696/// and how many won on rate-distortion -- the hash hit rate a gate prints
5697/// (class `gate-blind-to-feature`: "the search ran" and "the search found
5698/// something" and "the block took it" are three different claims).
5699static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
5700 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
5701
5702impl Drop for Ibc {
5703 fn drop(&mut self) {
5704 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
5705 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
5706 }
5707 }
5708}
5709
5710/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
5711/// its own encode.
5712#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5713pub(crate) fn take_intrabc_search() -> [usize; 3] {
5714 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5715}
5716
5717/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
5718/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
5719/// infers rather than codes.
5720fn dv_component_bits(diff: i32) -> f64 {
5721 let z = diff.unsigned_abs() as i32 - 1;
5722 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
5723 let class = mv_class_of(z);
5724 bits += symbol_bits(&cdf::MV_CLASS, class);
5725 let local = z - mv_class_base(class);
5726 if class == 0 {
5727 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
5728 } else {
5729 let d = local >> 3;
5730 for i in 0..class {
5731 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
5732 }
5733 }
5734 bits
5735}
5736
5737/// What one block vector costs against `pred`, plus the `skip` and
5738/// `use_intrabc` flags the block carries and the ordinary intra block does
5739/// not pay in this currency.
5740fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
5741 let diff = (dv.0 - pred.0, dv.1 - pred.1);
5742 let joint = match (diff.0 != 0, diff.1 != 0) {
5743 (false, false) => 0,
5744 (false, true) => 1,
5745 (true, false) => 2,
5746 (true, true) => 3,
5747 };
5748 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
5749 if diff.0 != 0 {
5750 bits += dv_component_bits(diff.0);
5751 }
5752 if diff.1 != 0 {
5753 bits += dv_component_bits(diff.1);
5754 }
5755 bits
5756}
5757
5758/// The squared error of copying the `side`-square block at `(sx, sy)` of each
5759/// plane's reconstruction onto the source block at `(x, y)`, luma and both
5760/// chroma planes together -- what an intrabc block's whole (residual-free)
5761/// distortion is.
5762fn ibc_sse(
5763 luma: &Plane,
5764 chroma: &[Plane; 2],
5765 (x, y): (usize, usize),
5766 (sx, sy): (usize, usize),
5767 side: usize,
5768) -> f64 {
5769 // Inside the true frame only, for the reason [`Plane::block_sse`] is
5770 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
5771 // how well it copies the padding.
5772 let mut sse = 0.0f64;
5773 let clip = |whole: usize, inside: usize| match edge_sse() {
5774 true => whole.min(inside),
5775 false => whole,
5776 };
5777 let rows = clip(side, luma.true_height.saturating_sub(y));
5778 let cols = clip(side, luma.true_width.saturating_sub(x));
5779 for row in 0..rows {
5780 let src = &luma.source[(y + row) * luma.width + x..][..cols];
5781 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
5782 for (&s, &r) in src.iter().zip(rec) {
5783 let d = f64::from(i32::from(s) - i32::from(r));
5784 sse += d * d;
5785 }
5786 }
5787 let half = side / 2;
5788 for plane in chroma {
5789 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
5790 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
5791 for row in 0..rows {
5792 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
5793 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
5794 for (&s, &r) in src.iter().zip(rec) {
5795 let d = f64::from(i32::from(s) - i32::from(r));
5796 sse += d * d;
5797 }
5798 }
5799 }
5800 sse
5801}
5802
5803/// Copies the `side`-square block at `(sx, sy)` of each plane's
5804/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
5805/// since it carries no residual (`skip`). Full-pel in both planes by
5806/// construction ([`intrabc_step`] keeps every DV even), which is what makes
5807/// this a plain copy where decode.rs runs the bilinear kernel over the same
5808/// samples.
5809fn ibc_commit(
5810 luma: &mut Plane,
5811 chroma: &mut [Plane; 2],
5812 (x, y): (usize, usize),
5813 (sx, sy): (usize, usize),
5814 side: usize,
5815) {
5816 for row in 0..side {
5817 let from = (sy + row) * luma.width + sx;
5818 let to = (y + row) * luma.width + x;
5819 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
5820 luma.reconstruction[to..to + side].copy_from_slice(&copied);
5821 }
5822 let half = side / 2;
5823 for plane in chroma {
5824 for row in 0..half {
5825 let from = (sy / 2 + row) * plane.width + sx / 2;
5826 let to = (y / 2 + row) * plane.width + x / 2;
5827 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
5828 plane.reconstruction[to..to + half].copy_from_slice(&copied);
5829 }
5830 plane.commit_ctx_zero(x / 2, y / 2, half);
5831 }
5832 luma.commit_ctx_zero(x, y, side);
5833}
5834
5835/// Searches this block's own DV: every hash-table position whose 16x16 luma
5836/// square equals the block's source square, plus the previous block's DV as a
5837/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
5838/// the winning `(dv, cost)`, or `None` when nothing valid was found.
5839fn ibc_search(
5840 ibc: &mut Ibc,
5841 luma: &Plane,
5842 chroma: &[Plane; 2],
5843 (x, y): (usize, usize),
5844 side: usize,
5845 lambda: f64,
5846) -> Option<((i32, i32), f64, (usize, usize))> {
5847 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
5848 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
5849 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
5850 let dv = (
5851 (sy as i32 - y as i32) * 8,
5852 (sx as i32 - x as i32) * 8,
5853 );
5854 if !ibc.dv_valid(x, y, side, side, dv) {
5855 return;
5856 }
5857 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
5858 if best.as_ref().is_none_or(|b| cost < b.1) {
5859 *best = Some((dv, cost, (sx, sy)));
5860 }
5861 };
5862 ibc.lookups += 1;
5863 let key = ibc_hash(luma.source, luma.width, x, y);
5864 // The table is filled in raster order, so the entries BEFORE this block's
5865 // own position are exactly the already-coded ones -- and the nearest of
5866 // them costs the fewest DV bits. Walking backwards from the block's own
5867 // slot is what makes the search look up-and-left; taking the newest
5868 // entries outright only ever finds candidates below and to the right,
5869 // every one of which `dv_valid` rejects.
5870 let hits: Vec<(u32, u32)> = ibc
5871 .table
5872 .get(&key)
5873 .map(|h| {
5874 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
5875 h[..end].iter().rev().take(32).copied().collect()
5876 })
5877 .unwrap_or_default();
5878 for (hx, hy) in hits {
5879 consider(&*ibc, hx as usize, hy as usize, &mut best);
5880 }
5881 if let Some(dv) = ibc.last_dv {
5882 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
5883 if sx >= 0 && sy >= 0 {
5884 consider(&*ibc, sx as usize, sy as usize, &mut best);
5885 }
5886 }
5887 if best.is_some() {
5888 ibc.found += 1;
5889 }
5890 best
5891}
5892
5893fn code_square(
5894 luma: &mut Plane,
5895 chroma: &mut [Plane; 2],
5896 (x, y): (usize, usize),
5897 side: usize,
5898 search: &Search,
5899 mode_bits: &[f64; 13],
5900 // The frame header's `tx_mode == TxMode::Select`: the block then searches
5901 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
5902 // transform over its whole side.
5903 tx_select: bool,
5904 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
5905 // header did not set `allow_intrabc`.
5906 ibc: Option<&mut Ibc>,
5907 // Whether this is a KEY frame's block, read only by the split census
5908 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
5909 // which is this lane's whole finding.
5910 census_key: bool,
5911 fctx: &crate::decode::FrameCtx,
5912) -> (BlockCoeffs, f64) {
5913 let (luma_set, chroma_set) = if side == SUPERBLOCK {
5914 // A whole superblock coded as ONE intra block (lane-i64): one
5915 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
5916 // `code_from_prediction` hands back, and one TX_32X32 per chroma
5917 // plane -- the same three sets the key frame writer's
5918 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
5919 // uses (`search_skip_64`).
5920 (TxbSet::Luma64, TxbSet::Chroma32)
5921 } else if side == BLOCK {
5922 (TxbSet::Luma32, TxbSet::Chroma16)
5923 } else if side == 8 {
5924 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
5925 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
5926 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
5927 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
5928 // (this branch is still unreached), so leaving `Chroma8` here would
5929 // silently wire the wrong table the moment one does; `Chroma4` is
5930 // what a real caller needs.
5931 (TxbSet::Luma8, TxbSet::Chroma4)
5932 } else {
5933 (TxbSet::Luma16, TxbSet::Chroma8)
5934 };
5935 let at = At {
5936 x,
5937 y,
5938 side,
5939 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
5940 set: luma_set_for(luma_set, search.screen),
5941 };
5942 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
5943 luma.search_block(at, search, mode_bits, fctx);
5944 let mut luma_tx_types = vec![tx_type];
5945 // The depth search runs on the mode the whole-block transform picked --
5946 // libaom's own ordering, and the reason it costs one extra pass per depth
5947 // rather than one per (mode, depth) pair.
5948 let mut tx_depth = 0u8;
5949 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
5950 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
5951 // pays that zero exactly as a 32x32's depth search makes it pay
5952 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
5953 // below hands the root a symbol for free.
5954 if tx_select && side == SUPERBLOCK {
5955 cost += search.lambda * tx_depth_bits(side, 0);
5956 }
5957 if tx_select && max_tx_depth(side) > 0 {
5958 let mut best = (
5959 cost + search.lambda * tx_depth_bits(side, 0),
5960 0usize,
5961 luma.snapshot(x, y, side),
5962 luma_coeffs,
5963 );
5964 let mut best_types = std::mem::take(&mut luma_tx_types);
5965 // The census wants the flat arm's own (rate, distortion), which
5966 // `search_block` only hands back folded into one cost -- so under the
5967 // env flag alone it is re-coded at depth 0 and the plane restored.
5968 let census_flat = split_census_on().then(|| {
5969 let kept = luma.snapshot(x, y, side);
5970 let (_, sse, bits, _) =
5971 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
5972 luma.restore(x, y, side, &kept);
5973 (bits + tx_depth_bits(side, 0), sse)
5974 });
5975 let mut census_split: Option<(f64, f64)> = None;
5976 for depth in 1..=max_tx_depth(side) {
5977 let (levels, sse, bits, types) =
5978 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
5979 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
5980 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
5981 if census_flat.is_some() {
5982 let c = (bits + tx_depth_bits(side, depth), sse);
5983 if census_split.is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
5984 {
5985 census_split = Some(c);
5986 }
5987 }
5988 if cost_d < best.0 {
5989 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
5990 best_types = types;
5991 }
5992 }
5993 if let (Some(flat), Some(split)) = (census_flat, census_split) {
5994 split_census(0, census_key, side, best.1 > 0, split, flat);
5995 }
5996 luma_tx_types = best_types;
5997 luma.restore(x, y, side, &best.2);
5998 cost = best.0;
5999 tx_depth = best.1 as u8;
6000 luma_coeffs = best.3;
6001 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6002 }
6003 // The palette candidate is priced against the mode the luma search (and
6004 // its transform-depth search) already settled on, so a block only takes
6005 // one when it beats the best ordinary intra coding of the same pixels.
6006 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
6007 // prediction is the colour map, not the DC of its neighbours.
6008 let mut mode = mode;
6009 let mut angle_delta = angle_delta;
6010 let mut palette = None;
6011 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6012 let source: Vec<u8> = (y..y + side)
6013 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
6014 .collect();
6015 let kept = luma.snapshot(x, y, side);
6016 // spec 5.11.50: a block cut by the frame's right/bottom edge codes
6017 // its map over the ON-SCREEN corner only and the decoder replicates
6018 // that outward, so the searched map is folded the same way here --
6019 // the prediction priced, the reconstruction committed and the symbols
6020 // `write_color_index_map` writes are then one and the same map
6021 // (lane-palw).
6022 let on = (
6023 side.min(luma.true_width.saturating_sub(x)),
6024 side.min(luma.true_height.saturating_sub(y)),
6025 );
6026 for mut pal in palette_candidates(&source) {
6027 let n = usize::from(pal.size);
6028 crate::decode::palette_replicate(&mut pal.map, side, side, on);
6029 let prediction: Vec<u8> = pal
6030 .map
6031 .iter()
6032 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
6033 .collect();
6034 let trial = luma.code_from_prediction(
6035 x,
6036 y,
6037 side,
6038 &prediction,
6039 false,
6040 search.base_q_idx,
6041 search.deadzone,
6042 luma_set,
6043 );
6044 let cost_p = trial.sse
6045 + search.lambda
6046 * (trial.bits
6047 + mode_bits[DC_PRED as usize]
6048 + crate::tile::palette_bits(&pal, side, on)
6049 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
6050 if cost_p < cost {
6051 cost = cost_p;
6052 mode = DC_PRED as u8;
6053 angle_delta = 0;
6054 tx_depth = 0;
6055 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
6056 luma.commit(x, y, side, &trial);
6057 palette = Some(pal);
6058 }
6059 }
6060 if palette.is_none() {
6061 luma.restore(x, y, side, &kept);
6062 }
6063 }
6064
6065 // The five recursive filter-intra modes (spec 5.11.14), priced against
6066 // whatever the mode, transform-depth and palette searches settled on --
6067 // the same "one candidate loop after the incumbent is known" shape the
6068 // palette above uses. A block that takes one is `DC_PRED` with no palette
6069 // by construction (`av1_filter_intra_allowed`), and its luma transform
6070 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
6071 //
6072 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
6073 // depth the ordinary intra search runs, each unit predicting recursively
6074 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
6075 // arm), so a block whose ordinary winner wanted a split transform is
6076 // compared against a filter arm that may split too.
6077 //
6078 // Measured (native BD table, lane-fitu): searching the depths on EVERY
6079 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
6080 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
6081 // locally cheaper reconstruction that the film rows go on to predict from
6082 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
6083 // content is where it pays, and a non-screen frame keeps the depth-0-only
6084 // arm, byte for byte.
6085 let mut filter_intra: Option<u8> = None;
6086 if filter_intra_on()
6087 && palette.is_none()
6088 && let Some(class) = crate::decode::filter_intra_size_class(side)
6089 {
6090 let row = &cdf::FILTER_INTRA[class];
6091 // With the sequence bit on, EVERY `DC_PRED` block without a luma
6092 // palette carries the flag, so the incumbent pays its zero before the
6093 // comparison -- otherwise the candidate is charged a bit the block
6094 // spends either way (class `price-the-narrowing-not-the-table`).
6095 if mode == DC_PRED {
6096 cost += search.lambda * symbol_bits(row, 0);
6097 }
6098 let one_bits = symbol_bits(row, 1);
6099 let kept = luma.snapshot(x, y, side);
6100 let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 };
6101 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
6102 for fi in 0..5u8 {
6103 for depth in 0..=max_depth {
6104 // A filter-intra block's units are coded through
6105 // `code_from_prediction`, which is `DCT_DCT` throughout, so
6106 // this arm keeps the empty (all-`DCT_DCT`) type list.
6107 let (levels, sse, bits, _) =
6108 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
6109 let cost_f = sse
6110 + search.lambda
6111 * (bits
6112 + mode_bits[DC_PRED as usize]
6113 + one_bits
6114 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
6115 + if tx_select { tx_depth_bits(side, depth) } else { 0.0 });
6116 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
6117 best = Some((
6118 cost_f,
6119 fi,
6120 depth,
6121 luma.snapshot(x, y, side),
6122 coeffs(&levels, side),
6123 ));
6124 }
6125 }
6126 }
6127 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
6128 cost = cost_f;
6129 mode = DC_PRED;
6130 angle_delta = 0;
6131 tx_depth = depth as u8;
6132 luma_coeffs = levels;
6133 luma.restore(x, y, side, &snapshot);
6134 filter_intra = Some(fi);
6135 } else {
6136 luma.restore(x, y, side, &kept);
6137 }
6138 }
6139
6140 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
6141 // planes; what it costs still counts towards the partition decision.
6142 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
6143 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
6144 cost += chroma_cost;
6145
6146 // The intrabc arm is priced against the WHOLE block -- luma and both
6147 // chroma planes, residual-free -- so it is compared after the chroma
6148 // search has added its own cost, not against the luma decision alone.
6149 if let Some(ibc) = ibc {
6150 if let Some((dv, cost_ibc, src)) =
6151 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
6152 {
6153 if cost_ibc < cost {
6154 ibc_commit(luma, chroma, (x, y), src, side);
6155 ibc.last_dv = Some(dv);
6156 ibc.hits += 1;
6157 return (
6158 BlockCoeffs {
6159 skip: true,
6160 dv: Some(dv),
6161 ..BlockCoeffs::default()
6162 },
6163 cost_ibc,
6164 );
6165 }
6166 }
6167 }
6168 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
6169 // (its levels came from `code_from_prediction`), so the searched types
6170 // belong to a block this one no longer is.
6171 if palette.is_some() || filter_intra.is_some() {
6172 luma_tx_types = Vec::new();
6173 }
6174 (
6175 BlockCoeffs {
6176 u,
6177 v,
6178 luma: luma_coeffs,
6179 mode,
6180 uv_mode,
6181 tx_depth,
6182 palette,
6183 palette_uv,
6184 filter_intra,
6185 cfl_alphas,
6186 angle_delta_y: angle_delta as i8,
6187 luma_tx_types,
6188 ..BlockCoeffs::default()
6189 },
6190 cost,
6191 )
6192}
6193
6194/// The chroma modes the search offers, and the only ones it may offer: each
6195/// predicts from the row directly above and the column directly to the left
6196/// and nothing further, so none of them needs the above-right/below-left
6197/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
6198/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
6199/// reconstruction and its own alpha syntax; both are left out here.
6200const CHROMA_MODES: [u8; 7] = [
6201 DC_PRED,
6202 V_PRED,
6203 H_PRED,
6204 SMOOTH_PRED,
6205 SMOOTH_V_PRED,
6206 SMOOTH_H_PRED,
6207 PAETH_PRED,
6208];
6209
6210/// The thirteen intra mode names, for the chroma fire count's print.
6211#[cfg(test)]
6212const UV_MODE_NAMES: [&str; 14] = [
6213 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
6214 "SMOOTH_H", "PAETH", "CFL",
6215];
6216
6217/// How many blocks each chroma mode has won, indexed by the mode itself --
6218/// the fire count that says whether the search below reaches its candidates
6219/// at all (the `gate-blind-to-feature` class), printed once per gate run.
6220static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
6221 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
6222
6223/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
6224/// won, summed over both chroma planes -- the alpha histogram the gate prints
6225/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
6226/// magnitude only is a search that never left its first candidate).
6227static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
6228 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
6229
6230/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
6231/// zero on a CfL block", `1..=16` the magnitudes.
6232#[cfg(test)]
6233pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
6234 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6235}
6236
6237/// How many directional luma blocks won at each `angle_delta_y`, indexed
6238/// `delta + 3` -- the histogram that says whether the refinement below ever
6239/// leaves zero (`gate-blind-to-feature`).
6240static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
6241 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
6242
6243/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
6244#[cfg(test)]
6245pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
6246 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
6247}
6248
6249/// Whether the luma search refines a directional winner's `angle_delta_y`
6250/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
6251fn angle_delta_on() -> bool {
6252 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6253 crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")
6254 });
6255 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
6256}
6257
6258/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
6259/// switches it off, which is how the lane measured its own on/off pair).
6260fn cfl_on() -> bool {
6261 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6262 crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0")
6263 });
6264 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
6265}
6266
6267/// Whether the intra search offers the five recursive filter-intra modes at
6268/// all, and with them whether the sequence header sets `enable_filter_intra`
6269/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
6270/// its own on/off pair -- and how every byte pin written before it still
6271/// reproduces). It is also a speed lever: on at preset 0, off above it.
6272// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
6273// it off for the whole process (a sequence-header field, so it cannot change
6274// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
6275// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
6276// this workspace.
6277
6278/// Whether a sequence codes 128x128 superblocks when the environment says
6279/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
6280/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
6281/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
6282/// 128x128 block in it every row of the native BD gate is down or flat on
6283/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
6284///
6285/// | row | 64 superblocks | 128 + the 128 root |
6286/// |---|---|---|
6287/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
6288/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
6289/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
6290/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
6291/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
6292///
6293/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
6294/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
6295///
6296/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
6297/// off (the delta_q unit at the 128 superblock, the superblock size travelling
6298/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
6299/// predictor and wavefront, and seven test harnesses that handed the encoder a
6300/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
6301pub(crate) const SB128_DEFAULT: bool = true;
6302
6303/// Whether this process's sequences code 128x128 superblocks. An ENCODER
6304/// knob (like `speed::SPEED`), never read by a decode: read through a
6305/// process-global (not a thread-local) because the tile writers run on
6306/// worker threads; `2` is "the environment has not been read yet".
6307static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
6308
6309/// Whether this process's sequences code 128x128 superblocks.
6310pub(crate) fn sb128_on() -> bool {
6311 use std::sync::atomic::Ordering::Relaxed;
6312 match ENC_SB128.load(Relaxed) {
6313 2 => {
6314 let on = crate::envflags::var("EC_AV1_SB128")
6315 .ok()
6316 .map_or(SB128_DEFAULT, |v| v != "0");
6317 ENC_SB128.store(u8::from(on), Relaxed);
6318 on
6319 }
6320 v => v == 1,
6321 }
6322}
6323
6324/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
6325/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
6326/// exactly like the speed-preset gates.
6327#[cfg(test)]
6328pub(crate) fn force_sb128(on: bool) {
6329 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
6330}
6331
6332/// The luma loop-restoration unit size this sequence codes: a 128 superblock
6333/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
6334/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
6335/// 128), which is the one filter parameter the superblock size moves.
6336pub(crate) fn lr_unit() -> u32 {
6337 if sb128_on() { 128 } else { 64 }
6338}
6339
6340pub(crate) fn filter_intra_on() -> bool {
6341 #[cfg(test)]
6342 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
6343 return forced;
6344 }
6345 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6346 crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0")
6347 });
6348 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
6349}
6350
6351/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
6352/// to its own encode.
6353#[cfg(test)]
6354pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
6355 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6356}
6357
6358/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
6359/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
6360/// Returns each plane's levels, the mode, and what the pair cost (squared
6361/// error plus lambda times bits, the same currency the luma search speaks).
6362///
6363/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
6364/// which is what the luma mode decision was taken against, so what a
6365/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
6366/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
6367/// writer then has to code.
6368#[allow(clippy::too_many_arguments)]
6369/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
6370/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
6371/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
6372/// trials all seven, as before this lever.
6373///
6374/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
6375/// the search's largest trial population by far -- seven modes times two
6376/// planes for every intra block, against 3.7 luma trials -- and the RD
6377/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
6378/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
6379fn chroma_top_k() -> Option<usize> {
6380 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
6381 crate::envflags::var("EC_AV1_CHROMA_K")
6382 .ok()
6383 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
6384 });
6385 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
6386}
6387
6388/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
6389/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
6390/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
6391/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
6392/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
6393/// BD swings by about a point in either direction as near-tie chroma modes
6394/// flip, which is the measurement's own sensitivity, not a trend: nothing
6395/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
6396/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
6397/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
6398/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
6399pub(crate) const CHROMA_TOP_K: Option<usize> = None;
6400
6401fn search_chroma(
6402 chroma: &mut [Plane; 2],
6403 // The luma plane's RECONSTRUCTION under this block, already committed by
6404 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
6405 luma: &Plane,
6406 (x, y): (usize, usize),
6407 side: usize,
6408 set: TxbSet,
6409 search: &Search,
6410 luma_mode: u8,
6411 fctx: &crate::decode::FrameCtx,
6412) -> (
6413 [Vec<Coeff>; 2],
6414 u8,
6415 f64,
6416 Option<crate::tile::PaletteUv>,
6417 Option<(i32, i32)>,
6418) {
6419 let at = At {
6420 x: x / 2,
6421 y: y / 2,
6422 side: side / 2,
6423 reach: Reach::none(),
6424 set,
6425 };
6426 // The census's cheap proxy for a chroma mode: the SAD of its prediction
6427 // summed over both planes, ranked by the same rule the luma histogram
6428 // uses. Only built under `EC_AV1_CENSUS`.
6429 // The SAD of each mode's prediction, summed over both planes -- the
6430 // census's ranking rule, and what [`chroma_top_k`] prunes by.
6431 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
6432 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6433 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6434 u.iter()
6435 .zip(v.iter())
6436 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
6437 .collect()
6438 };
6439 let modes: Vec<u8> = match chroma_top_k() {
6440 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
6441 _ => CHROMA_MODES.to_vec(),
6442 };
6443 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
6444 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
6445 let ranking: Vec<(f64, u8)> = if census_on() {
6446 sad_scores(chroma)
6447 } else {
6448 Vec::new()
6449 };
6450 census_add(2, 1);
6451 census_add(3, modes.len());
6452 let mut best: Option<(f64, u8, Trial, Trial)> = None;
6453 for mode in modes {
6454 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
6455 if (V_PRED..=D67_PRED).contains(&mode) {
6456 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
6457 }
6458 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
6459 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
6460 // chroma of a 64x64 block is `DCT_DCT` whatever
6461 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
6462 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
6463 // points.
6464 let tx_type = if at.side >= 32 {
6465 TxType::DctDct
6466 } else {
6467 crate::decode::default_intra_tx_type(mode)
6468 };
6469 let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6470 let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6471 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
6472 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
6473 best = Some((cost, mode, u, v));
6474 }
6475 }
6476 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
6477 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
6478 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
6479 // what keeps `u_colors` ascending and distinct the way
6480 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
6481 // each cluster's own mean, since the colour-index map is SHARED by the
6482 // two planes. Priced against the best ordinary chroma mode above, so a
6483 // block only takes one when it beats it; a palette block's chroma mode is
6484 // `UV_DC_PRED` by construction.
6485 let mut palette_uv = None;
6486 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6487 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
6488 let plane_source = |p: &Plane| -> Vec<u8> {
6489 (at.y..at.y + at.side)
6490 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
6491 .collect()
6492 };
6493 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
6494 // The luma on-screen extent carried into this plane exactly as the
6495 // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
6496 let on_uv = crate::decode::palette_onscreen_uv(
6497 (side, side),
6498 (
6499 side.min(luma.true_width.saturating_sub(x)),
6500 side.min(luma.true_height.saturating_sub(y)),
6501 ),
6502 (at.side, at.side),
6503 );
6504 for mut pal in palette_candidates(&u_source) {
6505 let n = usize::from(pal.size);
6506 crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
6507 // V's base colour per cluster: the mean of the samples the shared
6508 // map assigns to it (an empty cluster cannot happen -- every
6509 // colour `palette_candidates` returns is some pixel's nearest).
6510 let mut sums = [0u32; 8];
6511 let mut counts = [0u32; 8];
6512 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
6513 let k = usize::from(i).min(n - 1);
6514 sums[k] += u32::from(sample);
6515 counts[k] += 1;
6516 }
6517 let mut v_colors = [0u16; 8];
6518 for k in 0..n {
6519 v_colors[k] = if counts[k] > 0 {
6520 ((sums[k] + counts[k] / 2) / counts[k]) as u16
6521 } else {
6522 0
6523 };
6524 }
6525 let candidate = crate::tile::PaletteUv {
6526 size: pal.size,
6527 u_colors: pal.colors,
6528 v_colors,
6529 map: pal.map,
6530 };
6531 let predict = |colors: &[u16; 8]| -> Vec<u8> {
6532 candidate
6533 .map
6534 .iter()
6535 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
6536 .collect()
6537 };
6538 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
6539 let u_trial = chroma[0].code_from_prediction(
6540 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
6541 );
6542 let v_trial = chroma[1].code_from_prediction(
6543 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
6544 );
6545 let cost_p = u_trial.sse
6546 + v_trial.sse
6547 + search.lambda
6548 * (u_trial.bits
6549 + v_trial.bits
6550 + crate::tile::palette_uv_bits(&candidate, side, on_uv));
6551 if cost_p < cost {
6552 cost = cost_p;
6553 mode = DC_PRED;
6554 u = u_trial;
6555 v = v_trial;
6556 palette_uv = Some(candidate);
6557 }
6558 }
6559 }
6560 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
6561 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
6562 // nudges every sample by `alpha_q3` times the block's subsampled,
6563 // average-subtracted luma reconstruction. Offered only where
6564 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
6565 // and priced against the best ordinary chroma mode above, palette
6566 // included, so a block only takes it when it beats both.
6567 let mut cfl_alphas = None;
6568 if side <= 32 && cfl_on() {
6569 // The AC signal, through the decoder's own
6570 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
6571 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
6572 i32::from(luma.reconstruction[ly * luma.width + lx])
6573 });
6574 let dc_prediction = |plane: &Plane| -> Vec<u8> {
6575 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
6576 let (above, left, corner) =
6577 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
6578 let mut prediction = vec![0u8; at.side * at.side];
6579 intra_predict_u8(
6580 DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
6581 fctx,
6582 );
6583 prediction
6584 };
6585 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
6586 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
6587 // add the residual -- which is what [`Plane::code_from_prediction`]
6588 // does with what this returns.
6589 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
6590 base.iter()
6591 .zip(ac.iter())
6592 .map(|(&b, &a)| {
6593 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
6594 })
6595 .collect()
6596 };
6597 // The least-squares alpha, then its two neighbours: minimising
6598 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
6599 // dot-product ratio, and the quantised optimum is one of the two
6600 // integers around it (the clamp and the Q6 rounding are what the SSE
6601 // check below re-decides). libaom sweeps all sixteen magnitudes under
6602 // full RD; three predictions per plane buy nearly the same alpha for a
6603 // thirtieth of the search.
6604 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
6605 let (mut num, mut den) = (0.0f64, 0.0f64);
6606 for row in 0..at.side {
6607 for col in 0..at.side {
6608 let i = row * at.side + col;
6609 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
6610 - f64::from(base[i]);
6611 num += d * f64::from(ac[i]);
6612 den += f64::from(ac[i]) * f64::from(ac[i]);
6613 }
6614 }
6615 if den == 0.0 {
6616 return 0;
6617 }
6618 let ideal = 64.0 * num / den;
6619 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
6620 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
6621 let alpha = alpha.clamp(-16, 16) as i32;
6622 if alpha == 0 {
6623 continue;
6624 }
6625 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
6626 if sse < best.0 {
6627 best = (sse, alpha);
6628 }
6629 }
6630 best.1
6631 };
6632 let picked = [
6633 pick_alpha(&chroma[0], &bases[0]),
6634 pick_alpha(&chroma[1], &bases[1]),
6635 ];
6636 if picked != [0, 0] {
6637 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
6638 let trial = |plane_idx: usize, alpha: i32| -> Trial {
6639 let prediction = if alpha == 0 {
6640 bases[plane_idx].clone()
6641 } else {
6642 apply(&bases[plane_idx], alpha)
6643 };
6644 chroma[plane_idx].code_from_prediction(
6645 at.x,
6646 at.y,
6647 at.side,
6648 &prediction,
6649 false,
6650 search.base_q_idx,
6651 search.deadzone,
6652 set,
6653 )
6654 };
6655 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
6656 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
6657 let combos: [(i32, i32); 3] = [
6658 (picked[0], picked[1]),
6659 (picked[0], 0),
6660 (0, picked[1]),
6661 ];
6662 for &(alpha_u, alpha_v) in &combos {
6663 if (alpha_u, alpha_v) == (0, 0) {
6664 continue;
6665 }
6666 let cu = trial(0, alpha_u);
6667 let cv = trial(1, alpha_v);
6668 let bits =
6669 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
6670 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
6671 if cost_cfl < cost {
6672 cost = cost_cfl;
6673 mode = crate::tile::UV_CFL_PRED as u8;
6674 u = cu;
6675 v = cv;
6676 palette_uv = None;
6677 cfl_alphas = Some((alpha_u, alpha_v));
6678 }
6679 }
6680 }
6681 }
6682 if let Some((alpha_u, alpha_v)) = cfl_alphas {
6683 for alpha in [alpha_u, alpha_v] {
6684 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
6685 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6686 }
6687 }
6688 if census_on() {
6689 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
6690 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6691 }
6692 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6693 chroma[0].commit(at.x, at.y, at.side, &u);
6694 chroma[1].commit(at.x, at.y, at.side, &v);
6695 (
6696 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
6697 mode,
6698 cost,
6699 palette_uv,
6700 cfl_alphas,
6701 )
6702}
6703
6704/// Codes one leaf of a straddling quadrant as whichever costs least of intra
6705/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
6706/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
6707/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
6708/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
6709/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
6710/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
6711/// attempted here: these leaves only ever fill the sliver of real content a
6712/// true edge lands in the middle of a larger block, not a leaf worth a full
6713/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
6714/// (see `write_inter_frame_leaf`'s doc comment).
6715#[allow(clippy::too_many_arguments)]
6716/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
6717/// as [`code_square_inter`] wants them: empty on a frame that codes no
6718/// `reference_select`, or when the leaf compound candidates are switched off.
6719/// One helper because THREE leaf call sites need it -- the split quadrants
6720/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
6721/// `&[]` and so coded no compound block anywhere along the frame's true edge.
6722#[allow(clippy::too_many_arguments)]
6723fn leaf_compound_stacks<'a>(
6724 grid: &MiGrid,
6725 mi_row: usize,
6726 mi_col: usize,
6727 bw4: usize,
6728 bh4: usize,
6729 mi_cols: usize,
6730 mi_rows: usize,
6731 reference_select: bool,
6732 golden: Option<&'a Picture>,
6733 altref: Option<&'a Picture>,
6734) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
6735 if !(reference_select && leaf_compound()) {
6736 return Vec::new();
6737 }
6738 [
6739 (crate::mvstack::GOLDEN_FRAME, golden),
6740 (crate::mvstack::ALTREF_FRAME, altref),
6741 ]
6742 .into_iter()
6743 .filter_map(|(r, pic)| {
6744 pic.map(|p| {
6745 (
6746 r,
6747 p,
6748 crate::mvstack::find_mv_stack_compound(
6749 grid, mi_row, mi_col, bw4, bh4,
6750 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6751 grid.sign_bias_table(), &[(0, 0); 7], None,
6752 ),
6753 )
6754 })
6755 })
6756 .collect()
6757}
6758
6759/// The OBMC prediction of one square single-reference block: this block's own
6760/// translation prediction (`mc::predict`) with every bordering above/left
6761/// neighbour blended into the overlap strips by the DECODER's own plan and
6762/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
6763/// the search prices is what a decoder reconstructs -- never a second
6764/// implementation of the blend. `None` when the block has no overlappable
6765/// neighbour at all (the writer would then code no `motion_mode` symbol) or
6766/// when the plan cannot be built (a neighbour naming a reference this encode
6767/// does not hold).
6768#[allow(clippy::too_many_arguments)]
6769fn obmc_prediction(
6770 grid: &MiGrid,
6771 (mi_row, mi_col): (usize, usize),
6772 (mi_rows, mi_cols): (usize, usize),
6773 (x, y): (usize, usize),
6774 side: usize,
6775 mv: (i32, i32),
6776 refs: &[Option<&Picture>; 8],
6777 // This block's OWN reference planes, luma then both chroma, each as
6778 // (samples, stride, true width, true height).
6779 ref_planes: [(&[u16], usize, usize, usize); 3],
6780 frame_width: usize,
6781 fctx: &crate::decode::FrameCtx,
6782) -> Option<[Vec<u8>; 3]> {
6783 let n4 = side / 4;
6784 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
6785 return None;
6786 }
6787 let refpix = crate::decode::RefPix::ready(*refs);
6788 let plan = crate::decode::obmc_plan(
6789 grid,
6790 &[],
6791 &[],
6792 mi_row,
6793 mi_col,
6794 n4,
6795 n4,
6796 mi_rows,
6797 mi_cols,
6798 side,
6799 side,
6800 side,
6801 side / 2,
6802 x,
6803 y,
6804 x / 2,
6805 y / 2,
6806 &refpix,
6807 Some(fctx.interp_filter.get()),
6808 frame_width,
6809 )
6810 .ok()?;
6811 let mut pred = [
6812 vec![0u16; side * side],
6813 vec![0u16; side * side / 4],
6814 vec![0u16; side * side / 4],
6815 ];
6816 for (i, r) in ref_planes.into_iter().enumerate() {
6817 let luma_plane = i == 0;
6818 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
6819 let s = if luma_plane { side } else { side / 2 };
6820 mc::predict(
6821 r.0,
6822 r.1,
6823 r.2,
6824 r.3,
6825 mv_to_q4(px, mv.1, luma_plane),
6826 mv_to_q4(py, mv.0, luma_plane),
6827 s,
6828 s,
6829 &mut pred[i],
6830 fctx,
6831 );
6832 }
6833 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
6834 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
6835 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
6836 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
6837}
6838
6839fn code_square_inter(
6840 luma: &mut Plane,
6841 chroma: &mut [Plane; 2],
6842 (x, y): (usize, usize),
6843 side: usize,
6844 search: &Search,
6845 mode_bits: &[f64; 13],
6846 reference: &Picture,
6847 stack: &MvStack,
6848 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
6849 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
6850 // `reference_select`, and at the straddling call sites).
6851 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
6852 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
6853 // (`record_mi`, in the writer's own coding order) and this leaf's place in
6854 // it -- what the OBMC candidate's eligibility walk and neighbour plan
6855 // read, the same state the tile writer reads when it codes the leaf's
6856 // `motion_mode` symbol.
6857 grid: &MiGrid,
6858 (mi_row, mi_col): (usize, usize),
6859 (mi_rows, mi_cols): (usize, usize),
6860 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
6861 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
6862 refs: &[Option<&Picture>; 8],
6863 fctx: &crate::decode::FrameCtx,
6864) -> (BlockCoeffs, f64) {
6865 // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra
6866 // candidate at all -- `intra_cost` stays at infinity, so every
6867 // comparison below takes an inter candidate and the fallback arm at the
6868 // tail is unreachable. The planes hold what the caller snapshotted until
6869 // the winner commits: the intra trial used to commit here and be
6870 // overwritten by the inter commit, so skipping it changes no committed
6871 // sample, only work.
6872 let (intra_block, intra_cost) = if search.arf_leaf_intra {
6873 code_square(
6874 luma,
6875 chroma,
6876 (x, y),
6877 side,
6878 search,
6879 mode_bits,
6880 tx_select() && tx_select_inter(),
6881 None,
6882 false,
6883 fctx,
6884 )
6885 } else {
6886 arfmode_hit(0);
6887 (BlockCoeffs::default(), f64::INFINITY)
6888 };
6889 let luma_set = if side == 8 {
6890 TxbSet::Luma8Inter
6891 } else {
6892 TxbSet::Luma16Inter
6893 };
6894 let chroma_set = if side == 8 {
6895 TxbSet::Chroma4
6896 } else {
6897 TxbSet::Chroma8
6898 };
6899
6900 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
6901 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
6902 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
6903 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
6904 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
6905 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
6906
6907 let mv = stack.nearest_mv;
6908 let ref_luma = (
6909 &reference.y,
6910 reference.width,
6911 luma.true_width,
6912 luma.true_height,
6913 );
6914 let ref_u = (
6915 &reference.u,
6916 reference.width / 2,
6917 chroma[0].true_width,
6918 chroma[0].true_height,
6919 );
6920 let ref_v = (
6921 &reference.v,
6922 reference.width / 2,
6923 chroma[1].true_width,
6924 chroma[1].true_height,
6925 );
6926 let luma_trial = mc_trial(
6927 luma,
6928 x,
6929 y,
6930 side,
6931 mv,
6932 true,
6933 ref_luma.0,
6934 ref_luma.1,
6935 ref_luma.2,
6936 ref_luma.3,
6937 false,
6938 search.base_q_idx,
6939 search.deadzone,
6940 luma_set, fctx,
6941 );
6942 let u = mc_trial(
6943 &chroma[0],
6944 x / 2,
6945 y / 2,
6946 side / 2,
6947 mv,
6948 false,
6949 ref_u.0,
6950 ref_u.1,
6951 ref_u.2,
6952 ref_u.3,
6953 false,
6954 search.base_q_idx,
6955 search.deadzone,
6956 chroma_set, fctx,
6957 );
6958 let v = mc_trial(
6959 &chroma[1],
6960 x / 2,
6961 y / 2,
6962 side / 2,
6963 mv,
6964 false,
6965 ref_v.0,
6966 ref_v.1,
6967 ref_v.2,
6968 ref_v.3,
6969 false,
6970 search.base_q_idx,
6971 search.deadzone,
6972 chroma_set, fctx,
6973 );
6974 let skip = luma_trial.levels.iter().all(|&l| l == 0)
6975 && u.levels.iter().all(|&l| l == 0)
6976 && v.levels.iter().all(|&l| l == 0);
6977 let inter_cost = luma_trial.sse
6978 + u.sse
6979 + v.sse
6980 + search.lambda
6981 * (skip_bits(skip)
6982 + intra_inter_bits(true)
6983 + single_ref_bits
6984 + mode_bits_inter
6985 + if skip {
6986 0.0
6987 } else {
6988 luma_trial.bits + u.bits + v.bits
6989 });
6990
6991 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
6992 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
6993 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
6994 // scan's own coverage already reached as far) but a real gap at 4-mi
6995 // leaf geometry. r3 ported the extended scan and, while proving it a
6996 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
6997 // `mvstack.rs`), found and fixed a second bug the extended scan's
6998 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
6999 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
7000 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
7001 // regardless of whether it also casts a ref-frame-matching vote) --
7002 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
7003 // branches), which is what made 8-mi geometry a true no-op instead of
7004 // one that only held when every neighbour happened to be inter.
7005 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
7006 // only ever took the stack's NEARESTMV candidate or went intra, so a
7007 // 32x32 block splitting because its four quarters MOVE differently could
7008 // not code the movement it split for. Same candidate `search_inter_block`
7009 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
7010 // a vector the residual syntax can name -- at this leaf's own side.
7011 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
7012 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
7013 // re-price below can hand it back as the winner's own mode info.
7014 let nearest_info = InterInfo {
7015 ref1: None,
7016 mv1: (0, 0),
7017 ref_frame: crate::mvstack::LAST_FRAME,
7018 mode: InterMode::NearestMv,
7019 mv,
7020 ref_mv_idx: 0,
7021 };
7022 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
7023 // syntax, apart from its residual: the OBMC candidate re-prices the same
7024 // syntax against a different prediction, so both sides of that comparison
7025 // carry it.
7026 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
7027 // This leaf's own `NEWMV` vector, kept whether or not it won the
7028 // single-reference comparison: it seeds the compound half-new candidate
7029 // below, exactly as `search_inter_block` seeds its own from the searches
7030 // it already ran.
7031 let mut searched_new: Option<(i32, i32)> = None;
7032 // What that search cost, kept for the second reference's own early-out
7033 // below (`None` when this leaf ran no search at all).
7034 let mut searched_new_cost: Option<f64> = None;
7035 let source_block = luma.source_block(x, y, side);
7036 if leaf_new_mv() {
7037 let (seeds, seed_n) = mv_seeds(stack);
7038 let found = motion::search(
7039 ref_luma.0,
7040 ref_luma.1,
7041 ref_luma.2,
7042 ref_luma.3,
7043 &source_block,
7044 x,
7045 y,
7046 side,
7047 side,
7048 stack.pred_mv,
7049 &seeds[..seed_n],
7050 search.lambda, fctx,
7051 1,
7052 );
7053 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
7054 searched_new_cost = Some(found.cost);
7055 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
7056 if mv_residual.is_none() {
7057 // lane-newmv: a vector the writer cannot name never reaches RD.
7058 newmv_census_block(side, false, f64::INFINITY, best.0, new_mv, stack.nearest_mv, 0.0);
7059 }
7060 if let Some(mv_bits) = mv_residual {
7061 searched_new = Some(new_mv);
7062 // Same reuse as `search_inter_block`: a NEWMV equal to the
7063 // stack's NEARESTMV is the same three trials, already run above.
7064 let (luma_new, u_new, v_new) = if new_mv == mv {
7065 (luma_trial.clone(), u.clone(), v.clone())
7066 } else {
7067 (
7068 mc_trial(
7069 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
7070 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
7071 ),
7072 mc_trial(
7073 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
7074 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
7075 fctx,
7076 ),
7077 mc_trial(
7078 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
7079 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
7080 fctx,
7081 ),
7082 )
7083 };
7084 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
7085 && u_new.levels.iter().all(|&l| l == 0)
7086 && v_new.levels.iter().all(|&l| l == 0);
7087 let drl_bits = if stack.entries.len() > 1 {
7088 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
7089 } else {
7090 0.0
7091 };
7092 let cost_new = luma_new.sse
7093 + u_new.sse
7094 + v_new.sse
7095 + search.lambda
7096 * (skip_bits(skip_new)
7097 + intra_inter_bits(true)
7098 + single_ref_bits
7099 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7100 + drl_bits
7101 + mv_bits
7102 + mv_rate_surcharge(mv_bits)
7103 + if skip_new {
7104 0.0
7105 } else {
7106 luma_new.bits + u_new.bits + v_new.bits
7107 });
7108 newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits);
7109 if cost_new < best.0 {
7110 single_syntax = intra_inter_bits(true)
7111 + single_ref_bits
7112 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7113 + drl_bits
7114 + mv_bits;
7115 best = (
7116 cost_new,
7117 Some((
7118 luma_new,
7119 u_new,
7120 v_new,
7121 skip_new,
7122 InterInfo {
7123 ref1: None,
7124 mv1: (0, 0),
7125 ref_frame: crate::mvstack::LAST_FRAME,
7126 mode: InterMode::NewMv,
7127 mv: new_mv,
7128 ref_mv_idx: 0,
7129 },
7130 )),
7131 );
7132 }
7133 }
7134 }
7135
7136 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
7137 // `search_inter_block` prices for a whole 32x32 block:
7138 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
7139 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
7140 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
7141 // too. Priced with the same static-CDF approximation, plus the
7142 // compound-only syntax the writer emits.
7143 if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() {
7144 // lane-arfmode: arm 4 drops this leaf's compound set (counted once
7145 // per leaf, not once per pair); the single-reference candidates
7146 // above stay.
7147 arfmode_hit(2);
7148 }
7149 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound() && search.arf_leaf_compound) {
7150 let (ref1, g) = (*ref1, *g);
7151 // The whole `comp_mode` + reference-pair tree at the writer's own
7152 // contexts, for THIS pair (lane-ctx).
7153 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
7154 let mode_ctx =
7155 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7156 let mode_bits_of =
7157 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7158 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7159 (
7160 cstack.nearest_mv,
7161 mode_bits_of(0),
7162 InterInfo {
7163 ref_frame: crate::mvstack::LAST_FRAME,
7164 mode: InterMode::NearestNearestMv,
7165 mv: cstack.nearest_mv.0,
7166 mv1: cstack.nearest_mv.1,
7167 ref1: Some(ref1),
7168 ref_mv_idx: 0,
7169 },
7170 ),
7171 (
7172 ((0, 0), (0, 0)),
7173 mode_bits_of(6),
7174 InterInfo {
7175 ref_frame: crate::mvstack::LAST_FRAME,
7176 mode: InterMode::GlobalGlobalMv,
7177 mv: (0, 0),
7178 mv1: (0, 0),
7179 ref1: Some(ref1),
7180 ref_mv_idx: 0,
7181 },
7182 ),
7183 ];
7184 // Every compound MV residual here is priced against compound stack
7185 // entry 0, which is what `assign_compound_mv` predicts from at
7186 // `ref_mv_idx = 0` -- so it is also what the second-reference search
7187 // below seeds from and rounds to, and no candidate it finds can then
7188 // fail `mv_residual_bits`.
7189 let cbase = cstack
7190 .entries
7191 .first()
7192 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
7193 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
7194 // it a leaf could only name a stack vector for the second half, and
7195 // screen capture showed the consequence: every leaf compound block
7196 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
7197 // extra-reference `NEWMV`, when this reference's own
7198 // `NEAREST_NEARESTMV` vector already prices `margin` times better
7199 // than the `LAST` search of this same leaf did -- one candidate
7200 // evaluation standing in for a whole search.
7201 let margin = leaf_second_new_margin();
7202 let mut second_new: Option<(i32, i32)> = None;
7203 if leaf_second_new_mv() {
7204 newmv_census_global(2);
7205 let skip = margin > 0.0
7206 && searched_new_cost.is_some_and(|last| {
7207 motion::cost_at(
7208 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
7209 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
7210 ) * margin
7211 <= last
7212 });
7213 if skip {
7214 newmv_census_global(3);
7215 }
7216 if !skip {
7217 let mut seeds = [(0, 0); 4];
7218 let mut seed_n = 1;
7219 for e in cstack.entries.iter().take(3) {
7220 seeds[seed_n] = e.mv1;
7221 seed_n += 1;
7222 }
7223 let found = motion::search(
7224 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
7225 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
7226 );
7227 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
7228 }
7229 }
7230 if let Some(new_mv) = searched_new {
7231 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
7232 ccands.push((
7233 (new_mv, cstack.nearest_mv.1),
7234 mode_bits_of(3) + b0,
7235 InterInfo {
7236 ref_frame: crate::mvstack::LAST_FRAME,
7237 mode: InterMode::NewNearestMv,
7238 mv: new_mv,
7239 mv1: cstack.nearest_mv.1,
7240 ref1: Some(ref1),
7241 ref_mv_idx: 0,
7242 },
7243 ));
7244 }
7245 }
7246 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
7247 // searches this leaf ran, each residual priced against `cbase`.
7248 if let Some(mv1) = second_new {
7249 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
7250 ccands.push((
7251 (cstack.nearest_mv.0, mv1),
7252 mode_bits_of(2) + b1,
7253 InterInfo {
7254 ref_frame: crate::mvstack::LAST_FRAME,
7255 mode: InterMode::NearestNewMv,
7256 mv: cstack.nearest_mv.0,
7257 mv1,
7258 ref1: Some(ref1),
7259 ref_mv_idx: 0,
7260 },
7261 ));
7262 if let Some((new_mv, b0)) =
7263 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
7264 {
7265 ccands.push((
7266 (new_mv, mv1),
7267 mode_bits_of(7) + b0 + b1,
7268 InterInfo {
7269 ref_frame: crate::mvstack::LAST_FRAME,
7270 mode: InterMode::NewNewMv,
7271 mv: new_mv,
7272 mv1,
7273 ref1: Some(ref1),
7274 ref_mv_idx: 0,
7275 },
7276 ));
7277 }
7278 }
7279 }
7280 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
7281 ccands.dedup_by_key(|c| c.0);
7282 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
7283 let g_u = (
7284 g.u.as_slice(),
7285 g.width / 2,
7286 chroma[0].true_width,
7287 chroma[0].true_height,
7288 );
7289 let g_v = (
7290 g.v.as_slice(),
7291 g.width / 2,
7292 chroma[1].true_width,
7293 chroma[1].true_height,
7294 );
7295 for (mvs, bits, info) in ccands {
7296 let luma_c = mc_trial_compound(
7297 luma, x, y, side, mvs, true,
7298 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
7299 search.base_q_idx, search.deadzone, luma_set, fctx,
7300 );
7301 let u_c = mc_trial_compound(
7302 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
7303 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
7304 search.base_q_idx, search.deadzone, chroma_set, fctx,
7305 );
7306 let v_c = mc_trial_compound(
7307 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
7308 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
7309 search.base_q_idx, search.deadzone, chroma_set, fctx,
7310 );
7311 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
7312 && u_c.levels.iter().all(|&l| l == 0)
7313 && v_c.levels.iter().all(|&l| l == 0);
7314 let cost_c = luma_c.sse
7315 + u_c.sse
7316 + v_c.sse
7317 + search.lambda
7318 * (skip_bits(skip_c)
7319 + intra_inter_bits(true)
7320 + bits
7321 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
7322 if cost_c < best.0 {
7323 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
7324 }
7325 }
7326 }
7327
7328 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
7329 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
7330 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
7331 // the writer codes no symbol for one. The prediction is the decoder's own
7332 // plan and blend over the neighbours this leaf's `grid` already carries
7333 // (published by `record_mi` in the writer's coding order), so the
7334 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
7335 // offered this only at 32x32, which is not where libaom cashes its OBMC
7336 // gain.
7337 let mut motion_won = 0u8;
7338 let single = match &best.1 {
7339 None => Some(nearest_info),
7340 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
7341 Some(_) => None,
7342 };
7343 if let Some(info) = single.filter(|i| {
7344 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
7345 && i.ref_frame == crate::mvstack::LAST_FRAME
7346 }) {
7347 let planes = [
7348 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7349 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7350 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7351 ];
7352 // Which alphabet this block's writer will code the symbol against
7353 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
7354 // 3-symbol one only under `allow_warped_motion` and at least one warp
7355 // sample. Mirrored here so the candidates are priced against the
7356 // table the tile really narrows.
7357 let warp_alphabet = warp_on()
7358 && crate::decode::num_proj_ref(
7359 grid,
7360 mi_row,
7361 mi_col,
7362 side / 4,
7363 side / 4,
7364 mi_cols,
7365 mi_rows,
7366 info.ref_frame,
7367 fctx,
7368 ) >= 1;
7369 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
7370 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
7371 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
7372 if let Some(pred) = obmc_prediction(
7373 grid,
7374 (mi_row, mi_col),
7375 (mi_rows, mi_cols),
7376 (x, y),
7377 side,
7378 info.mv,
7379 refs,
7380 planes,
7381 reference.width,
7382 fctx,
7383 ) {
7384 candidates.push((1, pred));
7385 }
7386 }
7387 if warp_alphabet {
7388 if let Some(pred) = warp_prediction(
7389 grid,
7390 (mi_row, mi_col),
7391 (mi_rows, mi_cols),
7392 (x, y),
7393 side,
7394 info.mv,
7395 info.ref_frame,
7396 planes,
7397 fctx,
7398 ) {
7399 candidates.push((2, pred));
7400 }
7401 }
7402 for (motion, pred) in candidates {
7403 let luma_o = luma.code_from_prediction(
7404 x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
7405 );
7406 let u_o = chroma[0].code_from_prediction(
7407 x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
7408 chroma_set,
7409 );
7410 let v_o = chroma[1].code_from_prediction(
7411 x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
7412 chroma_set,
7413 );
7414 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
7415 && u_o.levels.iter().all(|&l| l == 0)
7416 && v_o.levels.iter().all(|&l| l == 0);
7417 let cost_o = luma_o.sse
7418 + u_o.sse
7419 + v_o.sse
7420 + search.lambda
7421 * (skip_bits(skip_o)
7422 + single_syntax
7423 + mm(motion)
7424 + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
7425 // The incumbent pays the motion_mode symbol IT would code, so
7426 // both sides of the comparison carry that syntax.
7427 if cost_o < best.0 + search.lambda * mm(motion_won) {
7428 motion_won = motion;
7429 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
7430 }
7431 }
7432 }
7433
7434 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
7435 if cost < intra_cost {
7436 // A compound winner commits the flat trial it was priced from:
7437 // `commit_inter_luma`'s var-tx trial set is single-reference
7438 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
7439 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
7440 // predicting each half-side trial from BOTH references, verified
7441 // byte-identical to this when its split is disabled) and MEASURED
7442 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
7443 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
7444 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
7445 // compound block's residual is small enough that the four extra
7446 // per-unit txb_skip/eob symbols cost more ladder bytes than this
7447 // encoder's static-CDF estimate prices them at, so the local RD
7448 // win does not convert. lane-av1txbits REBUILT it on top of a
7449 // search that prices against the tables the frame is really
7450 // written with (`tile::arm_pricing_cdfs`, the estimate error on
7451 // these very blocks measured down from +31% to +3%) and measured
7452 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
7453 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
7454 // same build without it. The static-CDF estimate was NOT what
7455 // held the compound var-tx trial back. The flat trial stays.
7456 // An OBMC winner commits the flat trial too: `commit_inter_luma`
7457 // re-predicts each var-tx unit by plain translation, which is not
7458 // the prediction this candidate was priced from.
7459 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
7460 // 0.05 (both rejections above were measured at 0.1, the weight
7461 // the lambda lane showed was 2x too heavy): a compound winner is
7462 // offered the same var-tx split, its units predicted from BOTH
7463 // references (`mc_trial_compound`). RE-MEASURED native: film
7464 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
7465 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
7466 // one row 0.2 down, two flat, short of the two-down-one-flat keep
7467 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
7468 // rather than change the default on a single 0.2 row. It fires:
7469 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
7470 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
7471 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
7472 // 1.3/1.2 down there, which is where the upgrade path is if this
7473 // is picked up again.
7474 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7475 refs[r as usize].map(|g| {
7476 (
7477 info.mv1,
7478 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
7479 )
7480 })
7481 });
7482 let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0
7483 || (info.ref1.is_some() && second.is_none())
7484 {
7485 luma.commit(x, y, side, &luma_new);
7486 (luma_new.levels.clone(), 0, 0.0, Vec::new())
7487 } else {
7488 commit_inter_luma(
7489 luma, (x, y), side, info.mv,
7490 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7491 search, &luma_new, skip_new, second, fctx,
7492 )
7493 };
7494 // lane-txrd: chroma follows the luma type the search just chose.
7495 let [u_new, v_new] = match luma_tx_types.first().copied() {
7496 Some(t) => recode_inter_chroma(
7497 chroma, (x, y), side, info.mv,
7498 [
7499 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7500 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7501 ],
7502 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7503 refs[r as usize].map(|g| {
7504 (
7505 info.mv1,
7506 [
7507 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
7508 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
7509 ],
7510 )
7511 })
7512 }),
7513 search, chroma_set, t, fctx,
7514 )
7515 .unwrap_or([u_new, v_new]),
7516 None => [u_new, v_new],
7517 };
7518 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
7519 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
7520 return (
7521 BlockCoeffs {
7522 angle_delta_y: 0,
7523 cfl_alphas: None,
7524 filter_intra: None,
7525 luma: coeffs(&levels, side),
7526 u: coeffs(&u_new.levels, side / 2),
7527 v: coeffs(&v_new.levels, side / 2),
7528 mode: DC_PRED as u8,
7529 uv_mode: DC_PRED,
7530 skip: skip_new,
7531 eight: None,
7532 dv: None,
7533 palette: None,
7534 palette_uv: None,
7535 tx_depth,
7536 luma_tx_types,
7537 inter: Some(info),
7538 motion_mode: motion_won,
7539 },
7540 cost + dcost,
7541 );
7542 }
7543 }
7544
7545 census_add(8, 1);
7546 if skip {
7547 census_add(10, 1);
7548 }
7549 if inter_cost >= intra_cost {
7550 census_add(9, 1);
7551 }
7552 if inter_cost < intra_cost {
7553 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
7554 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,
7555 );
7556 // lane-txrd: chroma follows the luma type (this tail's block is
7557 // single-reference `NEARESTMV`, so no compound second half).
7558 let [u, v] = match luma_tx_types.first().copied() {
7559 Some(t) => recode_inter_chroma(
7560 chroma, (x, y), side, mv,
7561 [
7562 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7563 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7564 ],
7565 None, search, chroma_set, t, fctx,
7566 )
7567 .unwrap_or([u, v]),
7568 None => [u, v],
7569 };
7570 chroma[0].commit(x / 2, y / 2, side / 2, &u);
7571 chroma[1].commit(x / 2, y / 2, side / 2, &v);
7572 (BlockCoeffs {
7573 luma_tx_types,
7574 angle_delta_y: 0,
7575 cfl_alphas: None,
7576 filter_intra: None,
7577 luma: coeffs(&levels, side),
7578 u: coeffs(&u.levels, side / 2),
7579 v: coeffs(&v.levels, side / 2),
7580 mode: DC_PRED as u8,
7581 uv_mode: DC_PRED,
7582 skip,
7583 eight: None,
7584 dv: None,
7585 palette: None,
7586 palette_uv: None,
7587 tx_depth,
7588 motion_mode: 0,
7589 inter: Some(InterInfo {
7590 ref1: None,
7591 mv1: (0, 0),
7592 ref_frame: crate::mvstack::LAST_FRAME,
7593 mode: InterMode::NearestMv,
7594 mv,
7595 ref_mv_idx: 0,
7596 }),
7597 }, inter_cost + dcost)
7598 } else {
7599 (intra_block, intra_cost)
7600 }
7601}
7602
7603/// Publishes one coded inter-frame block into the `mi` grid the next block's
7604/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
7605/// block casts no vote but is still a coded cell (see `code_square_inter`'s
7606/// note on `processed_rows`/`processed_cols`).
7607fn record_mi(
7608 grid: &mut MiGrid,
7609 mi_row: usize,
7610 mi_col: usize,
7611 size: u8,
7612 inter: Option<InterInfo>,
7613 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
7614 // the RD pricer the two cells the writer's `skip_ctx` sums.
7615 skip: bool,
7616) {
7617 let info = match inter {
7618 Some(info) => MiInfo {
7619 is_inter: true,
7620 ref_frame: info.ref_frame,
7621 // A COMPOUND block votes with BOTH of its references and both of
7622 // its vectors, exactly as the tile writer publishes it: recording
7623 // a compound block as a single-reference one here left the
7624 // encoder's own grid disagreeing with the writer's from the first
7625 // compound block on, so every later stack it searched against was
7626 // not the stack the decoder derives.
7627 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7628 mv1: mv16(info.mv1),
7629 mv: mv16(info.mv),
7630 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
7631 // side, compound modes 2/3/7 on the other.
7632 is_new_mv: matches!(
7633 info.mode,
7634 InterMode::NewMv
7635 | InterMode::NewNewMv
7636 | InterMode::NearestNewMv
7637 | InterMode::NewNearestMv
7638 ),
7639 size,
7640 size_h: size,
7641 is_global_mv0: false,
7642 is_global_mv1: false,
7643 },
7644 None => MiInfo {
7645 is_inter: false,
7646 ref_frame: -1,
7647 ref_frame1: NO_REF1,
7648 mv1: (0, 0),
7649 mv: (0, 0),
7650 is_new_mv: false,
7651 size,
7652 size_h: size,
7653 is_global_mv0: false,
7654 is_global_mv1: false,
7655 },
7656 };
7657 for dr in 0..usize::from(size) {
7658 for dc in 0..usize::from(size) {
7659 grid.set(mi_row + dr, mi_col + dc, info);
7660 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7661 }
7662 }
7663}
7664
7665/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
7666/// writer's own `write_inter_block_128_rect` makes, so the second half of a
7667/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
7668fn record_mi_rect(
7669 grid: &mut MiGrid,
7670 mi_row: usize,
7671 mi_col: usize,
7672 (w_mi, h_mi): (usize, usize),
7673 inter: Option<InterInfo>,
7674 skip: bool,
7675) {
7676 record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
7677 // `record_mi` stamped the square corner; widen it to the true footprint,
7678 // with the block's own (rect) size fields.
7679 let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
7680 info.size = w_mi as u8;
7681 info.size_h = h_mi as u8;
7682 for dr in 0..h_mi {
7683 for dc in 0..w_mi {
7684 grid.set(mi_row + dr, mi_col + dc, info);
7685 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7686 }
7687 }
7688}
7689
7690/// The reconstructed samples one 32x32 square covers in all three planes, so
7691/// that a partition trial can be undone.
7692/// One square of a plane, row-major, the inverse of [`Plane::restore`].
7693///
7694/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
7695/// which allocated and freed a `Vec` per row of every block it copied --
7696/// `Plane::snapshot` runs once per partition trial.
7697fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
7698 let mut out = vec![0u8; side * side];
7699 for row in 0..side {
7700 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
7701 }
7702 out
7703}
7704
7705fn snapshot(
7706 luma: &Plane,
7707 chroma: &[Plane; 2],
7708 (x, y): (usize, usize),
7709 side: usize,
7710) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
7711 [
7712 luma.snapshot(x, y, side),
7713 chroma[0].snapshot(x / 2, y / 2, side / 2),
7714 chroma[1].snapshot(x / 2, y / 2, side / 2),
7715 ]
7716}
7717
7718/// Puts such a snapshot back.
7719fn restore(
7720 luma: &mut Plane,
7721 chroma: &mut [Plane; 2],
7722 (x, y): (usize, usize),
7723 side: usize,
7724 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
7725) {
7726 luma.restore(x, y, side, &saved[0]);
7727 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
7728 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
7729}
7730
7731/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
7732/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
7733/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
7734/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
7735/// rule shared with the key-frame path, not a second one that could diverge.
7736fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
7737 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
7738 let dc_entry = dc_pos.map(|i| scored.remove(i));
7739 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
7740 scored.truncate(if dc_entry.is_some() {
7741 top_k.saturating_sub(1)
7742 } else {
7743 top_k
7744 });
7745 if let Some(dc_entry) = dc_entry {
7746 scored.push(dc_entry);
7747 }
7748 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
7749 modes.iter().copied().filter(|m| keep.contains(m)).collect()
7750}
7751
7752fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
7753 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
7754 [INTRA_MODE_CTX[usize::from(left_mode)]];
7755 std::array::from_fn(|mode| {
7756 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
7757 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
7758 } else {
7759 0.0
7760 };
7761 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
7762 })
7763}
7764
7765/// What the luma mode search picks between, and under what terms.
7766#[derive(Clone, Copy)]
7767struct Search<'a> {
7768 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
7769 /// luma search then offers a palette candidate beside the intra modes.
7770 screen: bool,
7771 base_q_idx: u8,
7772 deadzone: f64,
7773 lambda: f64,
7774 modes: &'a [u8],
7775 /// How many of `modes` the full RD trial (forward transform, quantize,
7776 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
7777 /// pre-pass on the prediction residual alone plus DC (always kept, since
7778 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
7779 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
7780 /// mode through full RD, unchanged from before this lever.
7781 top_k: Option<usize>,
7782 /// lane-arfmode: the top ARF's offer set ([`crate::speed::ARFMODE`])
7783 /// -- `false` cuts the named candidate group from the whole-32 search
7784 /// ([`search_inter_block`]), the 16x16/8x8 leaf search
7785 /// ([`code_square_inter`]) and the 8x8 split offer, at the top ARF
7786 /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is
7787 /// the pre-lane behaviour: the mid and quarter hidden frames, the shown
7788 /// leaves and the flat path keep intra and compound, and the
7789 /// straddling-edge 8x8s are only mode-gated, never partition-gated.
7790 /// The probe's correction: with the leaf gate ALONE the film A stream
7791 /// was byte-identical to the control -- the ARF's intra area lives at
7792 /// the whole-32 level, so the intra arm must cut it there too.
7793 arf_leaf_intra: bool,
7794 arf_leaf8: bool,
7795 arf_leaf_compound: bool,
7796}
7797
7798/// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what
7799/// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the
7800/// shipped table -- 0, bit-exact with the pre-lane encoder).
7801fn arfmode() -> u8 {
7802 match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
7803 u8::MAX => {}
7804 n => return n,
7805 }
7806 static ENV: std::sync::LazyLock<Option<u8>> = std::sync::LazyLock::new(|| {
7807 crate::envflags::var("EC_AV1_ARFMODE").ok().and_then(|v| v.parse().ok())
7808 });
7809 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE))
7810}
7811
7812/// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.
7813static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
7814
7815/// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
7816/// process constant ([`crate::envflags`]), so an in-process witness needs
7817/// this to arm the lever.
7818#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
7819pub(crate) fn set_arfmode(n: Option<u8>) {
7820 ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed);
7821}
7822
7823/// How often each armed [`crate::speed::ARFMODE`] arm actually fired since
7824/// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded
7825/// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8
7826/// split the search would have offered and the arm refused, 2 = a top-ARF
7827/// leaf whose compound set was dropped. A green gate over counts of zero
7828/// proves nothing about the lever.
7829static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [
7830 std::sync::atomic::AtomicUsize::new(0),
7831 std::sync::atomic::AtomicUsize::new(0),
7832 std::sync::atomic::AtomicUsize::new(0),
7833];
7834
7835/// Records one such hit.
7836fn arfmode_hit(which: usize) {
7837 ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7838}
7839
7840/// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer
7841/// condition, so the counter only runs when every other prune let the split
7842/// through and the arm alone refuses it.
7843fn arfmode_hit_and_no() -> bool {
7844 arfmode_hit(1);
7845 false
7846}
7847
7848/// Takes (and clears) the counts. `pub` for `examples/enc_probe`, so a
7849/// probe point can print a non-zero engagement count under the env knob
7850/// itself -- the counter the gate BD numbers are read against.
7851pub fn take_arfmode_hits() -> [usize; 3] {
7852 [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7853}
7854
7855fn prune_top_k() -> Option<usize> {
7856 #[cfg(test)]
7857 {
7858 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
7859 return k;
7860 }
7861 }
7862 let swept = std::env::var("EC_AV1_PRUNE_K")
7863 .ok()
7864 .and_then(|v| v.parse::<usize>().ok());
7865 match swept {
7866 Some(k) if cfg!(test) => Some(k),
7867 _ => crate::speed::at(&crate::speed::PRUNE_K),
7868 }
7869}
7870
7871// A per-thread override [`prune_top_k`] checks first, so one test can sweep
7872// `top_k` in-process without mutating the environment (forbidden here --
7873// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
7874#[cfg(test)]
7875thread_local! {
7876 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
7877 const { std::cell::Cell::new(None) };
7878}
7879
7880#[cfg(test)]
7881fn set_test_top_k_override(value: Option<usize>) {
7882 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
7883}
7884
7885/// The default: unpruned, thirteen full trials per block, same as before this
7886/// lever. Set from the sweep in the lane report if the quality gate clears it.
7887pub(crate) const PRUNE_TOP_K: Option<usize> = None;
7888
7889/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
7890/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
7891/// quality gates were measured separately and may land on different
7892/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
7893/// [`EC_AV1_PRUNE_K`] or the key-frame path.
7894fn prune_top_k_inter() -> Option<usize> {
7895 #[cfg(test)]
7896 {
7897 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
7898 return k;
7899 }
7900 }
7901 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
7902 .ok()
7903 .and_then(|v| v.parse::<usize>().ok());
7904 match swept {
7905 Some(k) if cfg!(test) => Some(k),
7906 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
7907 }
7908}
7909
7910// A per-thread override [`prune_top_k_inter`] checks first, same reason as
7911// [`TEST_TOP_K_OVERRIDE`].
7912#[cfg(test)]
7913thread_local! {
7914 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
7915 const { std::cell::Cell::new(None) };
7916}
7917
7918#[cfg(test)]
7919fn set_test_top_k_override_inter(value: Option<usize>) {
7920 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
7921}
7922
7923/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
7924/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
7925/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
7926/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
7927/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
7928/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
7929/// pruning them costs less quality here.
7930pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
7931
7932// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
7933// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
7934// inter frame's cost can be attributed to a bucket without changing what
7935// the search actually does. Index: 0 = whole-call time inside
7936// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
7937// [`crate::mc::predict`] (every call, from the motion search's own
7938// candidates and from a committed inter block's final prediction alike),
7939// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
7940#[cfg(test)]
7941thread_local! {
7942 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
7943 std::cell::Cell::new(0),
7944 std::cell::Cell::new(0),
7945 std::cell::Cell::new(0),
7946 std::cell::Cell::new(0),
7947 ];
7948}
7949
7950/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
7951/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
7952/// per transform trial and per `mc::predict` call whether or not anyone was
7953/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
7954/// The clock is now read only when [`crate::par::stage_times`] is on, which
7955/// is what prints the breakdown in the first place.
7956#[cfg(test)]
7957pub(crate) fn stage_start() -> Option<std::time::Instant> {
7958 crate::par::stage_times().then(std::time::Instant::now)
7959}
7960
7961#[cfg(test)]
7962pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
7963 if let Some(t) = t {
7964 stage_add(bucket, t.elapsed());
7965 }
7966}
7967
7968#[cfg(test)]
7969pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
7970 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
7971}
7972
7973#[cfg(test)]
7974fn stage_reset() {
7975 crate::par::set_stage_times(true);
7976 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
7977}
7978
7979#[cfg(test)]
7980fn stage_read() -> [std::time::Duration; 4] {
7981 crate::par::set_stage_times(false);
7982 STAGE_NS.with(|c| {
7983 c.each_ref()
7984 .map(|cell| std::time::Duration::from_nanos(cell.get()))
7985 })
7986}
7987
7988/// One mode's coding of one block, before it is committed.
7989#[derive(Clone)]
7990struct Trial {
7991 levels: Vec<i32>,
7992 reconstruction: Vec<u8>,
7993 sse: f64,
7994 bits: f64,
7995}
7996
7997/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
7998/// of a 64-point transform that is actually coded (everything outside it is
7999/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
8000fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
8001 let mut out = vec![0i32; to * to];
8002 for row in 0..to {
8003 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
8004 }
8005 out
8006}
8007
8008/// The non-zero levels of a block, as the tile writer takes them.
8009fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
8010 levels
8011 .iter()
8012 .enumerate()
8013 .filter(|&(_, &level)| level != 0)
8014 .map(|(i, &level)| Coeff {
8015 row: (i / side) as u8,
8016 col: (i % side) as u8,
8017 level,
8018 })
8019 .collect()
8020}
8021
8022thread_local! {
8023 /// The tile grid the next frame is coded with, as `(TileColsLog2,
8024 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
8025 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
8026 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
8027 /// one tile per frame, what every caller that never arms anything gets
8028 /// and what every stream this crate wrote before tiles existed carries.
8029 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
8030}
8031
8032/// Arms this thread's next frame encodes with a tile grid (log2 counts).
8033pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
8034 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
8035}
8036
8037fn armed_tiles() -> (u32, u32) {
8038 let armed = TILE_LOG2.with(std::cell::Cell::get);
8039 if armed != (0, 0) {
8040 return armed;
8041 }
8042 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
8043 // (which codes through `encode_sequence`, not the facade) can measure what
8044 // a tile grid costs without a knob of its own -- same shape as
8045 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
8046 match std::env::var("EC_AV1_TILES").ok() {
8047 Some(v) if cfg!(test) => {
8048 let mut f = v.split(':');
8049 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
8050 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
8051 (cols, rows)
8052 }
8053 _ => armed,
8054 }
8055}
8056
8057/// Codes a frame's `tiles` tiles, each entirely on its own (see
8058/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
8059/// the crate's own pool, and hands back their payloads in tile order plus
8060/// whatever `code` returned for tile `store` -- the CDF state
8061/// `context_update_tile_id` names. The result cannot depend on the thread
8062/// count: each job writes one tile from the frame's own starting tables into
8063/// its own slot.
8064fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
8065where
8066 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
8067{
8068 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
8069 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
8070 let threads = crate::par::tile_threads().min(tiles);
8071 let mut slots: Vec<Slot> = Vec::new();
8072 if threads <= 1 {
8073 for index in 0..tiles {
8074 slots.push(Some(code(index)));
8075 }
8076 } else {
8077 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8078 {
8079 let batch = crate::par::Batch::new("ec-av1-tile");
8080 for (from, to) in crate::par::bands(tiles, threads) {
8081 let done = &done;
8082 let code = &code;
8083 batch.submit(move || {
8084 for index in from..to {
8085 let coded = code(index);
8086 done.lock().expect("tile slots")[index] = Some(coded);
8087 }
8088 });
8089 }
8090 }
8091 slots = done.into_inner().expect("tile slots");
8092 }
8093 let mut out = Vec::with_capacity(tiles);
8094 let mut stored = None;
8095 for (index, slot) in slots.into_iter().enumerate() {
8096 let (bytes, cdfs) = slot.expect("every tile was coded")?;
8097 if index == store {
8098 stored = cdfs;
8099 }
8100 out.push(bytes);
8101 }
8102 Ok((out, stored))
8103}
8104
8105/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
8106/// workers, and returns the results in tile order. The counterpart of
8107/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
8108/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
8109/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
8110/// availability is already tile-relative (`clip_planes_to_tile`,
8111/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
8112/// other tiles have run -- gated by
8113/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
8114/// covers the search as well as the write.
8115///
8116/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
8117/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
8118/// does it for the decoder's filter bands.
8119fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
8120where
8121 T: Send,
8122 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
8123{
8124 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
8125 let threads = crate::par::tile_threads().min(tiles);
8126 if threads <= 1 {
8127 return (0..tiles).map(|index| job(index, fctx)).collect();
8128 }
8129 type Slot<T> = Option<Result<T>>;
8130 let done: std::sync::Mutex<Vec<Slot<T>>> =
8131 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8132 {
8133 let batch = crate::par::Batch::new("ec-av1-tile-search");
8134 for (from, to) in crate::par::bands(tiles, threads) {
8135 let done = &done;
8136 let job = &job;
8137 let ctx = crate::decode::filter_ctx_copy(fctx);
8138 batch.submit(move || {
8139 for index in from..to {
8140 let searched = job(index, &ctx);
8141 done.lock().expect("tile slots")[index] = Some(searched);
8142 }
8143 });
8144 }
8145 }
8146 done.into_inner()
8147 .expect("tile slots")
8148 .into_iter()
8149 .map(|slot| slot.expect("every tile was searched"))
8150 .collect()
8151}
8152
8153/// One tile job's own copy of a plane: the frame's source, a blank
8154/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
8155/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
8156/// of the frame's reconstruction because a tile's prediction never reads a
8157/// sample outside its own rectangle, and every sample inside it is written
8158/// before it is read.
8159fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
8160 Plane {
8161 source,
8162 reconstruction: vec![128; source.len()],
8163 width,
8164 height,
8165 true_width,
8166 true_height,
8167 tile_x0: 0,
8168 tile_y0: 0,
8169 tile_x1: width,
8170 tile_y1: height,
8171 ctx: CoefCtxMap::default(),
8172 }
8173}
8174
8175/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
8176/// the frame's plane, through the [`crate::par::Shared`] every job holds.
8177///
8178/// corner-cut: the disjointness that makes the aliasing sound is the caller's
8179/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
8180/// rectangles partition it -- checked end-to-end by
8181/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
8182/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
8183/// row-range `split_at_mut` plumbing through `Plane`, which would have to
8184/// thread an origin offset through every prediction and transform call site
8185/// for the same bytes.
8186#[allow(unsafe_code)]
8187fn copy_rect(
8188 dst: crate::par::Shared<'_, Vec<u8>>,
8189 src: &[u8],
8190 stride: usize,
8191 x0: usize,
8192 y0: usize,
8193 x1: usize,
8194 y1: usize,
8195) {
8196 // SAFETY: this job touches only its own tile rectangle (see above).
8197 let dst = unsafe { dst.get() };
8198 for y in y0..y1 {
8199 let (a, b) = (y * stride + x0, y * stride + x1);
8200 dst[a..b].copy_from_slice(&src[a..b]);
8201 }
8202}
8203
8204/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
8205/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
8206/// tables the frame stores (spec 7.20), which is what
8207/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
8208/// below publish.
8209fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
8210 ec_av1_syntax::TileInfo {
8211 uniform_spacing: true,
8212 cols: layout.cols(),
8213 rows: layout.rows(),
8214 cols_log2: layout.cols_log2,
8215 rows_log2: layout.rows_log2,
8216 mi_col_starts: layout.mi_col_starts(),
8217 mi_row_starts: layout.mi_row_starts(),
8218 context_update_tile_id: layout.largest_tile() as u32,
8219 tile_size_bytes,
8220 }
8221}
8222
8223/// Clips the three planes' intra edge reads to `rect`, the tile the
8224/// superblock about to be searched belongs to (the encoder side of the
8225/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
8226/// raster order -- which is a linear extension of every tile's own coding
8227/// order, so a block still only ever predicts from samples already
8228/// reconstructed -- and only availability is tile-relative.
8229fn clip_planes_to_tile(
8230 luma: &mut Plane<'_>,
8231 chroma: &mut [Plane<'_>; 2],
8232 rect: crate::tile::TileRect,
8233) {
8234 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8235 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8236 luma.set_tile(x0, y0, x1, y1);
8237 for plane in chroma.iter_mut() {
8238 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
8239 }
8240}
8241
8242/// Encodes one picture as a key frame.
8243///
8244/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
8245/// picks its coefficient CDFs from one of four q contexts by that index.
8246/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
8247/// smaller values trade fidelity for rate.
8248///
8249/// The picture may be any even width and height: the encoder pads it by edge
8250/// replication to a whole number of 32x32 blocks internally, and the frame it
8251/// writes crops back to the picture's own size (`render_width`/
8252/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
8253/// own size, never the padded one.
8254///
8255/// # Errors
8256/// Returns an error when the picture's width or height is zero or odd, or
8257/// when its planes are not 4:2:0 of that size.
8258/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
8259/// stream. The per-frame decode state this needs lives for exactly this call.
8260///
8261/// # Errors
8262/// Returns an error under the same conditions
8263/// [`encode_key_frame_with_modes`] does.
8264pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
8265 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
8266}
8267
8268/// [`encode_key_frame`] with the per-block intra modes given rather than
8269/// searched.
8270///
8271/// # Errors
8272/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
8273/// is empty, or when a block's coefficients do not fit the coded frame.
8274pub fn encode_key_frame_with_modes(
8275 picture: &Picture,
8276 base_q_idx: u8,
8277 deadzone: f64,
8278 modes: &[u8],
8279) -> Result<Encoded> {
8280 encode_key_frame_with_modes_with_ctx(
8281 picture,
8282 base_q_idx,
8283 deadzone,
8284 modes,
8285 &crate::decode::FrameCtx::for_encoder(),
8286 )
8287}
8288
8289/// Codes `pictures` as one key frame followed by inter frames.
8290///
8291/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
8292/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
8293/// `show_existing_frame` header, so `stream` is in CODING order while
8294/// `frames` stays in display order (`EncodedSequence::coding_order` is the
8295/// map). Screen content codes flat, decided once per sequence by the same
8296/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
8297/// puts every stream back on the flat path for an A/B.
8298///
8299/// # Errors
8300/// Returns an error under the same conditions [`encode_key_frame`] and the
8301/// inter frame path do.
8302pub fn encode_sequence(
8303 pictures: &[Picture],
8304 base_q_idx: u8,
8305 deadzone: f64,
8306) -> Result<EncodedSequence> {
8307 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
8308}
8309
8310pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
8311 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
8312}
8313
8314/// Encodes one picture as a key frame, choosing each block's luma mode from
8315/// `modes` alone.
8316///
8317/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
8318/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
8319/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
8320/// uses.
8321///
8322/// # Errors
8323/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
8324/// names a mode [`crate::intra::predict`] does not predict.
8325pub(crate) fn encode_key_frame_with_modes_with_ctx(
8326 picture: &Picture,
8327 base_q_idx: u8,
8328 deadzone: f64,
8329 modes: &[u8], fctx: &crate::decode::FrameCtx,
8330) -> Result<Encoded> {
8331 picture.check_even()?;
8332 let padded = picture.padded_to(BLOCK);
8333 let encoded = encode_key_frame_inner(
8334 &padded,
8335 base_q_idx,
8336 deadzone,
8337 modes,
8338 split_blocks(),
8339 (picture.width, picture.height),
8340 unspecified_color_config(), fctx,
8341 )?;
8342 Ok(crop_encoded(&encoded, picture.width, picture.height))
8343}
8344
8345/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
8346/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
8347/// already padded to a whole number of 32x32 blocks; `render` is the real
8348/// (pre-pad) size the frame header tells a decoder to crop back to.
8349pub(crate) fn encode_key_frame_inner(
8350 picture: &Picture,
8351 base_q_idx: u8,
8352 deadzone: f64,
8353 modes: &[u8],
8354 split_blocks: bool,
8355 render: (usize, usize),
8356 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
8357) -> Result<Encoded> {
8358 // lane-refs: an intra frame runs no motion compensation, and the
8359 // context is shared across the sequence -- put the kernel back to the
8360 // default so nothing reads the previous inter frame's.
8361 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
8362 picture.check()?;
8363 if modes.is_empty() {
8364 return Err(Error::unsupported(
8365 "AV1 encode",
8366 "a mode search needs at least one mode to choose from",
8367 ));
8368 }
8369 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
8370 return Err(Error::unsupported(
8371 "AV1 encode",
8372 format!("intra mode {bad} is not one the encoder predicts"),
8373 ));
8374 }
8375 // The header carries the frame's true (unpadded) size as `frame_width`/
8376 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
8377 // `mi_rows` derived from that same true size (spec `compute_image_size`).
8378 // `render_width`/`render_height` come out equal to it too, so
8379 // `render_and_frame_size_different` is false and no render_size bits are
8380 // written, mirroring libaom/rav1e: the padded `picture` below is only the
8381 // internal coding surface, never what the header names.
8382 // Screen-content detection runs on the SOURCE luma, before any header is
8383 // built: it decides this sequence's `seq_force_screen_content_tools` (and
8384 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
8385 // this frame's own `allow_screen_content_tools`.
8386 let screen = screen_content(
8387 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8388 picture.width,
8389 (picture.width).min(render.0),
8390 (picture.height).min(render.1),
8391 );
8392 arm_seq_screen(screen);
8393 // A key frame's writer really does start from the defaults, and a search
8394 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
8395 // disarm, or a key frame's bits would depend on which thread searched it.
8396 crate::tile::arm_pricing_cdfs(None, false);
8397 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
8398 // forces deblocking, CDEF and loop restoration OFF for this frame
8399 // (frame.rs:194/210/252/272), so it is only set when the source repeats
8400 // itself enough for the copied blocks to pay that back
8401 // ([`intrabc_worth_it`]).
8402 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
8403 // grid across every tile while this writer builds one per tile, so a
8404 // multi-tile allow_intrabc frame would predict its DVs off a different
8405 // grid than the decoder does. corner-cut, ceiling named: the upgrade
8406 // path is a frame-scoped grid shared by the tile writers.
8407 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
8408 intrabc_worth_it(
8409 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8410 picture.width,
8411 picture.width.min(render.0),
8412 picture.height.min(render.1),
8413 )
8414 } else {
8415 (false, 0.0)
8416 };
8417 IBC_SHARE.with(|c| c.set(ibc_share));
8418 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
8419 header.allow_screen_content_tools = screen;
8420 // lane-txi: the wider `tx_type` alphabets, gated by the same content
8421 // rule the type search itself stands behind ([`wide_tx_set`]).
8422 header.reduced_tx_set = !wide_tx_set(screen);
8423 header.allow_intrabc = allow_intrabc;
8424 header.render_width = render.0 as u32;
8425 header.render_height = render.1 as u32;
8426 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
8427 // its luma transform below its own side (`crate::tile::write_luma_select`).
8428 // Set here rather than in `key_frame_headers_colour` so the header
8429 // builders' other callers -- the hand-built tile writers, which code no
8430 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
8431 let tx_select = tx_select();
8432 if tx_select {
8433 header.tx_mode = TxMode::Select;
8434 }
8435 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
8436
8437 // Prediction reads no further than this, in each plane's own units --
8438 // see `Plane::true_width`/`true_height`.
8439 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
8440 // lane-palw: the encoder's own in-process reconstruct reads its palette
8441 // colour-index maps back through `decode::palette_onscreen`, which takes
8442 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
8443 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
8444 // them here so the reconstruct clamps a block cut by the frame edge
8445 // exactly as the writer now does.
8446 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
8447 fctx.seg_mi_dims.set(frame_mi_dims);
8448 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
8449 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
8450 // design (see `intra_predict_u8`'s doc comment), so narrow the source
8451 // once here.
8452 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
8453 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
8454 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
8455 let mut luma = Plane {
8456 source: &picture_y8,
8457 reconstruction: vec![128; picture_y8.len()],
8458 width: picture.width,
8459 height: picture.height,
8460 true_width,
8461 true_height,
8462 tile_x0: 0,
8463 tile_y0: 0,
8464 tile_x1: picture.width,
8465 tile_y1: picture.height,
8466 ctx: CoefCtxMap::default(),
8467 };
8468 let mut chroma = [
8469 Plane {
8470 source: &picture_u8,
8471 reconstruction: vec![128; picture_u8.len()],
8472 width: picture.width / 2,
8473 height: picture.height / 2,
8474 true_width: true_width / 2,
8475 true_height: true_height / 2,
8476 tile_x0: 0,
8477 tile_y0: 0,
8478 tile_x1: picture.width / 2,
8479 tile_y1: picture.height / 2,
8480 ctx: CoefCtxMap::default(),
8481 },
8482 Plane {
8483 source: &picture_v8,
8484 reconstruction: vec![128; picture_v8.len()],
8485 width: picture.width / 2,
8486 height: picture.height / 2,
8487 true_width: true_width / 2,
8488 true_height: true_height / 2,
8489 tile_x0: 0,
8490 tile_y0: 0,
8491 tile_x1: picture.width / 2,
8492 tile_y1: picture.height / 2,
8493 ctx: CoefCtxMap::default(),
8494 },
8495 ];
8496
8497 // The search trades a bit for the squared error it saves, in the units the
8498 // reconstruction is measured in: one step of the quantizer, squared.
8499 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
8500 let search = Search {
8501 base_q_idx,
8502 deadzone,
8503 lambda: lambda_scale() * key_lambda_factor() * step * step,
8504 modes,
8505 top_k: prune_top_k(),
8506 screen,
8507 arf_leaf_intra: true,
8508 arf_leaf8: true,
8509 arf_leaf_compound: true,
8510 };
8511
8512 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
8513 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
8514 // which may be fewer columns/rows than the padded picture has room for
8515 // -- a block whose origin sits past the true bound is not coded at all,
8516 // matching what a decoder derives from `frame_width`/`frame_height` and
8517 // so never visits either.
8518 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
8519 let (cols, rows) = (cols as usize, rows as usize);
8520 // The luma mode of the block above and of the block to the left, which is
8521 // what picks the CDF the next block's mode is coded against -- the same
8522 // bookkeeping the tile writer keeps, so that the search is costing the
8523 // symbol the writer will actually write.
8524 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
8525 // because a 32x32 block may be split into four 16x16 ones.
8526 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
8527 // This frame's tile grid (one tile unless the facade armed more).
8528 let layout =
8529 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
8530 header.tile_info = tile_info_of(&layout, 1);
8531 // The filter search re-decodes this frame's tiles; the decoder derives
8532 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
8533 // `mi_row_starts`), which is what makes the writer's rects and the
8534 // reader's the same rects.
8535 let header_tile_info = header.tile_info.clone();
8536 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
8537 // once over the whole frame. Each tile job builds its own reconstruction
8538 // planes and its own `above_mode`/`left_mode` bands, which is also what
8539 // the tile writer reads -- a tile resets its neighbour contexts (spec
8540 // 5.11.1), so a block at a tile's left edge must cost its mode against
8541 // the default context, not against whatever the tile to its west left in
8542 // that row. At one tile the bands are the frame's, exactly as before.
8543 let (frame_width, frame_height) = (picture.width, picture.height);
8544 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
8545 let [cb, cr] = &mut chroma;
8546 let chroma_out = [
8547 crate::par::Shared::new(&mut cb.reconstruction),
8548 crate::par::Shared::new(&mut cr.reconstruction),
8549 ];
8550 let search_tile = |index: usize,
8551 fctx: &crate::decode::FrameCtx|
8552 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
8553 crate::tile::arm_pricing_cdfs(None, false);
8554 let rect = layout.rect(index);
8555 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
8556 let mut chroma = [
8557 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8558 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8559 ];
8560 clip_planes_to_tile(&mut luma, &mut chroma, rect);
8561 let mut above_mode = vec![DC_PRED; cols * 2];
8562 let mut left_mode = vec![DC_PRED; rows * 2];
8563 let mut ibc = allow_intrabc.then(|| {
8564 Ibc::new(
8565 (
8566 rect.mi_col0 as usize * 4,
8567 rect.mi_row0 as usize * 4,
8568 (rect.mi_col1 as usize * 4).min(true_width),
8569 (rect.mi_row1 as usize * 4).min(true_height),
8570 ),
8571 &picture_y8,
8572 frame_width,
8573 )
8574 });
8575 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
8576 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
8577 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
8578 let mut modes = Vec::with_capacity(4);
8579 // The quadrants of a superblock are coded in the order the decoder
8580 // walks them, which for a 64x64 split into 32x32 blocks is raster
8581 // order among the quadrants that are inside the frame.
8582 let mut blocks = Vec::with_capacity(4);
8583 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
8584 // BEFORE its quadrants (so both start from the same
8585 // reconstruction) and compared against the four of them below --
8586 // the shape the inter frame's own 64 root takes
8587 // (`search_skip_64`). A frame that allows intrabc is refused
8588 // outright ([`I64_ROOT`]) because the quadrant searches below
8589 // carry DV state a discarded trial would desync.
8590 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
8591 // lane-corner LIFTED the two guards this root shipped with: the
8592 // frame no longer has to be a whole number of superblocks, and
8593 // the superblock no longer has to be wholly inside the frame.
8594 // The desync the guards were written for (a 248x152 corner's
8595 // chroma disagreeing three ways) does NOT reproduce at this
8596 // revision -- see
8597 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
8598 // which pins all three planes of the encoder's reconstruction,
8599 // our decoder and ffmpeg on four straddling sizes, three of them
8600 // cut on BOTH axes, with the edge fire count asserted. What the
8601 // guards cost was every key-frame root on an arbitrary export
8602 // size (the `aligned` line switched the whole feature off on, for
8603 // instance, a 1920x792 frame).
8604 let whole_inside = x64 + SUPERBLOCK <= luma.true_width
8605 && y64 + SUPERBLOCK <= luma.true_height;
8606 // lane-corner: and the superblock the true frame edge CUTS
8607 // THROUGH with more than half of each axis still inside, which is
8608 // all AV1 asks of a `PARTITION_NONE` root (spec
8609 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
8610 // key writer's `Superblock::Whole` arm checks) -- the shape the
8611 // inter root already takes ([`b64_edge`]).
8612 let edge_inside = edge_root_enabled()
8613 && crate::tile::has_half(
8614 sb_col as u32 * crate::tile::SB_MI,
8615 crate::tile::SB_MI,
8616 header.mi_cols,
8617 )
8618 && crate::tile::has_half(
8619 sb_row as u32 * crate::tile::SB_MI,
8620 crate::tile::SB_MI,
8621 header.mi_rows,
8622 );
8623 let sb64_legal = i64_root()
8624 && ibc.is_none()
8625 && sb_row * 2 + 1 < rows
8626 && sb_col * 2 + 1 < cols
8627 && (whole_inside || edge_inside);
8628 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
8629 if sb64_legal {
8630 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8631 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8632 let (c64, r64) = (sb_col * 4, sb_row * 4);
8633 let (block, cost) = code_square(
8634 &mut luma,
8635 &mut chroma,
8636 (x64, y64),
8637 SUPERBLOCK,
8638 &search,
8639 &mode_bits(above_mode[c64], left_mode[r64]),
8640 tx_select,
8641 None,
8642 true,
8643 fctx,
8644 );
8645 let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
8646 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8647 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
8648 sb64 = Some((cost, block, after));
8649 }
8650 // A superblock whose 64x64 trial already codes almost nothing per
8651 // pixel is taken outright and its quadrants are never searched --
8652 // `split_rd_breakout` one size up, at the threshold the inter
8653 // root clamps to ([`b64_breakout_threshold`]), where this lever
8654 // BUYS wall instead of spending it.
8655 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
8656 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
8657 });
8658 // What the four quadrants cost together, including the split
8659 // partition symbol at the superblock level, so the two arms are
8660 // one comparable number.
8661 let mut sb_cost = match sb64 {
8662 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
8663 None => 0.0,
8664 };
8665 for quadrant in 0..if early64 { 0 } else { 4 } {
8666 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
8667 if col >= cols || row >= rows {
8668 continue;
8669 }
8670 let (x, y) = (col * BLOCK, row * BLOCK);
8671 let (c0, r0) = (col * 2, row * 2);
8672 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
8673
8674 // spec `decode_partition`'s hasRows/hasCols recomputed at this
8675 // 32x32 block's own half (see `crate::tile::has_half`): the
8676 // true frame edge can fall inside a quadrant a superblock-level
8677 // check already let through. A quadrant that fails either may
8678 // not be left whole; a 16x16 sub-block that fails either (once
8679 // split) is a leaf this writer has no rectangular transform
8680 // for, so the search must not pick a split that would need one.
8681 let (has_cols32, has_rows32) = (
8682 crate::tile::has_half(
8683 col as u32 * crate::tile::BLOCK_MI,
8684 crate::tile::BLOCK_MI,
8685 header.mi_cols,
8686 ),
8687 crate::tile::has_half(
8688 row as u32 * crate::tile::BLOCK_MI,
8689 crate::tile::BLOCK_MI,
8690 header.mi_rows,
8691 ),
8692 );
8693 let whole_legal = has_cols32 && has_rows32;
8694 // A 16x16 sub-block's own hasCols/hasRows (spec
8695 // `decode_partition`, recomputed at this leaf's own half):
8696 // either axis false is a straddling leaf this writer codes as
8697 // the 8x8 leaves that are inside it
8698 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
8699 // false is the same split with the partition symbol inferred
8700 // rather than coded -- no rectangular transform is needed
8701 // (lane-av1rect).
8702 let sub_half = |sr: usize, sc: usize| {
8703 (
8704 crate::tile::has_half(
8705 sc as u32 * crate::tile::SUB_MI,
8706 crate::tile::SUB_MI,
8707 header.mi_cols,
8708 ),
8709 crate::tile::has_half(
8710 sr as u32 * crate::tile::SUB_MI,
8711 crate::tile::SUB_MI,
8712 header.mi_rows,
8713 ),
8714 )
8715 };
8716 // What the whole 32x32 costs, including the partition symbol
8717 // that says it is not split.
8718 let (whole, mut cost_whole) = code_square(
8719 &mut luma,
8720 &mut chroma,
8721 (x, y),
8722 BLOCK,
8723 &search,
8724 &mode_bits(above_mode[c0], left_mode[r0]),
8725 tx_select,
8726 ibc.as_mut(),
8727 true,
8728 fctx,
8729 );
8730 cost_whole += search.lambda * partition_bits(BLOCK, false);
8731 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
8732
8733 // What four 16x16 blocks cost instead, each searched against
8734 // the reconstruction the ones before it left.
8735 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
8736 let mut split = Vec::with_capacity(4);
8737 let mut cost_split = search.lambda
8738 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
8739 let mut split_modes = Vec::with_capacity(4);
8740 for sub in 0..4 {
8741 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
8742 // Same filter as the writer's `sub_positions` (spec
8743 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
8744 // return): a sub-block whose own origin sits past the
8745 // true frame is never coded, so it must not be searched
8746 // or pushed onto `split` either, or the writer's block
8747 // count will not match what it is prepared to name.
8748 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
8749 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
8750 {
8751 continue;
8752 }
8753 let (has_cols16, has_rows16) = sub_half(sr, sc);
8754 if has_cols16 && has_rows16 {
8755 let (block, cost) = code_square(
8756 &mut luma,
8757 &mut chroma,
8758 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
8759 SUB,
8760 &search,
8761 &mode_bits(above_mode[sc], left_mode[sr]),
8762 tx_select,
8763 ibc.as_mut(),
8764 true,
8765 fctx,
8766 );
8767 cost_split += cost;
8768 split_modes.push(block.mode);
8769 above_mode[sc] = block.mode;
8770 left_mode[sr] = block.mode;
8771 split.push(block);
8772 } else {
8773 // A straddling 16x16: two (or, at a true corner, one)
8774 // 8x8 leaves, in the raster order `write_leaf8`'s
8775 // caller expects. Both leaves cost against the SAME
8776 // enclosing-slot mode context (see
8777 // `crate::tile::write_leaf8`'s doc), and neither
8778 // updates `above_mode`/`left_mode` at this SUB slot --
8779 // the writer never does either, so the search must
8780 // not diverge from what it will actually read next.
8781 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
8782 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
8783 let mut leaves = Vec::with_capacity(2);
8784 for i in 0..4 {
8785 let leaf_x = x_sub + (i % 2) * 8;
8786 let leaf_y = y_sub + (i / 2) * 8;
8787 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
8788 continue;
8789 }
8790 let (leaf, cost) = code_square(
8791 &mut luma,
8792 &mut chroma,
8793 (leaf_x, leaf_y),
8794 8,
8795 &search,
8796 &leaf_mode_bits,
8797 tx_select,
8798 None,
8799 true,
8800 fctx,
8801 );
8802 cost_split += cost;
8803 split_modes.push(leaf.mode);
8804 leaves.push(leaf);
8805 }
8806 split.push(BlockCoeffs {
8807 eight: Some(leaves),
8808 ..BlockCoeffs::default()
8809 });
8810 }
8811 }
8812
8813 // A split whose subs are all whole 16x16 is a real quality
8814 // alternative to `whole`, exactly as before. Through r14, a
8815 // split carrying an 8x8-leaf sub was only ever forced
8816 // (`!whole_legal`), never chosen on cost, because the leaf
8817 // path was not yet proven against a real decoder; r15 proved
8818 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
8819 // the read path (`decode_leaf8`), so leaf8 can now win on
8820 // cost anywhere, same as any other split.
8821 if !whole_legal || (split_blocks && cost_split < cost_whole) {
8822 sb_cost += cost_split;
8823 modes.extend_from_slice(&split_modes);
8824 blocks.push(Quadrant::Split(split));
8825 } else {
8826 sb_cost += cost_whole;
8827 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
8828 for cell in 0..2 {
8829 above_mode[c0 + cell] = whole.mode;
8830 left_mode[r0 + cell] = whole.mode;
8831 }
8832 modes.push(whole.mode);
8833 blocks.push(Quadrant::Whole(whole));
8834 }
8835 }
8836 let index = sb_row * sb_cols + sb_col;
8837 match sb64 {
8838 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
8839 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
8840 for cell in 0..4 {
8841 above_mode[sb_col * 4 + cell] = block.mode;
8842 left_mode[sb_row * 4 + cell] = block.mode;
8843 }
8844 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8845 if !whole_inside {
8846 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8847 }
8848 let mode = block.mode;
8849 coded.push((index, Superblock::Whole(block), vec![mode]));
8850 }
8851 _ => coded.push((index, Superblock::Split(blocks), modes)),
8852 }
8853 }
8854 }
8855 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8856 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8857 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
8858 for (&out, tile) in chroma_out.iter().zip(&chroma) {
8859 copy_rect(
8860 out,
8861 &tile.reconstruction,
8862 frame_width / 2,
8863 x0 / 2,
8864 y0 / 2,
8865 x1.div_ceil(2),
8866 y1.div_ceil(2),
8867 );
8868 }
8869 Ok(coded)
8870 };
8871 let searched = search_tiles(layout.count(), fctx, search_tile)?;
8872 // Back into frame raster order: the tile writer indexes `superblocks` by
8873 // the frame's own superblock index, and `modes` is the coding order the
8874 // ablation drivers read.
8875 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
8876 for (at, superblock, block_modes) in searched.into_iter().flatten() {
8877 in_order[at] = Some((superblock, block_modes));
8878 }
8879 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
8880 let mut modes = Vec::with_capacity(cols * rows);
8881 for slot in in_order {
8882 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
8883 superblocks.push(superblock);
8884 modes.extend_from_slice(&block_modes);
8885 }
8886
8887 #[cfg(test)]
8888 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
8889 // A key frame always starts from the defaults (`primary_ref_frame` is
8890 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
8891 // set, so what it stores into the slots it refreshes is exactly those
8892 // defaults again (spec 7.20's `started_from` arm) -- the first inter
8893 // frame after it therefore starts from the defaults too.
8894 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
8895 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
8896 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
8897 // from -- `Cdfs::txb` widens every luma set under it.
8898 cdfs.reduced_tx_set = header.reduced_tx_set;
8899 let start_cdfs = CdfSnapshot(cdfs);
8900 // The luma restoration-unit grid this frame's `lr_params` implies
8901 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
8902 // swallowed by the one before it), for the tile writer's own per-unit
8903 // walk.
8904 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
8905 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
8906 // Every tile is coded from this frame's OWN starting tables and leaves
8907 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
8908 // loop-restoration reference and its neighbour contexts), so the tiles
8909 // are independent of each other and of the order they are written in.
8910 let code_tiles = |bits: u8,
8911 sb_cols: usize,
8912 grid: &[u8],
8913 units: &[Option<crate::restoration::WienerInfo>]|
8914 -> Result<Vec<Vec<u8>>> {
8915 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
8916 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
8917 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
8918 crate::tile::arm_sb128(sb128_on());
8919 let mut cdfs = start_cdfs.0.clone();
8920 crate::tile::arm_screen(screen);
8921 crate::tile::arm_frame_mi_dims(frame_mi_dims);
8922 crate::tile::arm_filter_intra(filter_intra_on());
8923 crate::tile::arm_intrabc(allow_intrabc);
8924 crate::tile::arm_pricing_cdfs(None, false);
8925 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
8926 mi_cols,
8927 mi_rows,
8928 base_q_idx,
8929 &superblocks,
8930 tx_select,
8931 &mut cdfs,
8932 layout.rect(index),
8933 )?;
8934 Ok((bytes, None))
8935 })?;
8936 Ok(out)
8937 };
8938 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
8939 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
8940 // the tile just coded back to the decoder under each candidate (see
8941 // `crate::filter_search`), and keep the filtered picture that wins as
8942 // the reconstruction -- what a decoder outputs, and what the next
8943 // frame predicts from.
8944 pick_and_apply_filters(
8945 &mut header,
8946 &mut luma,
8947 &mut chroma,
8948 [&picture_y8, &picture_u8, &picture_v8],
8949 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
8950 // and loop restoration off and codes none of their parameters
8951 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
8952 // the encoder's reconstruction is already what a decoder produces.
8953 !allow_intrabc,
8954 &mut tiles,
8955 search.lambda,
8956 fctx,
8957 // A key frame codes no 128x128 root block (the writer has no intra
8958 // path at that size), so every unit carries its own literal.
8959 &[],
8960 // Every re-code starts from this frame's OWN starting tables, never
8961 // from where the first write left them: the second tile is the same
8962 // symbol sequence plus new ones, so it must adapt from the same
8963 // point the decoder will.
8964 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
8965 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
8966 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
8967 crate::decode::decode_key_frame_tiles_lr(
8968 &payloads,
8969 &header_tile_info,
8970 h.mi_cols,
8971 h.mi_rows,
8972 base_q_idx,
8973 h.frame_width,
8974 h.frame_height,
8975 seq.enable_filter_intra,
8976 cdef,
8977 lf,
8978 tx_select,
8979 h.reduced_tx_set,
8980 h.allow_screen_content_tools,
8981 h.allow_intrabc,
8982 lr,
8983 fctx,
8984 )
8985 },
8986 )?;
8987 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
8988 header.tile_info.tile_size_bytes = tile_size_bytes;
8989 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
8990 let mut stream = temporal_delimiter();
8991 stream.extend_from_slice(&sequence_header_obu(&seq)?);
8992 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
8993
8994 let [u, v] = chroma;
8995 Ok(Encoded {
8996 stream,
8997 modes,
8998 inter_block_share: 0.0,
8999 reconstruction: Picture {
9000 width: luma.width,
9001 height: luma.height,
9002 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9003 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9004 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9005 },
9006 tile,
9007 mi_cols: header.mi_cols,
9008 mi_rows: header.mi_rows,
9009 base_q_idx,
9010 tx_select,
9011 // A key frame codes no inter block, so no motion_mode symbol.
9012 switchable_motion_mode: false,
9013 screen,
9014 reduced_tx_set: header.reduced_tx_set,
9015 next_cdfs: start_cdfs.clone(),
9016 start_cdfs,
9017 loop_filter: header.loop_filter,
9018 cdef: header.cdef,
9019 loop_restoration: header.loop_restoration,
9020 allow_intrabc,
9021 delta: header.delta.clone(),
9022 })
9023}
9024
9025/// Chooses this frame's deblocking levels and CDEF strengths, writes them
9026/// into `header` and
9027/// replaces the frame's own region of the encoder's reconstruction with the
9028/// filtered picture the decoder produced under them
9029/// ([`crate::filter_search::pick_deblock`]).
9030///
9031/// `search == false` leaves the header at level 0 (deblocking off) and the
9032/// reconstruction untouched: the caller's stream is one this crate's own
9033/// decoder cannot read back, so there is nothing to search against.
9034///
9035/// # Errors
9036/// The decoder's own error, when it refuses the tile the encoder just wrote
9037/// -- that is an encoder defect, not a filter one, so it is propagated
9038/// rather than swallowed into "no deblocking".
9039fn pick_and_apply_filters(
9040 header: &mut FrameHeader,
9041 luma: &mut Plane<'_>,
9042 chroma: &mut [Plane<'_>; 2],
9043 source: [&[u8]; 3],
9044 search: bool,
9045 // The coded tiles, one payload per tile of the frame's grid, replaced in
9046 // place when the search chooses a per-64x64 `cdef_idx` list
9047 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
9048 // tile is written a second time under `recode` and the winner
9049 // re-decoded from them.
9050 tiles: &mut Vec<Vec<u8>>,
9051 lambda: f64,
9052 fctx: &crate::decode::FrameCtx,
9053 // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles
9054 // carry -- empty (the identity map) for a frame whose every block covers
9055 // one 64x64 CDEF unit.
9056 cdef_owner: &[u32],
9057 recode: impl Fn(
9058 u8,
9059 usize,
9060 &[u8],
9061 &[Option<crate::restoration::WienerInfo>],
9062 ) -> Result<Vec<Vec<u8>>>,
9063 decode: impl Fn(
9064 &LoopFilterParams,
9065 &CdefParams,
9066 &FrameHeader,
9067 &[Vec<u8>],
9068 &LoopRestorationParams,
9069 ) -> Result<Picture>,
9070) -> Result<()> {
9071 if !search {
9072 return Ok(());
9073 }
9074 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
9075 let hdr = header.clone();
9076 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
9077 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
9078 let damping = 3 + (header.quantization.base_q_idx >> 6);
9079 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9080 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
9081 let none_lr = LoopRestorationParams::default();
9082 // Every candidate scores the same coded tile: decode it once and re-run
9083 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
9084 // the encoder's profile before this). The per-64x64 error the CDEF
9085 // preset search reads comes off the REPLAYED picture, which is the same
9086 // picture a decode produces -- that is what the replay is pinned on.
9087 crate::decode::clear_filter_replay();
9088 // lane-av1fpar: the per-tile search is over, so every core is idle from
9089 // here to the end of the frame -- band each candidate's deblock/CDEF
9090 // replay, the capture decode's own filter chain and the loop-restoration
9091 // passes across the same workers the search used.
9092 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
9093 let ft = crate::par::timer(crate::par::S_FILTER);
9094 let search_result = crate::filter_search::pick_filters(
9095 |lf, cdef| {
9096 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
9097 return Ok(picture);
9098 }
9099 crate::decode::arm_filter_replay();
9100 let _t = crate::par::timer(crate::par::S_FIRST);
9101 decode(lf, cdef, &hdr, tiles, &none_lr)
9102 },
9103 source,
9104 luma.width,
9105 (fw, fh),
9106 damping,
9107 (sb_cols, sb_rows),
9108 lambda,
9109 cdef_owner,
9110 );
9111 drop(ft);
9112 let (lf, cdef, idx_grid, picture) = search_result?;
9113 header.loop_filter = lf;
9114 header.cdef = cdef;
9115 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
9116 // in the frame header, so a re-decode under candidate parameters cannot
9117 // search them the way deblocking and CDEF are searched above. What the
9118 // decoder hands back instead is its own filter chain's intermediates
9119 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
9120 // those, through the decoder's own Wiener kernel.
9121 //
9122 // The capture rides the decode this stage was already going to do: the
9123 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
9124 // decode of the tile as it stands. That decode's header still says
9125 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
9126 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
9127 // an approximation inside the SEARCH only; the reconstruction this
9128 // function ends up splicing is always a real decode of the real tile.
9129 let lr_on = restoration_enabled();
9130 // The `cdef_idx` literals live in the tile payload, so a frame that
9131 // chose a per-64x64 preset list codes its tiles a second time.
9132 if !idx_grid.is_empty() {
9133 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
9134 }
9135 // lane-av1cap: that re-coded tile used to be DECODED here as well --
9136 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
9137 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
9138 // and the picture this function splices. Both come out of ONE more
9139 // replay of the winning parameters on the same captured pre-filter
9140 // planes every candidate was scored on: the same two filter kernels, on
9141 // the same input, in the same order, so the same bytes. Re-coding the
9142 // tile does not move the reconstruction the replay holds -- `cdef_idx`
9143 // is an equiprobable literal, so it adapts no CDF and changes no
9144 // residual.
9145 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
9146 #[cfg(test)]
9147 let replay_was_used = replayed.is_some();
9148 let (mut filtered, mut stages) = match replayed {
9149 Some((picture, stages)) => (picture, stages),
9150 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
9151 // refuses): every candidate was a full decode, so the winner's own
9152 // picture stands, and the stages still need a capturing decode.
9153 None => {
9154 fctx.capture_stages.set(lr_on);
9155 let picture = if idx_grid.is_empty() && !lr_on {
9156 picture
9157 } else {
9158 let _t = crate::par::timer(crate::par::S_CAPTURE);
9159 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
9160 };
9161 fctx.capture_stages.set(false);
9162 (picture, crate::decode::take_filter_stages(fctx))
9163 }
9164 };
9165 #[cfg(test)]
9166 if crate::decode::verify_final_replay() && replay_was_used {
9167 fctx.capture_stages.set(lr_on);
9168 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
9169 fctx.capture_stages.set(false);
9170 let want_stages = crate::decode::take_filter_stages(fctx);
9171 assert!(
9172 (want.width, want.height) == (filtered.width, filtered.height)
9173 && want.y == filtered.y
9174 && want.u == filtered.u
9175 && want.v == filtered.v,
9176 "the final filter replay is not the capture decode it stands in for",
9177 );
9178 // Only the frame's own cropped region: the plane is padded to the
9179 // superblock grid and the columns past the mi extent are written by
9180 // nothing (the decoder's plane pool leaves whatever the last frame
9181 // put there), while the restoration search reads strictly inside
9182 // `fw x fh` -- `restoration::lr_sample` clamps its column to
9183 // `plane_w - 1` and its row to the frame's, and
9184 // `filter_search::pick_restoration`'s own SSE walk never leaves the
9185 // crop either.
9186 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
9187 for row in 0..h {
9188 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
9189 assert!(
9190 x == y,
9191 "{what}: the replayed filter stages are not the ones the capture \
9192 decode returns (row {row} of {h}, width {w}, stride {stride})",
9193 );
9194 }
9195 };
9196 match (&want_stages, &stages) {
9197 (Some(a), Some(b)) => {
9198 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
9199 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9200 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
9201 region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked");
9202 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
9203 }
9204 }
9205 (None, None) => {}
9206 _ => panic!("one path captured filter stages and the other did not"),
9207 }
9208 }
9209 // lane-av1cap2: the capture stays live past the restoration search --
9210 // `crate::decode::replay_restoration` filters the same post-CDEF plane
9211 // rather than decoding the re-coded tile. Cleared at the end instead.
9212 let mut lr = LoopRestorationParams::default();
9213 if lr_on {
9214 let unit = lr_unit();
9215 let mut want = LoopRestorationParams {
9216 loop_restoration_size: [unit, unit, unit],
9217 uses_lr: true,
9218 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
9219 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
9220 lr_unit_shift: u8::from(unit == 128),
9221 ..LoopRestorationParams::default()
9222 };
9223 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
9224 let lrt = crate::par::timer(crate::par::S_LR);
9225 let units = match stages.take() {
9226 Some(stages) => crate::filter_search::pick_restoration(
9227 &stages,
9228 source[0],
9229 luma.width,
9230 (fw, fh),
9231 &want,
9232 lambda,
9233 fctx,
9234 ),
9235 None => Vec::new(),
9236 };
9237 // A frame no unit restores keeps `RESTORE_NONE` on every plane
9238 // rather than paying ~1 bit per 64x64 for a tile full of
9239 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
9240 // clip whose units never take a filter).
9241 drop(lrt);
9242 if units.iter().any(Option::is_some) {
9243 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
9244 let _t = crate::par::timer(crate::par::S_CAPTURE);
9245 // lane-av1cap2: that re-coded tile used to be DECODED here to
9246 // reach the restored reference frame -- 5.6% of a 4K frame,
9247 // for a filter that reads nothing of the tile but the per-unit
9248 // Wiener filters this stage just chose. Run the decoder's own
9249 // restoration kernel on the replay's post-CDEF plane instead
9250 // (`crate::decode::replay_restoration`), with the real
9251 // post-deblock stripe borders.
9252 match crate::decode::replay_restoration(&want, &units, fctx) {
9253 Some(y) => {
9254 #[cfg(test)]
9255 let margin = fctx
9256 .last_frame_wide_margin
9257 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
9258 #[cfg(test)]
9259 if crate::decode::verify_final_replay() {
9260 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
9261 assert!(
9262 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
9263 && want_pic.u == filtered.u
9264 && want_pic.v == filtered.v,
9265 "the restoration replay moved a chroma plane or the picture size",
9266 );
9267 assert!(
9268 want_pic.y == y,
9269 "the restoration replay is not the decode of the re-coded tile",
9270 );
9271 assert!(
9272 fctx.last_frame_wide_margin
9273 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
9274 == margin,
9275 "the restoration replay's wide-margin luma is not the decode's",
9276 );
9277 }
9278 filtered.y = y;
9279 }
9280 // Nothing captured: the winner came out of a full decode,
9281 // so this one does too.
9282 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
9283 }
9284 *tiles = coded;
9285 lr = want;
9286 }
9287 }
9288 crate::decode::clear_filter_replay();
9289 header.loop_restoration = lr;
9290 let dec_cw = filtered.width.div_ceil(2);
9291 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9292 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
9293 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
9294 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
9295 Ok(())
9296}
9297
9298/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
9299/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
9300/// since every block this crate's inter tile writer codes is 32x32.
9301const SIZE_GROUP_32: usize = 3;
9302
9303/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
9304/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
9305/// stack this encoder builds is ever asked to predict against.
9306const LAST_FRAME: i8 = 1;
9307
9308/// What an inter frame's intra branch spends to name each of the thirteen
9309/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
9310/// context, since an inter frame's intra blocks do not read their
9311/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
9312/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
9313/// state, so it is built once per frame.
9314fn inter_mode_bits() -> [f64; 13] {
9315 std::array::from_fn(|mode| {
9316 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
9317 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
9318 } else {
9319 0.0
9320 };
9321 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
9322 + angle
9323 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
9324 })
9325}
9326
9327/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
9328/// [`mc::predict`] takes, in the units of the plane it predicts into.
9329///
9330/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
9331/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
9332/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
9333/// domain. `luma` picks which.
9334fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
9335 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
9336}
9337
9338/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
9339/// that module): the magnitude an `MV_CLASS_n` component's own bits start
9340/// counting from.
9341fn mv_class_base(class: usize) -> i32 {
9342 if class == 0 { 0 } else { 2i32 << (class + 2) }
9343}
9344
9345/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
9346/// `tile::mv_class_of`.
9347fn mv_class_of(z: i32) -> usize {
9348 let mut class = 0;
9349 while class < 10 && mv_class_base(class + 1) <= z {
9350 class += 1;
9351 }
9352 class
9353}
9354
9355/// What [`crate::tile::write_mv_component`] (private to that module) would
9356/// spend coding one non-zero motion vector component, against the same
9357/// static default CDFs the writer starts a frame from — the same
9358/// static-table approximation [`mode_bits`] costs the luma mode symbol
9359/// through, not the tile writer's own adapting state, which this encoder has
9360/// no way to read without duplicating it block for block.
9361///
9362/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
9363/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
9364/// exists to avoid ever happening.
9365fn mv_component_bits(diff: i32) -> Option<f64> {
9366 let hp_frame = crate::tile::high_precision_mv();
9367 let mag = diff.unsigned_abs() as i32;
9368 let z = mag - 1;
9369 if !hp_frame && z & 1 == 0 {
9370 return None;
9371 }
9372 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
9373 let class = mv_class_of(z);
9374 bits += symbol_bits(&cdf::MV_CLASS, class);
9375 let local = z - mv_class_base(class);
9376 let hp = (local & 1) as usize;
9377 if class == 0 {
9378 let bit = (local >> 3) & 1;
9379 let fr = (local >> 1) & 3;
9380 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
9381 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
9382 // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
9383 // frame, so the pricer charges for it there and only there.
9384 if hp_frame {
9385 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
9386 }
9387 } else {
9388 let d = local >> 3;
9389 let fr = (local >> 1) & 3;
9390 for i in 0..class {
9391 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
9392 }
9393 bits += symbol_bits(&cdf::MV_FR, fr as usize);
9394 if hp_frame {
9395 bits += symbol_bits(&cdf::MV_HP, hp);
9396 }
9397 }
9398 Some(bits)
9399}
9400
9401/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
9402/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
9403/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
9404/// value without the second motion search's wall.
9405fn last2_new_mv() -> bool {
9406 match std::env::var("EC_AV1_LAST2_NEW").ok() {
9407 Some(v) => v != "0",
9408 None => true,
9409 }
9410}
9411
9412/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
9413/// own -- a second motion search per block against that reference's picture,
9414/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
9415/// off in a test build (what the lane measured both arms with).
9416fn extra_ref_new_mv() -> bool {
9417 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
9418 Some(v) if cfg!(test) => v != "0",
9419 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
9420 }
9421}
9422
9423/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
9424/// flat slot plan (`inter_frame_headers_slots`): every reference but
9425/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
9426/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
9427/// frame two back when there is one (otherwise it, too, names the key frame's
9428/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
9429pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
9430 let last = order_hint.wrapping_sub(1) & 0x7f;
9431 let alt = if has_altref {
9432 order_hint.wrapping_sub(2) & 0x7f
9433 } else {
9434 key_hint
9435 };
9436 [last, last, last, key_hint, last, last, alt]
9437}
9438
9439/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
9440/// header bit that lets each block choose between a single and a compound
9441/// reference. Off by default until compound prediction is measured to pay;
9442/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
9443/// runs as), and every block still codes SINGLE, so the only cost is one
9444/// `comp_mode` symbol per inter block.
9445pub(crate) const REFERENCE_SELECT: bool = true;
9446
9447/// [`REFERENCE_SELECT`], with the test-build environment override.
9448pub(crate) fn reference_select() -> bool {
9449 match std::env::var("EC_AV1_COMPOUND").ok() {
9450 Some(v) if cfg!(test) => v != "0",
9451 _ => crate::speed::at(&crate::speed::COMPOUND),
9452 }
9453}
9454
9455/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
9456/// per entry past `start`, `1` to advance and `0` to stop, at most two.
9457fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
9458 let mut bits = 0.0;
9459 let mut idx = start;
9460 while idx < start + 2 && stack.entries.len() > idx + 1 {
9461 let advance = idx < target;
9462 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
9463 if !advance {
9464 break;
9465 }
9466 idx += 1;
9467 }
9468 bits
9469}
9470
9471/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
9472/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
9473/// `assign_mv`), so the same vector costs a different residual from each.
9474fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
9475 let mut best: Option<(f64, u8)> = None;
9476 for idx in 0..3usize {
9477 if idx > 0 && stack.entries.len() <= idx {
9478 break;
9479 }
9480 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
9481 if let Some(b) = mv_residual_bits(mv, base) {
9482 let total = b + drl_bits_for(stack, 0, idx);
9483 if best.is_none_or(|(t, _)| total < t) {
9484 best = Some((total, idx as u8));
9485 }
9486 }
9487 }
9488 best
9489}
9490
9491/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
9492/// zero vector and the stack's own candidates. A neighbour block's vector is
9493/// where this block's motion most often already is, which is what pays for
9494/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
9495/// vs libaom for 0.2 s off a 6 s ladder).
9496fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
9497 let mut seeds = [(0, 0); 4];
9498 let mut n = 1;
9499 for e in stack.entries.iter().take(3) {
9500 seeds[n] = e.mv;
9501 n += 1;
9502 }
9503 (seeds, n)
9504}
9505
9506/// What [`crate::tile::write_mv`] (private to that module) would spend
9507/// coding `mv` as a residual against `pred`: the joint symbol naming which
9508/// components differ, then each differing component. `None` under the same
9509/// condition [`mv_component_bits`] returns `None`.
9510/// How many frames back `ref_frame` sits from the frame being coded, off the
9511/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
9512/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
9513/// what [`crate::motion::search`] scales its starting step by.
9514fn ref_distance(ref_frame: i8) -> u32 {
9515 let (bits, order_hint, hints) = crate::tile::order_hints();
9516 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
9517 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
9518 .unsigned_abs()
9519 .max(1);
9520 if crate::envflags::env_flag!("EC_TRACE_DIST") {
9521 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
9522 }
9523 d
9524}
9525
9526fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
9527 let diff = (mv.0 - pred.0, mv.1 - pred.1);
9528 let joint = match (diff.0 != 0, diff.1 != 0) {
9529 (false, false) => 0,
9530 (false, true) => 1,
9531 (true, false) => 2,
9532 (true, true) => 3,
9533 };
9534 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
9535 for d in [diff.0, diff.1] {
9536 if d != 0 {
9537 bits += mv_component_bits(d)?;
9538 }
9539 }
9540 Some(bits)
9541}
9542
9543/// Rounds `mv` so that its residual against `pred` is one
9544/// [`crate::tile::write_mv_component`] can actually code: each component's
9545/// difference is either zero or has an even magnitude (the eighth-pel bit
9546/// `allow_high_precision_mv` off always infers as one forces the coded
9547/// magnitude odd one step further in, which comes out even here since this
9548/// crate's motion search works in whole units of that same step). Rounding
9549/// down keeps every coded MV — and so every `nearest_mv` a later block's
9550/// stack votes with — built from an even displacement from `(0, 0)`, so the
9551/// invariant holds without this function seeing the whole stack.
9552/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
9553/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
9554/// always), the shape [`set_frame_interp`] has: the witness that has to see
9555/// `mv_hp` symbols coded turns it on through this while holding
9556/// [`crate::speed::knob_write`].
9557static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
9558
9559/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
9560#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
9561pub(crate) fn set_high_precision_mv(on: Option<bool>) {
9562 HP_MV_OVERRIDE.store(on.map_or(u8::MAX, u8::from), std::sync::atomic::Ordering::Relaxed);
9563}
9564
9565/// The qindex below which an inter frame codes `allow_high_precision_mv`
9566/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
9567/// crate's shipped value, i.e. high-precision motion vectors off in every
9568/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
9569pub(crate) const HP_MV_QTHRESH: u8 = 0;
9570
9571/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
9572/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
9573/// always, any number as the threshold) so the BD gate can sweep the policy
9574/// without a rebuild.
9575pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
9576 match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
9577 0 => return false,
9578 1 => return true,
9579 _ => {}
9580 }
9581 static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
9582 let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
9583 Some("all" | "always") => 256,
9584 Some("0" | "off") => 0,
9585 Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
9586 None => u16::from(HP_MV_QTHRESH),
9587 });
9588 u16::from(base_q_idx) < threshold
9589}
9590
9591fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
9592 // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
9593 // residual is codable and there is nothing to round away.
9594 if crate::tile::high_precision_mv() {
9595 return mv;
9596 }
9597 let round = |m: i32, p: i32| {
9598 let diff = m - p;
9599 let mag = diff.unsigned_abs() as i32;
9600 let even = mag - mag % 2;
9601 if even == 0 {
9602 p
9603 } else {
9604 p + even * diff.signum()
9605 }
9606 };
9607 (round(mv.0, pred.0), round(mv.1, pred.1))
9608}
9609
9610/// Predicts one `side`-square block by motion compensation from `reference`
9611/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
9612#[allow(clippy::too_many_arguments)]
9613fn mc_trial(
9614 plane: &Plane,
9615 x: usize,
9616 y: usize,
9617 side: usize,
9618 mv: (i32, i32),
9619 luma: bool,
9620 reference: &[u16],
9621 stride: usize,
9622 ref_width: usize,
9623 ref_height: usize,
9624 skip: bool,
9625 base_q_idx: u8,
9626 deadzone: f64,
9627 set: TxbSet,
9628 fctx: &crate::decode::FrameCtx,
9629) -> Trial {
9630 mc_trial_typed(
9631 plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx,
9632 deadzone, set, TxType::DctDct, fctx,
9633 )
9634}
9635
9636/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
9637#[allow(clippy::too_many_arguments)]
9638fn mc_trial_typed(
9639 plane: &Plane,
9640 x: usize,
9641 y: usize,
9642 side: usize,
9643 mv: (i32, i32),
9644 luma: bool,
9645 reference: &[u16],
9646 stride: usize,
9647 ref_width: usize,
9648 ref_height: usize,
9649 skip: bool,
9650 base_q_idx: u8,
9651 deadzone: f64,
9652 set: TxbSet,
9653 tx_type: TxType,
9654 fctx: &crate::decode::FrameCtx,
9655) -> Trial {
9656 let x_q4 = mv_to_q4(x, mv.1, luma);
9657 let y_q4 = mv_to_q4(y, mv.0, luma);
9658 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
9659 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
9660 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
9661 // lane-av1speed: both buffers are per-candidate scratch on the hottest
9662 // path in the encoder, so they live on the stack -- `side` is at most
9663 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
9664 // per motion-compensated trial otherwise.
9665 let mut prediction16 = [0u16; BLOCK * BLOCK];
9666 let prediction16 = &mut prediction16[..side * side];
9667 mc::predict(
9668 reference,
9669 stride,
9670 ref_width,
9671 ref_height,
9672 x_q4,
9673 y_q4,
9674 side,
9675 side,
9676 prediction16, fctx,
9677 );
9678 let mut prediction = [0u8; BLOCK * BLOCK];
9679 let prediction = &mut prediction[..side * side];
9680 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
9681 *dst = src as u8;
9682 }
9683 plane.code_from_prediction_typed(
9684 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
9685 )
9686}
9687
9688/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
9689/// references predict into the `CONV_BUF` intermediate domain
9690/// ([`mc::predict_compound_intermediate`]) and are blended by
9691/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
9692/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
9693/// block, so the encoder's reconstruction is the decoder's.
9694#[allow(clippy::too_many_arguments)]
9695fn mc_trial_compound(
9696 plane: &Plane,
9697 x: usize,
9698 y: usize,
9699 side: usize,
9700 mvs: ((i32, i32), (i32, i32)),
9701 luma: bool,
9702 ref0: (&[u16], usize, usize, usize),
9703 ref1: (&[u16], usize, usize, usize),
9704 base_q_idx: u8,
9705 deadzone: f64,
9706 set: TxbSet,
9707 fctx: &crate::decode::FrameCtx,
9708) -> Trial {
9709 mc_trial_compound_typed(
9710 plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx,
9711 )
9712}
9713
9714/// [`mc_trial_compound`] coding its residual with a named transform type
9715/// (lane-txset2).
9716#[allow(clippy::too_many_arguments)]
9717fn mc_trial_compound_typed(
9718 plane: &Plane,
9719 x: usize,
9720 y: usize,
9721 side: usize,
9722 (mv0, mv1): ((i32, i32), (i32, i32)),
9723 luma: bool,
9724 ref0: (&[u16], usize, usize, usize),
9725 ref1: (&[u16], usize, usize, usize),
9726 base_q_idx: u8,
9727 deadzone: f64,
9728 set: TxbSet,
9729 tx_type: TxType,
9730 fctx: &crate::decode::FrameCtx,
9731) -> Trial {
9732 let mut inter0 = [0i32; BLOCK * BLOCK];
9733 let mut inter1 = [0i32; BLOCK * BLOCK];
9734 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
9735 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
9736 mc::predict_compound_intermediate(
9737 r.0,
9738 r.1,
9739 r.2,
9740 r.3,
9741 mv_to_q4(x, mv.1, luma),
9742 mv_to_q4(y, mv.0, luma),
9743 mc::REF_NO_SCALE,
9744 side,
9745 side,
9746 fctx.interp_filter.get(),
9747 fctx.interp_filter.get(),
9748 dst, fctx,
9749 );
9750 }
9751 let mut blended16 = [0u16; BLOCK * BLOCK];
9752 let blended16 = &mut blended16[..side * side];
9753 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
9754 let mut prediction = [0u8; BLOCK * BLOCK];
9755 let prediction = &mut prediction[..side * side];
9756 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
9757 *dst = src as u8;
9758 }
9759 plane.code_from_prediction_typed(
9760 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
9761 )
9762}
9763
9764/// Codes one 32x32 block of an inter frame as whichever costs least of: each
9765/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
9766/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
9767/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
9768/// coding a real residual (`skip: false`) whenever one prices out cheaper
9769/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
9770/// missing inter `tx_type` symbol (the desync this function's candidates
9771/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
9772/// fixed.
9773///
9774/// The symbol costs this ranks candidates by use fixed contexts (0) for
9775/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
9776/// contexts for those come from its own neighbour bookkeeping
9777/// (`tile::Neighbours`), which is private to that module and not worth
9778/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
9779/// `drl_mode` contexts come straight from `stack`, which is exact, because
9780/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
9781/// the tile writer derives from the same grid state.
9782#[allow(clippy::too_many_arguments)]
9783/// One prediction of `side` x `side` samples from `reference`, as `u8` --
9784/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
9785/// four times the stack scratch that function sizes for [`BLOCK`].
9786fn predict_u8(
9787 reference: &[u16],
9788 stride: usize,
9789 ref_width: usize,
9790 ref_height: usize,
9791 (x, y): (usize, usize),
9792 side: usize,
9793 mv: (i32, i32),
9794 luma: bool,
9795 fctx: &crate::decode::FrameCtx,
9796) -> Vec<u8> {
9797 let mut prediction = vec![0u16; side * side];
9798 mc::predict(
9799 reference,
9800 stride,
9801 ref_width,
9802 ref_height,
9803 mv_to_q4(x, mv.1, luma),
9804 mv_to_q4(y, mv.0, luma),
9805 side,
9806 side,
9807 &mut prediction,
9808 fctx,
9809 );
9810 prediction.iter().map(|&v| v as u8).collect()
9811}
9812
9813/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
9814/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
9815/// references predict into the `CONV_BUF` intermediate domain and are blended
9816/// at the simple-average split `(8, 8)`, the same path (and so the same
9817/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
9818fn predict_compound_u8(
9819 ref0: (&[u16], usize, usize, usize),
9820 ref1: (&[u16], usize, usize, usize),
9821 (x, y): (usize, usize),
9822 side: usize,
9823 (mv0, mv1): ((i32, i32), (i32, i32)),
9824 luma: bool,
9825 fctx: &crate::decode::FrameCtx,
9826) -> Vec<u8> {
9827 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
9828 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
9829 mc::predict_compound_intermediate(
9830 r.0,
9831 r.1,
9832 r.2,
9833 r.3,
9834 mv_to_q4(x, mv.1, luma),
9835 mv_to_q4(y, mv.0, luma),
9836 mc::REF_NO_SCALE,
9837 side,
9838 side,
9839 fctx.interp_filter.get(),
9840 fctx.interp_filter.get(),
9841 dst, fctx,
9842 );
9843 }
9844 let mut blended = vec![0u16; side * side];
9845 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
9846 blended.iter().map(|&v| v as u8).collect()
9847}
9848
9849/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
9850/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
9851/// one motion vector where the four 64x64 roots below spend four of each.
9852///
9853/// SKIP only (`residual: false`): a 128x128 block's residual is four
9854/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
9855/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
9856/// path for -- offering one here would price a block
9857/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
9858/// the same reason: the compound arm at this size is untested against the
9859/// writer's own `write_compound_block` window.
9860///
9861/// Only a root whose whole 128x128 lies inside the true frame AND inside
9862/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
9863/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
9864/// block would have to be ranked over its inside part alone.
9865///
9866/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
9867/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
9868/// against the four superblocks plus the SPLIT symbol.
9869#[allow(clippy::too_many_arguments)]
9870fn search_root_128(
9871 luma: &mut Plane,
9872 chroma: &mut [Plane; 2],
9873 grid: &crate::mvstack::MiGrid,
9874 (root_r, root_c): (usize, usize),
9875 // The 32x32-block grid this tile's `blocks` vector is indexed on.
9876 (rows, cols): (usize, usize),
9877 // The frame's own mode-info grid, which bounds the root.
9878 (mi_cols, mi_rows): (u32, u32),
9879 search: Search<'_>,
9880 tpl_factors: &Option<Vec<f64>>,
9881 sb_q: Option<&Vec<u8>>,
9882 sb_cols: usize,
9883 tpl_cells_x: usize,
9884 base_q_idx: u8,
9885 // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
9886 // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
9887 dq_res: i32,
9888 reference: &Picture,
9889 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
9890 // built by the caller off the same grid the tile writer rebuilds its
9891 // stack from (empty unless the frame carries `reference_select` and
9892 // [`b128_compound`] is on).
9893 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9894 fctx: &crate::decode::FrameCtx,
9895) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
9896 const SIDE: usize = SUPERBLOCK * 2;
9897 const SIDE_MI: usize = SIDE / 4;
9898 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9899 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9900 if root_r * 2 + 3 >= rows
9901 || root_c * 2 + 3 >= cols
9902 || (mi_row + SIDE_MI) as u32 > mi_rows
9903 || (mi_col + SIDE_MI) as u32 > mi_cols
9904 || x128 + SIDE > luma.true_width
9905 || y128 + SIDE > luma.true_height
9906 {
9907 return None;
9908 }
9909 // One lambda for the whole root, the mean of what its four superblocks
9910 // would each be searched at -- the 128-vs-four comparison weighs one cost
9911 // against four, so both sides have to be priced at the same lambda (the
9912 // same rule the 64 root's own mean-of-sixteen tpl cells follows).
9913 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
9914 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
9915 (None, Some(f)) => {
9916 let mean = (0..16)
9917 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
9918 .sum::<f64>()
9919 / 16.0;
9920 search.lambda * mean
9921 }
9922 (None, None) => search.lambda,
9923 };
9924 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
9925 .iter()
9926 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9927 .sum::<f64>()
9928 / 4.0;
9929 // The qindex this root is really quantized at: the delta_q unit is the
9930 // 128 superblock, so the root's own top-left cell is the one coded
9931 // (lane-b128m), and the residual arm below has to quantize at exactly it.
9932 let root_search = Search {
9933 lambda,
9934 ..match sb_q {
9935 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
9936 None => search,
9937 }
9938 };
9939 let stack = find_mv_stack(
9940 grid,
9941 mi_row,
9942 mi_col,
9943 SIDE_MI,
9944 SIDE_MI,
9945 LAST_FRAME,
9946 mi_cols as usize,
9947 mi_rows as usize,
9948 );
9949 let base = snapshot(luma, chroma, (x128, y128), SIDE);
9950 let found = search_skip_64(
9951 luma,
9952 chroma,
9953 (x128, y128),
9954 (SIDE, SIDE),
9955 &root_search,
9956 false,
9957 reference,
9958 &stack,
9959 compound,
9960 fctx,
9961 );
9962 let (mut cost, mut block) = found?;
9963 if block.inter.is_some_and(|i| i.ref1.is_some()) {
9964 B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9965 }
9966 // lane-b128r: the same prediction with a REAL residual, priced against
9967 // the skip arm the search just committed to the planes (which IS the
9968 // winner's prediction, sample for sample). The block's residual is four
9969 // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
9970 // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
9971 // sides the forward network already reaches, never as one 128-point
9972 // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
9973 //
9974 // The four `txfm_partition` symbols the writer codes for them are not
9975 // priced, exactly as the 64 root does not price its own (their contexts
9976 // are only known at write time); at four symbols a root this is under a
9977 // bit against residuals of hundreds.
9978 if b128_residual() && block.skip {
9979 // Every unit's coded level grid is 32x32 (a 64-point transform codes
9980 // only its top-left corner), packed per plane into one 64-wide grid
9981 // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
9982 // `write_inter_block_128` slices back out in the same chunk order.
9983 let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
9984 let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
9985 let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
9986 for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
9987 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9988 let (cx, cy) = (px / 2, py / 2);
9989 let half = SUPERBLOCK / 2;
9990 let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
9991 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
9992 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
9993 sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
9994 + chroma[0].block_sse(cx, cy, half, &pred_u)
9995 + chroma[1].block_sse(cx, cy, half, &pred_v);
9996 let trials = [
9997 luma.code_from_prediction(
9998 px, py, SUPERBLOCK, &pred_y, false, root_search.base_q_idx,
9999 root_search.deadzone, TxbSet::Luma64,
10000 ),
10001 chroma[0].code_from_prediction(
10002 cx, cy, half, &pred_u, false, root_search.base_q_idx,
10003 root_search.deadzone, TxbSet::Chroma32,
10004 ),
10005 chroma[1].code_from_prediction(
10006 cx, cy, half, &pred_v, false, root_search.base_q_idx,
10007 root_search.deadzone, TxbSet::Chroma32,
10008 ),
10009 ];
10010 for (plane, trial) in trials.iter().enumerate() {
10011 sse_res += trial.sse;
10012 coeff_bits += trial.bits;
10013 for row in 0..32 {
10014 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10015 .copy_from_slice(&trial.levels[row * 32..][..32]);
10016 }
10017 }
10018 chunks.push(((cr, cc), trials));
10019 }
10020 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
10021 // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
10022 // coefficients.
10023 let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
10024 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10025 if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
10026 B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10027 for ((cr, cc), trials) in &chunks {
10028 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10029 let half = SUPERBLOCK / 2;
10030 luma.commit(px, py, SUPERBLOCK, &trials[0]);
10031 chroma[0].commit(px / 2, py / 2, half, &trials[1]);
10032 chroma[1].commit(px / 2, py / 2, half, &trials[2]);
10033 }
10034 cost = res_cost;
10035 block.skip = false;
10036 block.tx_depth = 0;
10037 block.luma_tx_types = Vec::new();
10038 block.luma = coeffs(&packed[0], 64);
10039 block.u = coeffs(&packed[1], 64);
10040 block.v = coeffs(&packed[2], 64);
10041 }
10042 }
10043 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10044 restore(luma, chroma, (x128, y128), SIDE, &base);
10045 // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
10046 // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
10047 // residual arm above codes it like every other block does.
10048 let dq = if block.skip {
10049 0.0
10050 } else {
10051 delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
10052 };
10053 Some((
10054 cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
10055 lambda,
10056 block,
10057 after,
10058 ))
10059}
10060
10061/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
10062/// arm the caller's [`search_skip_64`] just committed to the planes (which
10063/// IS the winner's prediction, sample for sample -- the same rule
10064/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
10065/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
10066/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
10067/// each trial at sides the forward network already reaches, never a
10068/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
10069/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
10070///
10071/// The depth-0 `txfm_partition` symbols the writer codes for the units are
10072/// not priced, exactly as [`search_root_128`] does not price its four (their
10073/// contexts are only known at write time); at two symbols a half this is
10074/// under a bit against residuals of hundreds. On a win (or under the witness
10075/// force) the trials are committed to the planes, `block` is flipped to
10076/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
10077/// slices back out, and the new cost is returned; otherwise `cost` passes
10078/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
10079#[allow(clippy::too_many_arguments)]
10080fn search_rect_residual(
10081 luma: &mut Plane,
10082 chroma: &mut [Plane; 2],
10083 // The piece's own top-left, in luma samples.
10084 (px, py): (usize, usize),
10085 // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
10086 (w, h): (usize, usize),
10087 cost: f64,
10088 lambda: f64,
10089 search: &Search<'_>,
10090 // The piece's own mv stack, for the skip symbol's cost either way.
10091 stack: &crate::mvstack::MvStack,
10092 block: &mut BlockCoeffs,
10093) -> f64 {
10094 /// The 64x64 "mu" chunk side, luma; chroma halves it.
10095 const MU: usize = SUPERBLOCK;
10096 let chunks: [(usize, usize); 2] = match (w, h) {
10097 (128, 64) => [(0, 0), (0, 1)],
10098 (64, 128) => [(0, 0), (1, 0)],
10099 _ => [(0, 0), (0, 0)],
10100 };
10101 let n = if w.max(h) > MU { 2 } else { 1 };
10102 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10103 // only its top-left corner), packed per plane into one 64-wide grid with
10104 // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
10105 // back out in the same chunk order.
10106 let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
10107 let mut sse_skip = 0.0f64;
10108 let mut sse_res = 0.0f64;
10109 let mut coeff_bits = 0.0f64;
10110 let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
10111 for &(cr, cc) in &chunks[..n] {
10112 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10113 let (cx, cy) = (cxx / 2, cyy / 2);
10114 let half = MU / 2;
10115 let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
10116 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10117 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10118 sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
10119 + chroma[0].block_sse(cx, cy, half, &pred_u)
10120 + chroma[1].block_sse(cx, cy, half, &pred_v);
10121 let trials = [
10122 luma.code_from_prediction(
10123 cxx, cyy, MU, &pred_y, false, search.base_q_idx, search.deadzone,
10124 TxbSet::Luma64,
10125 ),
10126 chroma[0].code_from_prediction(
10127 cx, cy, half, &pred_u, false, search.base_q_idx, search.deadzone,
10128 TxbSet::Chroma32,
10129 ),
10130 chroma[1].code_from_prediction(
10131 cx, cy, half, &pred_v, false, search.base_q_idx, search.deadzone,
10132 TxbSet::Chroma32,
10133 ),
10134 ];
10135 for (plane, trial) in trials.iter().enumerate() {
10136 sse_res += trial.sse;
10137 coeff_bits += trial.bits;
10138 for row in 0..32 {
10139 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10140 .copy_from_slice(&trial.levels[row * 32..][..32]);
10141 }
10142 }
10143 trials_per_chunk.push(trials);
10144 }
10145 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
10146 // pays the same syntax with `skip` coded 0 instead of 1, plus its
10147 // coefficients.
10148 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10149 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10150 if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
10151 for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
10152 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10153 let (cx, cy) = (cxx / 2, cyy / 2);
10154 let half = MU / 2;
10155 luma.commit(cxx, cyy, MU, &trials[0]);
10156 chroma[0].commit(cx, cy, half, &trials[1]);
10157 chroma[1].commit(cx, cy, half, &trials[2]);
10158 }
10159 block.skip = false;
10160 block.tx_depth = 0;
10161 block.luma_tx_types = Vec::new();
10162 block.luma = coeffs(&packed[0], 64);
10163 block.u = coeffs(&packed[1], 64);
10164 block.v = coeffs(&packed[2], 64);
10165 B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10166 res_cost
10167 } else {
10168 cost
10169 }
10170}
10171
10172/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
10173/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
10174/// shipped NONE machinery halved. Skip-only by default, single reference or
10175/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
10176/// ([`search_rect_residual`]) -- exactly what
10177/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
10178/// reads at `sb128_rect`.
10179///
10180/// The FIRST half is published into `grid` before the second is searched --
10181/// the writer publishes it too, so a second half searched against the stale
10182/// grid would be priced (and its mv predicted) off a stack the decoder never
10183/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
10184/// both planes are put back before returning; the caller re-applies the
10185/// winner.
10186///
10187/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
10188/// carrying the root's own partition symbol so it ranks against
10189/// [`search_root_128`] and against the four superblocks below.
10190#[allow(clippy::too_many_arguments)]
10191fn search_root_128_rect(
10192 luma: &mut Plane,
10193 chroma: &mut [Plane; 2],
10194 grid: &mut crate::mvstack::MiGrid,
10195 (root_r, root_c): (usize, usize),
10196 (rows, cols): (usize, usize),
10197 (mi_cols, mi_rows): (u32, u32),
10198 search: Search<'_>,
10199 tpl_factors: &Option<Vec<f64>>,
10200 sb_q: Option<&Vec<u8>>,
10201 sb_cols: usize,
10202 tpl_cells_x: usize,
10203 base_q_idx: u8,
10204 // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
10205 dq_res: i32,
10206 reference: &Picture,
10207 // The `LAST` + extra-reference pairs offered at this root; only the
10208 // reference and its picture are read here, since each HALF derives its
10209 // own compound stack at its own rectangular window.
10210 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10211 horz: bool,
10212 fctx: &crate::decode::FrameCtx,
10213) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10214 const SIDE: usize = SUPERBLOCK * 2;
10215 const SIDE_MI: usize = SIDE / 4;
10216 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10217 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10218 if root_r * 2 + 3 >= rows
10219 || root_c * 2 + 3 >= cols
10220 || (mi_row + SIDE_MI) as u32 > mi_rows
10221 || (mi_col + SIDE_MI) as u32 > mi_cols
10222 || x128 + SIDE > luma.true_width
10223 || y128 + SIDE > luma.true_height
10224 {
10225 return None;
10226 }
10227 // The root's own lambda, the mean of its four superblocks' -- the same
10228 // one [`search_root_128`] prices with, so the three root candidates and
10229 // the four-superblock arm are all comparable.
10230 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10231 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10232 (None, Some(f)) => {
10233 let mean = (0..16)
10234 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10235 .sum::<f64>()
10236 / 16.0;
10237 search.lambda * mean
10238 }
10239 (None, None) => search.lambda,
10240 };
10241 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10242 .iter()
10243 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10244 .sum::<f64>()
10245 / 4.0;
10246 let root_search = Search {
10247 lambda,
10248 ..match sb_q {
10249 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10250 None => search,
10251 }
10252 };
10253 let (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) };
10254 let (w_mi, h_mi) = (w / 4, h / 4);
10255 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10256 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10257 let mut cost = 0.0f64;
10258 let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
10259 for i in 0..2usize {
10260 let (mr, mc) = if horz {
10261 (mi_row + i * 16, mi_col)
10262 } else {
10263 (mi_row, mi_col + i * 16)
10264 };
10265 let stack = find_mv_stack(
10266 grid,
10267 mr,
10268 mc,
10269 w_mi,
10270 h_mi,
10271 LAST_FRAME,
10272 mi_cols as usize,
10273 mi_rows as usize,
10274 );
10275 let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10276 .iter()
10277 .map(|&(r, pic, _)| {
10278 (
10279 r,
10280 pic,
10281 crate::mvstack::find_mv_stack_compound(
10282 grid,
10283 mr,
10284 mc,
10285 w_mi,
10286 h_mi,
10287 (LAST_FRAME, r),
10288 mi_cols as usize,
10289 mi_rows as usize,
10290 grid.sign_bias_table(),
10291 &[(0, 0); 7],
10292 None,
10293 ),
10294 )
10295 })
10296 .collect();
10297 let found = search_skip_64(
10298 luma,
10299 chroma,
10300 (mc * 4, mr * 4),
10301 (w, h),
10302 &root_search,
10303 false,
10304 reference,
10305 &stack,
10306 &half_compound,
10307 fctx,
10308 );
10309 match found {
10310 Some((mut c, mut block)) => {
10311 // lane-rectres: the same prediction with a REAL residual,
10312 // priced against the skip arm the search just committed to
10313 // the planes -- two 64x64 mu chunks for a half.
10314 if rectres() && block.skip {
10315 c = search_rect_residual(
10316 luma,
10317 chroma,
10318 (mc * 4, mr * 4),
10319 (w, h),
10320 c,
10321 root_search.lambda,
10322 &root_search,
10323 &stack,
10324 &mut block,
10325 );
10326 }
10327 cost += c;
10328 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10329 halves.push(block);
10330 }
10331 None => {
10332 restore(luma, chroma, (x128, y128), SIDE, &base);
10333 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10334 return None;
10335 }
10336 }
10337 }
10338 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10339 restore(luma, chroma, (x128, y128), SIDE, &base);
10340 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10341 let symbol = if horz { 1 } else { 2 };
10342 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
10343 // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
10344 // codes the delta_q group whether it is skipped or not
10345 // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
10346 // half is at a non-origin mi and codes none.
10347 let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
10348 Some((
10349 cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
10350 lambda,
10351 [b0, b1],
10352 after,
10353 ))
10354}
10355
10356/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
10357/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
10358/// decoder's own). Each piece is priced through the same `search_skip_64`
10359/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
10360/// into `grid` before the next is searched -- the writer publishes it too, so
10361/// a later piece searched against a stale grid would be priced (and its mv
10362/// predicted) off a stack the decoder never derives (class
10363/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
10364/// are put back before returning; the caller re-applies the winner.
10365///
10366/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
10367/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
10368/// libaom's own AB shapes earn their keep.
10369///
10370/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
10371/// already carrying the root's own partition symbol so it ranks against the
10372/// other root candidates and against the four superblocks below.
10373#[allow(clippy::too_many_arguments)]
10374fn search_root_128_ab(
10375 luma: &mut Plane,
10376 chroma: &mut [Plane; 2],
10377 grid: &mut crate::mvstack::MiGrid,
10378 (root_r, root_c): (usize, usize),
10379 (rows, cols): (usize, usize),
10380 (mi_cols, mi_rows): (u32, u32),
10381 search: Search<'_>,
10382 tpl_factors: &Option<Vec<f64>>,
10383 sb_q: Option<&Vec<u8>>,
10384 sb_cols: usize,
10385 tpl_cells_x: usize,
10386 base_q_idx: u8,
10387 reference: &Picture,
10388 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10389 // The partition symbol, 4..=7.
10390 symbol: usize,
10391 fctx: &crate::decode::FrameCtx,
10392) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10393 const SIDE: usize = SUPERBLOCK * 2;
10394 const SIDE_MI: usize = SIDE / 4;
10395 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10396 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10397 if root_r * 2 + 3 >= rows
10398 || root_c * 2 + 3 >= cols
10399 || (mi_row + SIDE_MI) as u32 > mi_rows
10400 || (mi_col + SIDE_MI) as u32 > mi_cols
10401 || x128 + SIDE > luma.true_width
10402 || y128 + SIDE > luma.true_height
10403 {
10404 return None;
10405 }
10406 // The root's own lambda, the mean of its four superblocks' -- the same one
10407 // [`search_root_128`] prices with, so every root candidate and the
10408 // four-superblock arm are comparable.
10409 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10410 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10411 (None, Some(f)) => {
10412 let mean = (0..16)
10413 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10414 .sum::<f64>()
10415 / 16.0;
10416 search.lambda * mean
10417 }
10418 (None, None) => search.lambda,
10419 };
10420 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10421 .iter()
10422 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10423 .sum::<f64>()
10424 / 4.0;
10425 let root_search = Search {
10426 lambda,
10427 ..match sb_q {
10428 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10429 None => search,
10430 }
10431 };
10432 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10433 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10434 let mut cost = 0.0f64;
10435 let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
10436 for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
10437 let (w_mi, h_mi) = (w / 4, h / 4);
10438 let stack = find_mv_stack(
10439 grid,
10440 mr,
10441 mc,
10442 w_mi,
10443 h_mi,
10444 LAST_FRAME,
10445 mi_cols as usize,
10446 mi_rows as usize,
10447 );
10448 let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10449 .iter()
10450 .map(|&(r, pic, _)| {
10451 (
10452 r,
10453 pic,
10454 crate::mvstack::find_mv_stack_compound(
10455 grid,
10456 mr,
10457 mc,
10458 w_mi,
10459 h_mi,
10460 (LAST_FRAME, r),
10461 mi_cols as usize,
10462 mi_rows as usize,
10463 grid.sign_bias_table(),
10464 &[(0, 0); 7],
10465 None,
10466 ),
10467 )
10468 })
10469 .collect();
10470 let found = search_skip_64(
10471 luma,
10472 chroma,
10473 (mc * 4, mr * 4),
10474 (w, h),
10475 &root_search,
10476 false,
10477 reference,
10478 &stack,
10479 &piece_compound,
10480 fctx,
10481 );
10482 match found {
10483 Some((mut c, mut block)) => {
10484 // lane-rectres: the same prediction with a REAL residual,
10485 // priced against the skip arm the search just committed to
10486 // the planes -- one mu chunk for a 64x64 square, two for a
10487 // half. The 64x64 squares are where libaom's own AB shapes
10488 // earn their keep.
10489 if rectres() && block.skip {
10490 c = search_rect_residual(
10491 luma,
10492 chroma,
10493 (mc * 4, mr * 4),
10494 (w, h),
10495 c,
10496 root_search.lambda,
10497 &root_search,
10498 &stack,
10499 &mut block,
10500 );
10501 }
10502 cost += c;
10503 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10504 pieces.push(block);
10505 }
10506 None => {
10507 restore(luma, chroma, (x128, y128), SIDE, &base);
10508 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10509 return None;
10510 }
10511 }
10512 }
10513 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10514 restore(luma, chroma, (x128, y128), SIDE, &base);
10515 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10516 let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
10517 Some((
10518 cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
10519 lambda,
10520 [b0, b1, b2],
10521 after,
10522 ))
10523}
10524
10525/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
10526/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
10527/// SKIP, priced through the same `symbol_bits` path every other candidate
10528/// uses. The winner's prediction is committed to the planes (it IS the
10529/// reconstruction -- a skip block has no residual); the caller restores them
10530/// if the four quadrants come out cheaper.
10531///
10532/// `None` when no candidate could be coded at all (a `NEWMV` residual the
10533/// writer cannot name is simply not offered, and the other modes always are,
10534/// so this only happens if every candidate is refused).
10535fn search_skip_64(
10536 luma: &mut Plane,
10537 chroma: &mut [Plane; 2],
10538 (x, y): (usize, usize),
10539 // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
10540 // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
10541 // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
10542 // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
10543 // side (one square when it is square, two otherwise), and the residual
10544 // arm is only ever asked for at 64 -- a 128 block's residual is four
10545 // TX_64X64 units the writer has no path for.
10546 (bw, bh): (usize, usize),
10547 search: &Search,
10548 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
10549 // screen content -- see that function's doc).
10550 residual: bool,
10551 reference: &Picture,
10552 stack: &MvStack,
10553 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
10554 // superblock's 16x16-mi window, built off the same grid the tile writer
10555 // rebuilds it from (empty unless the frame carries `reference_select`).
10556 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10557 fctx: &crate::decode::FrameCtx,
10558) -> Option<(f64, BlockCoeffs)> {
10559 debug_assert!(
10560 (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
10561 "only a 64 root has a residual arm"
10562 );
10563 // The square units every trial below is taken on: the block itself when
10564 // it is square, its two halves otherwise. Luma first (in raster order),
10565 // then each chroma plane over the same tiling at half the side -- which is
10566 // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
10567 let sq = bw.min(bh);
10568 let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
10569 .flat_map(|plane| {
10570 let (ox, oy, s) = if plane == 0 { (x, y, sq) } else { (x / 2, y / 2, sq / 2) };
10571 (0..bh / sq).flat_map(move |j| {
10572 (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
10573 })
10574 })
10575 .collect();
10576 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
10577 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
10578 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
10579 // What every candidate pays whatever its vector: `skip` coded 1, then
10580 // `is_inter` coded 1, then the LAST chain above.
10581 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
10582 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
10583 ref1: None,
10584 mv1: (0, 0),
10585 ref_frame: crate::mvstack::LAST_FRAME,
10586 mode,
10587 mv,
10588 ref_mv_idx,
10589 };
10590 let mut cands: Vec<(f64, InterInfo)> = vec![
10591 (
10592 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
10593 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
10594 ),
10595 (
10596 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
10597 info_of(InterMode::GlobalMv, (0, 0), 0),
10598 ),
10599 ];
10600 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
10601 for idx in 1..=2usize {
10602 if let Some(e) = stack.entries.get(idx) {
10603 cands.push((
10604 near_bits + drl_bits_for(stack, 1, idx),
10605 info_of(InterMode::NearMv, e.mv, idx as u8),
10606 ));
10607 }
10608 }
10609 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
10610 // candidate below to pair with the second reference's NEAREST half.
10611 let mut last_new_mv: Option<(i32, i32)> = None;
10612 if leaf_new_mv() {
10613 let source_block = luma.source_block_rect(x, y, bw, bh);
10614 let (seeds, seed_n) = mv_seeds(stack);
10615 let found = motion::search(
10616 &reference.y,
10617 reference.width,
10618 luma.true_width,
10619 luma.true_height,
10620 &source_block,
10621 x,
10622 y,
10623 bw,
10624 bh,
10625 stack.pred_mv,
10626 &seeds[..seed_n],
10627 search.lambda,
10628 fctx,
10629 1,
10630 );
10631 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
10632 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
10633 last_new_mv = Some(mv);
10634 cands.push((
10635 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
10636 info_of(InterMode::NewMv, mv, ref_mv_idx),
10637 ));
10638 }
10639 }
10640
10641 let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
10642 for (bits, info) in cands {
10643 let trials: Vec<Trial> = units
10644 .iter()
10645 .map(|&(plane, px, py, s, is_luma)| {
10646 let (samples, stride, w, h) = match plane {
10647 0 => (&reference.y, reference.width, luma.true_width, luma.true_height),
10648 1 => (
10649 &reference.u,
10650 reference.width / 2,
10651 chroma[0].true_width,
10652 chroma[0].true_height,
10653 ),
10654 _ => (
10655 &reference.v,
10656 reference.width / 2,
10657 chroma[1].true_width,
10658 chroma[1].true_height,
10659 ),
10660 };
10661 let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
10662 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
10663 // `skip` true: the trial is the prediction itself plus its SSE,
10664 // so no transform of any size is involved (the reason a 64x64
10665 // root can be coded at all before a forward TX_64X64 exists).
10666 target.code_from_prediction(
10667 px,
10668 py,
10669 s,
10670 &prediction,
10671 true,
10672 search.base_q_idx,
10673 search.deadzone,
10674 TxbSet::Luma32Inter,
10675 )
10676 })
10677 .collect();
10678 let cost =
10679 trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
10680 if best.as_ref().is_none_or(|b| cost < b.0) {
10681 best = Some((cost, fixed + bits, info, trials));
10682 }
10683 }
10684
10685 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
10686 // superblock can form without a second motion search ([`b64_compound`]),
10687 // priced through the same `symbol_bits` path -- `fixed` minus the single
10688 // reference's tree, plus the pair tree and the compound mode.
10689 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
10690 let (ref1, g) = (*ref1, *g);
10691 // The whole `comp_mode` + reference-pair tree at the writer's own
10692 // contexts, for THIS pair (lane-ctx).
10693 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
10694 let mode_ctx =
10695 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
10696 let mode_bits_of =
10697 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
10698 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
10699 ref1: Some(ref1),
10700 mv1: mvs.1,
10701 ref_frame: crate::mvstack::LAST_FRAME,
10702 mode,
10703 mv: mvs.0,
10704 ref_mv_idx: 0,
10705 };
10706 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
10707 (
10708 cstack.nearest_mv,
10709 mode_bits_of(0),
10710 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
10711 ),
10712 (
10713 ((0, 0), (0, 0)),
10714 mode_bits_of(6),
10715 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
10716 ),
10717 ];
10718 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
10719 // above, its residual priced against compound stack entry 0 -- what
10720 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
10721 let cbase = cstack
10722 .entries
10723 .first()
10724 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
10725 if let Some(new_mv) = last_new_mv
10726 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
10727 {
10728 let mvs = (new_mv, cstack.nearest_mv.1);
10729 ccands.push((
10730 mvs,
10731 mode_bits_of(3) + b0,
10732 compound_info(InterMode::NewNearestMv, mvs),
10733 ));
10734 }
10735 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
10736 ccands.dedup_by_key(|c| c.0);
10737 for (mvs, bits, info) in ccands {
10738 let trials: Vec<Trial> = units
10739 .iter()
10740 .map(|&(plane, px, py, s, is_luma)| {
10741 let (r0, r1) = match plane {
10742 0 => (
10743 (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height),
10744 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10745 ),
10746 1 => (
10747 (
10748 reference.u.as_slice(),
10749 reference.width / 2,
10750 chroma[0].true_width,
10751 chroma[0].true_height,
10752 ),
10753 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
10754 ),
10755 _ => (
10756 (
10757 reference.v.as_slice(),
10758 reference.width / 2,
10759 chroma[1].true_width,
10760 chroma[1].true_height,
10761 ),
10762 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
10763 ),
10764 };
10765 let prediction =
10766 predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
10767 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
10768 target.code_from_prediction(
10769 px,
10770 py,
10771 s,
10772 &prediction,
10773 true,
10774 search.base_q_idx,
10775 search.deadzone,
10776 TxbSet::Luma32Inter,
10777 )
10778 })
10779 .collect();
10780 let syntax = fixed - ref_bits + bits;
10781 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
10782 if best.as_ref().is_none_or(|b| cost < b.0) {
10783 best = Some((cost, syntax, info, trials));
10784 }
10785 }
10786 }
10787
10788 let (skip_cost, syntax, info, skip_trials) = best?;
10789
10790 // The winner's prediction coded with a REAL residual (lane-tx64): one
10791 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
10792 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
10793 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
10794 // the skip arm already chose is re-coded: the prediction with the lowest
10795 // SSE is also the cheapest residual to code, and a second 64x64 motion
10796 // search per superblock is the wall this root was taken to SAVE.
10797 //
10798 // Priced against the skip arm through the same `symbol_bits` path, so the
10799 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
10800 // arm charges 0 instead and adds its three planes' coefficient bits.
10801 let mut chosen = (skip_cost, true, skip_trials);
10802 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
10803 // into the plane, so the tail below does not commit over its units.
10804 let mut luma_committed = false;
10805 // The residual arm's luma levels and the `txfm_split` depth the writer
10806 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
10807 // four TX_32X32 units in 64x64 ones.
10808 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
10809 if residual {
10810 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
10811 // Square by construction (the `debug_assert` above), so `units` is
10812 // one entry per plane and `chosen.2[plane]` is that plane's trial.
10813 let residual_trials = [0usize, 1, 2].map(|plane| {
10814 let (target, px, py, s) = if plane == 0 {
10815 (&*luma, x, y, bw)
10816 } else {
10817 (&chroma[plane - 1], x / 2, y / 2, bw / 2)
10818 };
10819 target.code_from_prediction(
10820 px,
10821 py,
10822 s,
10823 &chosen.2[plane].reconstruction,
10824 false,
10825 search.base_q_idx,
10826 search.deadzone,
10827 sets[plane],
10828 )
10829 });
10830 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10831 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
10832 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
10833 // four TX_32X32 units of `txfm_split = 1`, taken by the same
10834 // `commit_inter_luma` every other inter block's is (it commits the
10835 // winner and hands back the cost it took off the flat arm).
10836 let (levels, depth, gain, tx_types) = if b64_var_tx() {
10837 let second = info.ref1.and_then(|r1| {
10838 compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| {
10839 (
10840 info.mv1,
10841 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10842 )
10843 })
10844 });
10845 luma_committed = true;
10846 commit_inter_luma(
10847 luma,
10848 (x, y),
10849 bw,
10850 info.mv,
10851 (&reference.y, reference.width, luma.true_width, luma.true_height),
10852 search,
10853 &residual_trials[0],
10854 false,
10855 second,
10856 fctx,
10857 )
10858 } else {
10859 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
10860 };
10861 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
10862 + search.lambda * (syntax + unskip + coeff_bits)
10863 + gain;
10864 if cost < skip_cost {
10865 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10866 if depth == 1 {
10867 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10868 }
10869 luma_levels = Some((levels, depth, tx_types));
10870 chosen = (cost, false, residual_trials.to_vec());
10871 }
10872 }
10873
10874 let (cost, skip, trials) = chosen;
10875 // `commit_inter_luma` already wrote the residual arm's luma (its four
10876 // split units are not one 64-sided trial); a skip winner overwrites it.
10877 for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
10878 match plane {
10879 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
10880 0 => {}
10881 _ => chroma[plane - 1].commit(px, py, s, trial),
10882 }
10883 }
10884 Some((
10885 cost,
10886 BlockCoeffs {
10887 skip,
10888 inter: Some(info),
10889 // The chroma grids are whole TX_32X32; the luma one is the
10890 // 64-point transform's coded 32x32 corner at depth 0 and the
10891 // whole 64-sided block at depth 1 (lane-b64b).
10892 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
10893 luma_tx_types: match (skip, &luma_levels) {
10894 (false, Some((_, _, types))) => types.clone(),
10895 _ => Vec::new(),
10896 },
10897 luma: match (skip, &luma_levels) {
10898 (true, _) => Vec::new(),
10899 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
10900 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
10901 (false, None) => coeffs(&trials[0].levels, BLOCK),
10902 },
10903 u: if skip { Vec::new() } else { coeffs(&trials[1].levels, bw / 2) },
10904 v: if skip { Vec::new() } else { coeffs(&trials[2].levels, bw / 2) },
10905 ..BlockCoeffs::default()
10906 },
10907 ))
10908}
10909
10910fn search_inter_block(
10911 luma: &mut Plane,
10912 chroma: &mut [Plane; 2],
10913 (x, y): (usize, usize),
10914 search: &Search,
10915 mode_bits: &[f64; 13],
10916 reference: &Picture,
10917 stack: &MvStack,
10918 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
10919 // for the whole GOP, with the stack this block derives against it. Only
10920 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
10921 // second motion search would double the wall of the stage that already
10922 // owns most of it.
10923 extra: &[(i8, &Picture, &MvStack)],
10924 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
10925 // the caller off the same MI grid the tile writer will (empty unless the
10926 // frame carries `reference_select`).
10927 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10928 // lane-av1obmc: the mi grid this search's neighbours were published into
10929 // (`record_mi`) and this block's own place in it -- what the OBMC
10930 // candidate's eligibility walk and neighbour plan read, the same state
10931 // the tile writer will read when it codes the `motion_mode` symbol.
10932 grid: &MiGrid,
10933 (mi_row, mi_col): (usize, usize),
10934 (mi_rows, mi_cols): (usize, usize),
10935 fctx: &crate::decode::FrameCtx,
10936) -> (BlockCoeffs, f64) {
10937 // `luma_set` is the INTRA candidates' table; the two inter candidates
10938 // below price their coefficients through `TxbSet::Luma32Inter`, which is
10939 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
10940 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
10941 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
10942 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
10943
10944 // skip / intra_inter symbol costs at a fixed context -- see this
10945 // function's doc comment.
10946 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
10947 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
10948
10949 struct Candidate {
10950 cost: f64,
10951 luma: Trial,
10952 u: Trial,
10953 v: Trial,
10954 mode: u8,
10955 skip: bool,
10956 inter: Option<InterInfo>,
10957 /// The mode/mv syntax this candidate pays for, apart from its
10958 /// residual -- what the OBMC candidate below has to re-pay when it
10959 /// re-prices the winner's prediction.
10960 mode_bits: f64,
10961 }
10962 let mut best: Option<Candidate> = None;
10963 let mut consider = |candidate: Candidate| {
10964 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
10965 best = Some(candidate);
10966 }
10967 };
10968
10969 // The chroma trial an intra candidate prices does not depend on `mode`
10970 // at all -- both planes always code `DC_PRED` here (a coding choice this
10971 // search inherited, not this loop's to second-guess) at the same `reach:
10972 // Reach::none()` -- so it is the same call with the same inputs on every
10973 // one of the thirteen iterations below; run it once and reuse the result
10974 // rather than repeat an already-priced transform/quantize/entropy call
10975 // twelve times for nothing (bit-identical: the value each iteration
10976 // reads back is exactly what it used to recompute).
10977 let u_trial = chroma[0].trial(
10978 At {
10979 x: x / 2,
10980 y: y / 2,
10981 side: BLOCK / 2,
10982 reach: Reach::none(),
10983 set: chroma_set,
10984 },
10985 DC_PRED,
10986 0,
10987 search.base_q_idx,
10988 search.deadzone, fctx,
10989 );
10990 let v_trial = chroma[1].trial(
10991 At {
10992 x: x / 2,
10993 y: y / 2,
10994 side: BLOCK / 2,
10995 reach: Reach::none(),
10996 set: chroma_set,
10997 },
10998 DC_PRED,
10999 0,
11000 search.base_q_idx,
11001 search.deadzone, fctx,
11002 );
11003
11004 let intra_modes: Vec<u8> = match search.top_k {
11005 Some(k) if k < search.modes.len() => {
11006 let scored = luma.intra_scores(
11007 At {
11008 x,
11009 y,
11010 side: BLOCK,
11011 reach,
11012 set: luma_set,
11013 },
11014 search.modes,
11015 mode_bits,
11016 search.lambda, fctx,
11017 );
11018 prune_by_sad(search.modes, scored, k)
11019 }
11020 _ => search.modes.to_vec(),
11021 };
11022 census_add(5, 1);
11023 census_add(6, if search.arf_leaf_intra { intra_modes.len() } else { 0 });
11024 // lane-arfmode: arm 1 drops the whole-32 block's intra candidates at the
11025 // top ARF too -- the probe proved the ARF's intra AREA lives HERE, not at
11026 // the leaves (film A arm 1 vs control byte-identical with the leaf gate
11027 // alone), so "the 32x32 whole keeps intra as the scene-cut hatch" was a
11028 // hatch nothing else was using. Counted once per block.
11029 if search.arf_leaf_intra {
11030 for &mode in &intra_modes {
11031 let luma_trial = luma.trial(
11032 At {
11033 x,
11034 y,
11035 side: BLOCK,
11036 reach,
11037 set: luma_set,
11038 },
11039 mode,
11040 0,
11041 search.base_q_idx,
11042 search.deadzone, fctx,
11043 );
11044 let u = u_trial.clone();
11045 let v = v_trial.clone();
11046 let cost = luma_trial.sse
11047 + u.sse
11048 + v.sse
11049 + search.lambda
11050 * (luma_trial.bits
11051 + u.bits
11052 + v.bits
11053 + mode_bits[usize::from(mode)]
11054 + skip_bits(false)
11055 + intra_inter_bits(false));
11056 consider(Candidate {
11057 cost,
11058 luma: luma_trial,
11059 u,
11060 v,
11061 mode,
11062 skip: false,
11063 inter: None,
11064 mode_bits: mode_bits[usize::from(mode)],
11065 });
11066 }
11067 } else {
11068 arfmode_hit(0);
11069 }
11070
11071 // The reference frame buffer a spec decoder holds is exactly the true
11072 // (unpadded) coded extent -- a superblock whose partition stops early at
11073 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
11074 // beyond it, so those samples are never part of the decoded picture.
11075 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
11076 // reference sample position clamp), not to this crate's own
11077 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
11078 // here would let a fractional-pel read past the true edge pick up this
11079 // encoder's own uncoded padding instead of the true edge's replicated
11080 // value a decoder computes.
11081 let ref_luma = (
11082 &reference.y,
11083 reference.width,
11084 luma.true_width,
11085 luma.true_height,
11086 );
11087 let ref_u = (
11088 &reference.u,
11089 reference.width / 2,
11090 chroma[0].true_width,
11091 chroma[0].true_height,
11092 );
11093 let ref_v = (
11094 &reference.v,
11095 reference.width / 2,
11096 chroma[1].true_width,
11097 chroma[1].true_height,
11098 );
11099 // Every single-reference mode the writer can code (spec 5.11.24's symbol
11100 // chain, mirrored by `tile::write_inter_mode`), priced with the static
11101 // CDFs at this block's own stack contexts. A candidate is a motion
11102 // vector plus the cheapest syntax that reaches it, so two modes landing
11103 // on the same vector share one set of trials: the added modes cost
11104 // mode-bit arithmetic, not another motion compensation.
11105 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11106 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11107 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
11108 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
11109 // the loop cannot reach is never offered below -- every candidate's
11110 // index is one this same loop walks to.
11111 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
11112 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11113 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
11114 (
11115 stack.nearest_mv,
11116 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11117 InterInfo {
11118 ref1: None,
11119 mv1: (0, 0),
11120 ref_frame: crate::mvstack::LAST_FRAME,
11121 mode: InterMode::NearestMv,
11122 mv: stack.nearest_mv,
11123 ref_mv_idx: 0,
11124 },
11125 ),
11126 // GLOBALMV is the identity model's zero vector -- this encoder writes
11127 // no `gm_params` -- and the cheapest syntax of the four on the static
11128 // content where that vector is also the right one.
11129 (
11130 (0, 0),
11131 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11132 InterInfo {
11133 ref1: None,
11134 mv1: (0, 0),
11135 ref_frame: crate::mvstack::LAST_FRAME,
11136 mode: InterMode::GlobalMv,
11137 mv: (0, 0),
11138 ref_mv_idx: 0,
11139 },
11140 ),
11141 ];
11142 let near_bits =
11143 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11144 for idx in 1..=2usize {
11145 if let Some(e) = stack.entries.get(idx) {
11146 cands.push((
11147 e.mv,
11148 near_bits + drl_bits(1, idx),
11149 InterInfo {
11150 ref1: None,
11151 mv1: (0, 0),
11152 ref_frame: crate::mvstack::LAST_FRAME,
11153 mode: InterMode::NearMv,
11154 mv: e.mv,
11155 ref_mv_idx: idx as u8,
11156 },
11157 ));
11158 }
11159 }
11160
11161 let source_block = luma.source_block(x, y, BLOCK);
11162 let (seeds, seed_n) = mv_seeds(stack);
11163 #[cfg(test)]
11164 let t = stage_start();
11165 let found = motion::search(
11166 ref_luma.0,
11167 ref_luma.1,
11168 ref_luma.2,
11169 ref_luma.3,
11170 &source_block,
11171 x,
11172 y,
11173 BLOCK,
11174 BLOCK,
11175 stack.pred_mv,
11176 &seeds[..seed_n],
11177 search.lambda, fctx,
11178 1,
11179 );
11180 #[cfg(test)]
11181 stage_since(0, t);
11182 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
11183 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
11184 // costs, for the census below (`None` when the writer cannot name it).
11185 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
11186 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
11187 // the same vector costs a different residual from each: take the index
11188 // whose residual plus DRL bits is cheapest, not entry 0 by default.
11189 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
11190 newmv_syntax = Some((mv, bits));
11191 cands.push((
11192 mv,
11193 last_ref_bits
11194 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
11195 + bits
11196 + mv_rate_surcharge(bits),
11197 InterInfo {
11198 ref1: None,
11199 mv1: (0, 0),
11200 ref_frame: crate::mvstack::LAST_FRAME,
11201 mode: InterMode::NewMv,
11202 mv,
11203 ref_mv_idx,
11204 },
11205 ));
11206 }
11207
11208 // Each extra reference's own `NEWMV` vector, for the compound
11209 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
11210 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
11211 for &(ref_frame, g, gstack) in extra {
11212 let g_ref_bits = single_ref_bits(ref_frame, gstack);
11213 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
11214 cands.push((
11215 gstack.nearest_mv,
11216 g_ref_bits
11217 + g_not_new
11218 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
11219 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
11220 InterInfo {
11221 ref1: None,
11222 mv1: (0, 0),
11223 ref_frame,
11224 mode: InterMode::NearestMv,
11225 mv: gstack.nearest_mv,
11226 ref_mv_idx: 0,
11227 },
11228 ));
11229 cands.push((
11230 (0, 0),
11231 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
11232 InterInfo {
11233 ref1: None,
11234 mv1: (0, 0),
11235 ref_frame,
11236 mode: InterMode::GlobalMv,
11237 mv: (0, 0),
11238 ref_mv_idx: 0,
11239 },
11240 ));
11241 // A motion search of this reference's own: without it, GOLDEN/ALTREF
11242 // can only be coded at a vector some neighbour already found, which
11243 // is why they carried a third of the inter blocks at their two
11244 // search-free modes alone.
11245 // The search is skipped when this reference's own NEARESTMV already
11246 // prices out `margin` times better than LAST's best vector does --
11247 // one candidate evaluation (`motion::cost_at`) standing in for a
11248 // whole search of ~50.
11249 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
11250 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
11251 // neighbour already found, which is how GOLDEN/ALTREF were offered
11252 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
11253 // own value from the second motion search's wall.
11254 let searched = extra_ref_new_mv()
11255 && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
11256 let margin = extra_new_skip_margin();
11257 if searched {
11258 newmv_census_global(0);
11259 }
11260 let skip_search = searched
11261 && margin > 0.0
11262 && motion::cost_at(
11263 &g.y,
11264 g.width,
11265 luma.true_width,
11266 luma.true_height,
11267 &source_block,
11268 x,
11269 y,
11270 BLOCK,
11271 BLOCK,
11272 gstack.nearest_mv,
11273 gstack.pred_mv,
11274 search.lambda,
11275 fctx,
11276 ) * margin
11277 <= found.cost;
11278 if skip_search {
11279 newmv_census_global(1);
11280 }
11281 if searched && !skip_search {
11282 let (gseeds, gn) = mv_seeds(gstack);
11283 #[cfg(test)]
11284 let t = stage_start();
11285 let gfound = motion::search(
11286 &g.y,
11287 g.width,
11288 luma.true_width,
11289 luma.true_height,
11290 &source_block,
11291 x,
11292 y,
11293 BLOCK,
11294 BLOCK,
11295 gstack.pred_mv,
11296 &gseeds[..gn],
11297 search.lambda, fctx,
11298 ref_distance(ref_frame),
11299 );
11300 #[cfg(test)]
11301 stage_since(0, t);
11302 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
11303 extra_new_mvs.push((ref_frame, gmv));
11304 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
11305 cands.push((
11306 gmv,
11307 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
11308 InterInfo {
11309 ref1: None,
11310 mv1: (0, 0),
11311 ref_frame,
11312 mode: InterMode::NewMv,
11313 mv: gmv,
11314 ref_mv_idx,
11315 },
11316 ));
11317 }
11318 }
11319 }
11320
11321 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
11322 // trial set each: both references predict the block and the two
11323 // predictions are averaged, which is what pays on content where neither
11324 // reference alone is right. Priced with the same static-CDF approximation
11325 // the single-reference candidates use, plus the compound-only symbols
11326 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
11327 // The two compound-mode arms, each measured alone on the BD gate before
11328 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
11329 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
11330 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
11331 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
11332 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
11333 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
11334 // the keep rule. Still behind the knob.
11335 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
11336 let half_new = true;
11337 for (ref1, g, cstack) in compound {
11338 let (ref1, g) = (*ref1, *g);
11339 // The whole `comp_mode` + reference-pair tree at the writer's own
11340 // contexts, for THIS pair (lane-ctx).
11341 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
11342 let mode_ctx =
11343 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
11344 let mode_bits_of =
11345 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
11346 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
11347 (
11348 cstack.nearest_mv,
11349 mode_bits_of(0),
11350 InterInfo {
11351 ref_frame: crate::mvstack::LAST_FRAME,
11352 mode: InterMode::NearestNearestMv,
11353 mv: cstack.nearest_mv.0,
11354 mv1: cstack.nearest_mv.1,
11355 ref1: Some(ref1),
11356 ref_mv_idx: 0,
11357 },
11358 ),
11359 (
11360 ((0, 0), (0, 0)),
11361 mode_bits_of(6),
11362 InterInfo {
11363 ref_frame: crate::mvstack::LAST_FRAME,
11364 mode: InterMode::GlobalGlobalMv,
11365 mv: (0, 0),
11366 mv1: (0, 0),
11367 ref1: Some(ref1),
11368 ref_mv_idx: 0,
11369 },
11370 ),
11371 ];
11372 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
11373 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
11374 // the stack is deep enough for that walk to read one.
11375 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
11376 let drl = if cstack.entries.len() > 2 {
11377 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
11378 } else {
11379 0.0
11380 };
11381 ccands.push((
11382 (e.mv0, e.mv1),
11383 mode_bits_of(1) + drl,
11384 InterInfo {
11385 ref_frame: crate::mvstack::LAST_FRAME,
11386 mode: InterMode::NearNearMv,
11387 mv: e.mv0,
11388 mv1: e.mv1,
11389 ref1: Some(ref1),
11390 ref_mv_idx: 0,
11391 },
11392 ));
11393 }
11394 // The half-new modes and `NEW_NEWMV`, all seeded from the two
11395 // single-reference searches this block already ran -- no joint search
11396 // of its own. Every residual is priced against stack entry 0, which
11397 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
11398 let cbase = cstack
11399 .entries
11400 .first()
11401 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
11402 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
11403 ccands.push((
11404 (mv, cstack.nearest_mv.1),
11405 mode_bits_of(3) + b0,
11406 InterInfo {
11407 ref_frame: crate::mvstack::LAST_FRAME,
11408 mode: InterMode::NewNearestMv,
11409 mv,
11410 mv1: cstack.nearest_mv.1,
11411 ref1: Some(ref1),
11412 ref_mv_idx: 0,
11413 },
11414 ));
11415 }
11416 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
11417 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
11418 ccands.push((
11419 (cstack.nearest_mv.0, mv1),
11420 mode_bits_of(2) + b1,
11421 InterInfo {
11422 ref_frame: crate::mvstack::LAST_FRAME,
11423 mode: InterMode::NearestNewMv,
11424 mv: cstack.nearest_mv.0,
11425 mv1,
11426 ref1: Some(ref1),
11427 ref_mv_idx: 0,
11428 },
11429 ));
11430 }
11431 let base = cbase;
11432 if let (Some(b0), Some(b1)) = (
11433 mv_residual_bits(mv, base.0),
11434 mv_residual_bits(mv1, base.1),
11435 ) {
11436 ccands.push((
11437 (mv, mv1),
11438 mode_bits_of(7) + b0 + b1,
11439 InterInfo {
11440 ref_frame: crate::mvstack::LAST_FRAME,
11441 mode: InterMode::NewNewMv,
11442 mv,
11443 mv1,
11444 ref1: Some(ref1),
11445 ref_mv_idx: 0,
11446 },
11447 ));
11448 }
11449 }
11450 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
11451 ccands.dedup_by_key(|c| c.0);
11452 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
11453 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
11454 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
11455 for (mvs, bits, info) in ccands {
11456 let luma_trial = mc_trial_compound(
11457 luma, x, y, BLOCK, mvs, true,
11458 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
11459 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
11460 );
11461 let u = mc_trial_compound(
11462 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
11463 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
11464 search.base_q_idx, search.deadzone, chroma_set, fctx,
11465 );
11466 let v = mc_trial_compound(
11467 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
11468 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
11469 search.base_q_idx, search.deadzone, chroma_set, fctx,
11470 );
11471 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11472 && u.levels.iter().all(|&l| l == 0)
11473 && v.levels.iter().all(|&l| l == 0);
11474 let cost = luma_trial.sse
11475 + u.sse
11476 + v.sse
11477 + search.lambda
11478 * (skip_bits(skip)
11479 + intra_inter_bits(true)
11480 + bits
11481 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
11482 consider(Candidate {
11483 cost,
11484 luma: luma_trial,
11485 u,
11486 v,
11487 mode: DC_PRED,
11488 skip,
11489 mode_bits: bits,
11490 inter: Some(info),
11491 });
11492 }
11493 }
11494
11495 // One trial set per distinct (reference, vector) pair: sort, cheapest
11496 // syntax first, and drop the rest of each pair's run.
11497 cands.sort_by(|a, b| {
11498 (a.2.ref_frame, a.0)
11499 .cmp(&(b.2.ref_frame, b.0))
11500 .then(a.1.total_cmp(&b.1))
11501 });
11502 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
11503 census_add(7, cands.len());
11504 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
11505 // this block reaches WITHOUT it, taken inside the one loop that prices
11506 // them all (a second pricing pass would be a second oracle).
11507 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
11508 {
11509 for (mv, mode_bits_inter, info) in cands {
11510 let (ref_luma, ref_u, ref_v) = match extra
11511 .iter()
11512 .find(|(r, _, _)| *r == info.ref_frame)
11513 {
11514 Some(&(_, g, _)) => (
11515 (&g.y, g.width, luma.true_width, luma.true_height),
11516 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
11517 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
11518 ),
11519 None => (ref_luma, ref_u, ref_v),
11520 };
11521 let luma_trial = mc_trial(
11522 luma,
11523 x,
11524 y,
11525 BLOCK,
11526 mv,
11527 true,
11528 ref_luma.0,
11529 ref_luma.1,
11530 ref_luma.2,
11531 ref_luma.3,
11532 false,
11533 search.base_q_idx,
11534 search.deadzone,
11535 TxbSet::Luma32Inter, fctx,
11536 );
11537 let u = mc_trial(
11538 &chroma[0],
11539 x / 2,
11540 y / 2,
11541 BLOCK / 2,
11542 mv,
11543 false,
11544 ref_u.0,
11545 ref_u.1,
11546 ref_u.2,
11547 ref_u.3,
11548 false,
11549 search.base_q_idx,
11550 search.deadzone,
11551 chroma_set, fctx,
11552 );
11553 let v = mc_trial(
11554 &chroma[1],
11555 x / 2,
11556 y / 2,
11557 BLOCK / 2,
11558 mv,
11559 false,
11560 ref_v.0,
11561 ref_v.1,
11562 ref_v.2,
11563 ref_v.3,
11564 false,
11565 search.base_q_idx,
11566 search.deadzone,
11567 chroma_set, fctx,
11568 );
11569 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11570 && u.levels.iter().all(|&l| l == 0)
11571 && v.levels.iter().all(|&l| l == 0);
11572 let cost = luma_trial.sse
11573 + u.sse
11574 + v.sse
11575 + search.lambda
11576 * (skip_bits(skip)
11577 + intra_inter_bits(true)
11578 + mode_bits_inter
11579 + if skip {
11580 0.0
11581 } else {
11582 luma_trial.bits + u.bits + v.bits
11583 });
11584 consider(Candidate {
11585 cost,
11586 luma: luma_trial,
11587 u,
11588 v,
11589 mode: DC_PRED,
11590 skip,
11591 mode_bits: mode_bits_inter,
11592 inter: Some(info),
11593 });
11594 if newmv_census_on() {
11595 if info.mode == InterMode::NewMv
11596 && info.ref1.is_none()
11597 && info.ref_frame == crate::mvstack::LAST_FRAME
11598 {
11599 new_cost = cost;
11600 } else {
11601 other_cost = other_cost.min(cost);
11602 }
11603 }
11604 }
11605 }
11606 if let Some((new_mv, bits)) = newmv_syntax {
11607 newmv_census_block(BLOCK, true, new_cost, other_cost, new_mv, stack.nearest_mv, bits);
11608 } else {
11609 newmv_census_block(BLOCK, false, f64::INFINITY, other_cost, mv, stack.nearest_mv, 0.0);
11610 }
11611
11612 let best = best.expect("the search offers at least the intra modes");
11613 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
11614 // offered to the SINGLE-REFERENCE winner only -- libaom's
11615 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
11616 // compound block, so the writer codes no symbol for one. The prediction
11617 // is built by the DECODER's own plan and blend
11618 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
11619 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
11620 // this search's `grid` already carries, so what is priced here is what a
11621 // decoder reconstructs -- never a second implementation of the blend.
11622 //
11623 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
11624 // on). Native crop BD, the standing recipe, with it on against the same
11625 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
11626 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
11627 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
11628 // one UP -- the keep rule wants two down and one flat, so it stays off.
11629 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
11630 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
11631 // things bound it and are the upgrade path: only the 32x32 winner is
11632 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
11633 // that is where libaom cashes most of its OBMC gain), and the symbol/
11634 // residual price here is the static-CDF estimate.
11635 let mut best = best;
11636 let mut motion_won = 0u8;
11637 if let Some(info) = best.inter.filter(|i| {
11638 i.ref1.is_none()
11639 && (crate::envflags::env_flag!("EC_AV1_OBMC")
11640 || warp_on())
11641 }) {
11642 let mut refs: [Option<&Picture>; 8] = [None; 8];
11643 refs[LAST_FRAME as usize] = Some(reference);
11644 for &(r, p, _) in extra {
11645 refs[r as usize] = Some(p);
11646 }
11647 // This block's OWN reference planes: the single-reference winner may
11648 // be one of the extra references, not LAST.
11649 let planes: [(&[u16], usize, usize, usize); 3] =
11650 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11651 Some(&(_, g, _)) => [
11652 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11653 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11654 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11655 ],
11656 None => [
11657 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
11658 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
11659 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
11660 ],
11661 };
11662 // The alphabet `tile::write_motion_mode` will code this block's
11663 // symbol against, mirrored term for term (libaom
11664 // `motion_mode_allowed`).
11665 let warp_alphabet = warp_on()
11666 && crate::decode::num_proj_ref(
11667 grid,
11668 mi_row,
11669 mi_col,
11670 8,
11671 8,
11672 mi_cols,
11673 mi_rows,
11674 info.ref_frame,
11675 fctx,
11676 ) >= 1;
11677 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
11678 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
11679 if crate::envflags::env_flag!("EC_AV1_OBMC") {
11680 if let Some(pred) = obmc_prediction(
11681 grid,
11682 (mi_row, mi_col),
11683 (mi_rows, mi_cols),
11684 (x, y),
11685 BLOCK,
11686 info.mv,
11687 &refs,
11688 planes,
11689 reference.width,
11690 fctx,
11691 ) {
11692 candidates.push((1, pred));
11693 }
11694 }
11695 if warp_alphabet {
11696 if let Some(pred) = warp_prediction(
11697 grid,
11698 (mi_row, mi_col),
11699 (mi_rows, mi_cols),
11700 (x, y),
11701 BLOCK,
11702 info.mv,
11703 info.ref_frame,
11704 planes,
11705 fctx,
11706 ) {
11707 candidates.push((2, pred));
11708 }
11709 }
11710 for (motion, pred) in candidates {
11711 let luma_trial = luma.code_from_prediction(
11712 x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
11713 TxbSet::Luma32Inter,
11714 );
11715 let u = chroma[0].code_from_prediction(
11716 x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
11717 chroma_set,
11718 );
11719 let v = chroma[1].code_from_prediction(
11720 x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
11721 chroma_set,
11722 );
11723 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11724 && u.levels.iter().all(|&l| l == 0)
11725 && v.levels.iter().all(|&l| l == 0);
11726 let cost = luma_trial.sse
11727 + u.sse
11728 + v.sse
11729 + search.lambda
11730 * (skip_bits(skip)
11731 + intra_inter_bits(true)
11732 + best.mode_bits
11733 + mm(motion)
11734 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
11735 if cost < best.cost + search.lambda * mm(motion_won) {
11736 motion_won = motion;
11737 best = Candidate {
11738 cost,
11739 luma: luma_trial,
11740 u,
11741 v,
11742 mode: DC_PRED,
11743 skip,
11744 mode_bits: best.mode_bits,
11745 inter: best.inter,
11746 };
11747 }
11748 }
11749 }
11750 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
11751 // default OFF): the four 16x16 units of `commit_inter_luma` against the
11752 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
11753 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
11754 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
11755 // it, and it is worse again on the deciding native table: film 1080p
11756 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
11757 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
11758 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
11759 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
11760 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
11761 // +28.4/+47.4/-4.0 -- the native table decides.)
11762 //
11763 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
11764 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
11765 // either, and the census names the row: the split units' own set
11766 // `Luma16Inter` is priced within 1.4% of what it is written at in every
11767 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
11768 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
11769 // so a perfect pricer would split even more, and more splitting is what
11770 // measured worse. The four extra txb_skip/eob symbols simply cost more
11771 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
11772 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
11773 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
11774 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
11775 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
11776 // plain translation, which is not the prediction it was priced from.
11777 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
11778 Some(info) => {
11779 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11780 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11781 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
11782 };
11783 let second = info.ref1.and_then(|r| {
11784 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
11785 (
11786 info.mv1,
11787 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11788 )
11789 })
11790 });
11791 match info.ref1.is_some() && second.is_none() {
11792 true => {
11793 luma.commit(x, y, BLOCK, &best.luma);
11794 (best.luma.levels.clone(), 0, 0.0, Vec::new())
11795 }
11796 false => commit_inter_luma(
11797 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,
11798 fctx,
11799 ),
11800 }
11801 }
11802 None => {
11803 luma.commit(x, y, BLOCK, &best.luma);
11804 (best.luma.levels.clone(), 0, 0.0, Vec::new())
11805 }
11806 };
11807 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
11808 let [bu, bv] = match (best.inter.filter(|_| motion_won == 0), luma_tx_types.first().copied()) {
11809 (Some(info), Some(t)) => {
11810 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11811 Some(&(_, g, _)) => (
11812 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11813 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11814 ),
11815 None => (
11816 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
11817 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
11818 ),
11819 };
11820 let sec = info.ref1.and_then(|r| {
11821 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
11822 (
11823 info.mv1,
11824 [
11825 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11826 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11827 ],
11828 )
11829 })
11830 });
11831 recode_inter_chroma(
11832 chroma, (x, y), BLOCK, info.mv, [ou, ov], sec, search, chroma_set, t, fctx,
11833 )
11834 .unwrap_or([best.u, best.v])
11835 }
11836 _ => [best.u, best.v],
11837 };
11838 let best = Candidate { u: bu, v: bv, ..best };
11839 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
11840 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
11841 (
11842 BlockCoeffs {
11843 luma_tx_types,
11844 angle_delta_y: 0,
11845 cfl_alphas: None,
11846 filter_intra: None,
11847 luma: coeffs(&levels, BLOCK),
11848 u: coeffs(&best.u.levels, BLOCK / 2),
11849 v: coeffs(&best.v.levels, BLOCK / 2),
11850 mode: best.mode,
11851 uv_mode: DC_PRED,
11852 skip: best.skip,
11853 inter: best.inter,
11854 motion_mode: motion_won,
11855 eight: None,
11856 dv: None,
11857 palette: None,
11858 palette_uv: None,
11859 tx_depth,
11860 },
11861 best.cost + dcost,
11862 )
11863}
11864
11865/// lane-av1tpl: the strength `k` of the temporal lambda weighting
11866/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
11867/// is what every measurement before this lane was taken on. Swept by
11868/// `EC_AV1_TPL=<k>`.
11869///
11870/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
11871/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
11872/// baseline exactly, which is the control the rest of the table is read
11873/// against:
11874///
11875/// | k | film 1080p | film 2160p | screen |
11876/// |---|---|---|---|
11877/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
11878/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
11879/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
11880/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
11881/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
11882///
11883/// 0.5 is the only arm that is at least flat on every row and down on five of
11884/// the six columns, so it ships as the default. The lookahead pass that feeds
11885/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
11886const TPL_STRENGTH: f64 = 0.5;
11887
11888/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
11889/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
11890/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
11891/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
11892///
11893/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
11894/// nothing to vary the quantizer BY and codes no delta syntax at all.
11895fn deltaq_res_log2() -> Option<u8> {
11896 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
11897 u8::MAX => {}
11898 4 => return None,
11899 r => return Some(r),
11900 }
11901 match crate::envflags::var("EC_AV1_DELTAQ").ok().as_deref().map(str::trim) {
11902 Some("0") => None,
11903 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
11904 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
11905 }
11906}
11907
11908/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
11909/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
11910/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
11911/// speed presets take, because the streams every other test pins move under
11912/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
11913static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 =
11914 std::sync::atomic::AtomicU8::new(u8::MAX);
11915
11916/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
11917#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
11918pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
11919 DELTAQ_OVERRIDE.store(
11920 res_log2.unwrap_or(u8::MAX),
11921 std::sync::atomic::Ordering::Relaxed,
11922 );
11923}
11924
11925/// How much of the derived qindex step is actually taken
11926/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
11927fn deltaq_k() -> f64 {
11928 crate::envflags::var("EC_AV1_DELTAQ_K")
11929 .ok()
11930 .and_then(|v| v.trim().parse::<f64>().ok())
11931 .filter(|k| k.is_finite() && *k >= 0.0)
11932 .unwrap_or(1.0)
11933}
11934
11935/// The largest qindex the map may move a superblock by, either way
11936/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
11937/// deltaq around a quarter of the base qindex).
11938fn deltaq_clamp() -> i32 {
11939 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
11940 .ok()
11941 .and_then(|v| v.trim().parse::<i32>().ok())
11942 .filter(|c| (0..=63).contains(c))
11943 .unwrap_or(16)
11944}
11945
11946/// The qindex a lambda factor `f` asks for, derived rather than fitted.
11947///
11948/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
11949/// square of the quantizer step (`encode_inter_frame`'s own
11950/// `lambda = .. * step * step`), so the step this superblock wants is
11951/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
11952/// step ratio is inverted through the table itself -- the index whose `ac_q`
11953/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
11954/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
11955/// bounds it, and the answer is snapped onto the `res` grid so that every
11956/// superblock's qindex is congruent to `base` and the coded delta is a whole
11957/// number of steps.
11958fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
11959 let base_ac = f64::from(ac_q(8, i32::from(base)));
11960 let target = base_ac * f.max(1e-6).sqrt();
11961 let exact = (1..=255)
11962 .min_by(|&a, &b| {
11963 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
11964 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
11965 })
11966 .expect("the qindex range is not empty")
11967 - i32::from(base);
11968 let want = (exact as f64 * k).round() as i32;
11969 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
11970 // and need not be a whole number of steps, and clamping afterwards would
11971 // hand back a qindex that is not congruent to `base`.
11972 let max_steps = clamp / res;
11973 let steps = (want as f64 / f64::from(res)).round() as i32;
11974 let delta = steps.clamp(-max_steps, max_steps) * res;
11975 (i32::from(base) + delta).clamp(1, 255) as u8
11976}
11977
11978/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
11979/// objective would, from the SAME tpl dependence ratio our own map already
11980/// carries (`EC_AV1_DQ_TPL=1`).
11981///
11982/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
11983/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
11984/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
11985/// same expression at frame scope) by it, and asks
11986/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
11987/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
11988/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
11989/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
11990/// libaom reads `r0`. The offset is clamped to libaom's own
11991/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
11992/// twice the +-16 qindex [`deltaq_for_factor`] allows.
11993///
11994/// Two things differ from [`deltaq_for_factor`] and both are the point of the
11995/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
11996/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
11997/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
11998/// much stronger for the same map. `strength` scales the offset.
11999fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
12000 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
12001 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
12002 let exact = (1..=255)
12003 .min_by(|&a, &b| {
12004 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
12005 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
12006 })
12007 .expect("the qindex range is not empty")
12008 - i32::from(base);
12009 let want = exact as f64 * strength;
12010 // Snapped onto the `res` grid first, so the coded delta is a whole number
12011 // of steps, then bounded by libaom's own `res * 9 - 1`.
12012 let max_steps = (res * 9 - 1) / res;
12013 let steps = (want / f64::from(res)).round() as i32;
12014 let delta = steps.clamp(-max_steps, max_steps) * res;
12015 (i32::from(base) + delta).clamp(1, 255) as u8
12016}
12017
12018/// The frame-level `r0` libaom's objective divides by: the log-mean of
12019/// `1 + r` over the frame's cells, minus 1.
12020fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
12021 if ratio.is_empty() {
12022 return 0.0;
12023 }
12024 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
12025 m.exp() - 1.0
12026}
12027
12028/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
12029/// [`deltaq_for_factor`] derivation.
12030///
12031/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
12032/// the strength (default 1.0 = libaom's own offset when the flag armed it);
12033/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
12034fn dq_tpl_strength(level: DqLevel) -> Option<f64> {
12035 let m = dq_level_k()[level as usize];
12036 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
12037 .ok()
12038 .and_then(|v| v.trim().parse::<f64>().ok())
12039 .filter(|k| k.is_finite() && *k >= 0.0);
12040 let base = match crate::envflags::var("EC_AV1_DQ_TPL").ok().as_deref().map(str::trim) {
12041 Some("0") => return None,
12042 Some(_) => Some(env_k.unwrap_or(1.0)),
12043 None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))),
12044 };
12045 base.map(|k| k * m).filter(|k| *k > 0.0)
12046}
12047
12048/// lane-arfq: which pyramid level the frame asking for a
12049/// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it
12050/// codes no `delta_q` syntax at all (the whole lever lives in
12051/// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the
12052/// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job.
12053#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12054pub(crate) enum DqLevel {
12055 /// The mini-GOP's own hidden `ALTREF`, which every other frame of the
12056 /// group predicts from (directly or through the mid level).
12057 TopArf = 0,
12058 /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it.
12059 MidArf = 1,
12060 /// A shown leaf -- and every frame of the flat, non-pyramid path.
12061 Leaf = 2,
12062}
12063
12064/// The per-level multiplier on the [`dq_tpl_strength`] the preset carries:
12065/// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else
12066/// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes
12067/// no `delta_q` (see [`DqLevel`]).
12068fn dq_level_k() -> [f64; 3] {
12069 dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref())
12070}
12071
12072/// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an
12073/// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry.
12074fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] {
12075 let mut k = crate::speed::DQ_LEVEL_K;
12076 if let Some(spec) = spec {
12077 for (slot, field) in k.iter_mut().zip(spec.split(':')) {
12078 if let Some(v) =
12079 field.trim().parse::<f64>().ok().filter(|v: &f64| v.is_finite() && *v >= 0.0)
12080 {
12081 *slot = v;
12082 }
12083 }
12084 }
12085 k
12086}
12087
12088/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
12089/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
12090/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
12091/// the same tpl map -- and which of the two the frame actually coded.
12092fn dq_census() -> bool {
12093 crate::envflags::var("EC_AV1_DQ_CENSUS").ok().as_deref().map(str::trim) == Some("1")
12094}
12095
12096/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
12097fn dq_summary(offsets: &[i32]) -> String {
12098 let n = offsets.len().max(1);
12099 let (lo, hi) = offsets.iter().fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
12100 let nz = offsets.iter().filter(|&&o| o != 0).count();
12101 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
12102 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
12103 let mut levels: Vec<i32> = offsets.to_vec();
12104 levels.sort_unstable();
12105 levels.dedup();
12106 format!(
12107 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
12108 offsets.len(),
12109 levels.len()
12110 )
12111}
12112
12113/// How many DISTINCT per-superblock quantizer levels the last inter frame's
12114/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
12115/// (class `gate-blind-to-feature`: every exactness assert below passes on a
12116/// grid that is one flat value, i.e. on no delta_q at all). Process-global
12117/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
12118/// keeps the LARGEST count seen since the last read.
12119static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12120
12121/// [`DELTAQ_LEVELS`], reset to 0.
12122#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
12123pub(crate) fn take_deltaq_levels() -> usize {
12124 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
12125}
12126
12127/// This superblock's search state: the quantizer it is coded at, and the
12128/// lambda that quantizer implies. RD lambda goes as the square of the step,
12129/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
12130/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
12131/// before lane-deltaq).
12132fn sb_q_search<'m>(
12133 sb_q: &[u8],
12134 sb_cols: usize,
12135 base_q_idx: u8,
12136 (sb_r, sb_c): (usize, usize),
12137 base: Search<'m>,
12138) -> Search<'m> {
12139 let q = sb_q[sb_r * sb_cols + sb_c];
12140 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
12141 Search { base_q_idx: q, lambda: base.lambda * ratio * ratio, ..base }
12142}
12143
12144fn tpl_strength() -> f64 {
12145 std::env::var("EC_AV1_TPL")
12146 .ok()
12147 .and_then(|v| v.parse::<f64>().ok())
12148 .filter(|k| k.is_finite() && *k >= 0.0)
12149 .unwrap_or(TPL_STRENGTH)
12150}
12151
12152/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
12153/// the frame being coded. 1 turns the weighting off; 2 is the shipped
12154/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
12155/// [`tpl_propagating`], which is the map that can actually use them and is
12156/// the default since lane-av1tpl3, so the default window is 8. Swept by
12157/// `EC_AV1_TPL_D=<d>`.
12158///
12159/// The streaming facade holds `depth - 1` pictures back so it feeds
12160/// `encode_inter_frame` the same window `encode_sequence` does; both read
12161/// THIS function, so the two paths cannot disagree about the window.
12162pub(crate) const TPL_DEPTH: usize = 8;
12163
12164/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
12165/// 0.5 is libaom's own square-root compression of its dependence ratio.
12166const TPL_POWER: f64 = 0.5;
12167
12168/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
12169/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
12170///
12171/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
12172/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
12173/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
12174///
12175/// | k | D | p | film 1080p | film 2160p | screen |
12176/// |---|---|---|---|---|---|
12177/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
12178/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
12179/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
12180/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
12181/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
12182/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
12183/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
12184/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
12185/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
12186/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
12187/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
12188/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
12189///
12190/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
12191/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
12192/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
12193/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
12194/// 0.1..0.4 UP on film 2160p, so it shipped off.
12195///
12196/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
12197/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
12198/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
12199/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
12200/// wherever the window leans on a flat bar, which is exactly where coding is
12201/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
12202/// (libaom's own granularity) puts a busy cell's denominator next to the flat
12203/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
12204/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
12205/// the same native gate (baseline = the shipped one-frame map):
12206///
12207/// | arm | film 1080p | film 2160p | screen |
12208/// |---|---|---|---|
12209/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
12210/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
12211/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
12212/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
12213/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
12214/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
12215/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
12216/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
12217/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
12218/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
12219///
12220/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
12221/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
12222/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
12223/// floor is a real effect on the ratio and never a win once the aggregation
12224/// is in -- the aggregation is the same fix, done where libaom does it.
12225fn tpl_propagating() -> bool {
12226 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
12227}
12228
12229pub(crate) fn tpl_depth() -> usize {
12230 std::env::var("EC_AV1_TPL_D")
12231 .ok()
12232 .and_then(|v| v.parse::<usize>().ok())
12233 .filter(|d| *d >= 1)
12234 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
12235 .max(1)
12236}
12237
12238/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
12239/// process, so the gate can price it against the encode it rides on.
12240static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
12241
12242/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
12243/// the winning displacement and its SAD.
12244///
12245/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
12246/// the left/above winners, first-best tie-break. Built once on the frame's
12247/// own thread and read-only afterwards, so it cannot make a tile's bytes
12248/// depend on the thread count.
12249fn tpl_coarse_pass(
12250 cur: &[u8],
12251 next: &[u8],
12252 width: usize,
12253 height: usize,
12254) -> Vec<((i32, i32), u32)> {
12255 let (cells_x, cells_y) = (width / 16, height / 16);
12256 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
12257 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
12258 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
12259 return u32::MAX;
12260 }
12261 let (sx, sy) = (sx as usize, sy as usize);
12262 let mut sum = 0u32;
12263 for r in 0..16 {
12264 let a = &next[(by + r) * width + bx..][..16];
12265 let b = &cur[(sy + r) * width + sx..][..16];
12266 sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>();
12267 }
12268 sum
12269 };
12270 let mut out = Vec::with_capacity(cells_x * cells_y);
12271 let mut above = vec![(0i32, 0i32); cells_x];
12272 for cy in 0..cells_y {
12273 let mut left = (0i32, 0i32);
12274 for cx in 0..cells_x {
12275 let (bx, by) = (cx * 16, cy * 16);
12276 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
12277 for cand in [left, above[cx]] {
12278 if cand != (0, 0) {
12279 let s = sad(bx, by, cand);
12280 if s < best.0 {
12281 best = (s, cand);
12282 }
12283 }
12284 }
12285 for step in [8i32, 4, 2, 1] {
12286 let centre = best.1;
12287 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
12288 let mv = (centre.0 + dx, centre.1 + dy);
12289 if mv.0.abs() > 32 || mv.1.abs() > 32 {
12290 continue;
12291 }
12292 let s = sad(bx, by, mv);
12293 if s < best.0 {
12294 best = (s, mv);
12295 }
12296 }
12297 }
12298 left = best.1;
12299 above[cx] = best.1;
12300 out.push((best.1, best.0));
12301 }
12302 }
12303 out
12304}
12305
12306/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
12307/// transform: here, the mean absolute deviation of the cell from its own DC.
12308/// It is the denominator every propagated cost is read against, so only its
12309/// SHAPE across the frame matters, not its scale.
12310fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
12311 let (cells_x, cells_y) = (width / 16, height / 16);
12312 let mut out = Vec::with_capacity(cells_x * cells_y);
12313 for cy in 0..cells_y {
12314 for cx in 0..cells_x {
12315 let (bx, by) = (cx * 16, cy * 16);
12316 let mut sum = 0u32;
12317 for r in 0..16 {
12318 sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>();
12319 }
12320 let dc = ((sum + 128) / 256) as u8;
12321 let mut cost = 0u32;
12322 for r in 0..16 {
12323 cost += frame[(by + r) * width + bx..][..16]
12324 .iter()
12325 .map(|&p| u32::from(p.abs_diff(dc)))
12326 .sum::<u32>();
12327 }
12328 out.push(cost);
12329 }
12330 }
12331 out
12332}
12333
12334/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
12335/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
12336/// splats its own area, at its winning displacement, onto the (at most four)
12337/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
12338fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
12339 let start = std::time::Instant::now();
12340 let (cells_x, cells_y) = (width / 16, height / 16);
12341 let pass = tpl_coarse_pass(cur, next, width, height);
12342 let mut area = vec![0.0f64; cells_x * cells_y];
12343 for cy in 0..cells_y {
12344 for cx in 0..cells_x {
12345 let (mv, _) = pass[cy * cells_x + cx];
12346 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
12347 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
12348 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
12349 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
12350 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
12351 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
12352 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
12353 }
12354 }
12355 }
12356 }
12357 TPL_NANOS.fetch_add(
12358 start.elapsed().as_nanos() as u64,
12359 std::sync::atomic::Ordering::Relaxed,
12360 );
12361 area
12362}
12363
12364/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
12365/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
12366/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
12367/// Decreasing in referenced-ness (a block the next frame leans on is coded
12368/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
12369/// total lambda scale is only redistributed, never moved -- a global move is
12370/// the thing lane-av1lambda already measured inert.
12371fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
12372 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
12373 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
12374 let mut out = Vec::with_capacity(sb_cols * sb_rows);
12375 for sr in 0..sb_rows {
12376 for sc in 0..sb_cols {
12377 let mut sum = 0.0;
12378 for r in 0..4 {
12379 for c in 0..4 {
12380 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
12381 }
12382 }
12383 let w_rel = sum / 16.0 / mean;
12384 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
12385 }
12386 }
12387 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
12388 let mut hist = [0usize; 8];
12389 for w in map {
12390 hist[((w / mean * 2.0) as usize).min(7)] += 1;
12391 }
12392 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
12393 eprintln!(
12394 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
12395 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
12396 map.len(),
12397 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
12398 );
12399 }
12400 out
12401}
12402
12403/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
12404/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
12405/// much of the WHOLE lookahead window leans on that cell.
12406///
12407/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
12408/// coarse pass gives a displacement and an inter cost; a cell's own
12409/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
12410/// cell well saves the frames that predict from it -- and it is splatted,
12411/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
12412/// displacement lands on. Walking `f` from the far end of the window back to
12413/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
12414/// area map could not do at all.
12415///
12416/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
12417/// factor over the frame is exactly 1: a cell the window leans on is coded
12418/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
12419/// scale only moves around, never up or down -- a global move is what
12420/// lane-av1lambda already measured inert.
12421/// Returns the per-cell lambda factors AND the per-cell dependence ratio
12422/// `mc_dep / intra` they were derived from -- the second half is what
12423/// [`deltaq_libaom`] needs, since the factor alone has been through a
12424/// mean normalisation the raw ratio cannot be recovered across.
12425fn tpl_lambda_factors(
12426 frames: &[&[u8]],
12427 width: usize,
12428 height: usize,
12429 k: f64,
12430) -> (Vec<f64>, Vec<f64>) {
12431 let start = std::time::Instant::now();
12432 let (cells_x, cells_y) = (width / 16, height / 16);
12433 let cells = cells_x * cells_y;
12434 let levels = frames.len();
12435 let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect();
12436 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
12437 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
12438 .collect();
12439 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
12440 for f in (1..levels).rev() {
12441 for cy in 0..cells_y {
12442 for cx in 0..cells_x {
12443 let ci = cy * cells_x + cx;
12444 let (mv, inter) = passes[f - 1][ci];
12445 let saved = f64::from(intra[f][ci].saturating_sub(inter));
12446 let propagate = saved + mc_dep[f][ci];
12447 if propagate <= 0.0 {
12448 continue;
12449 }
12450 // The 16x16 window of the PREVIOUS frame this cell predicted
12451 // from, spread over the cells it overlaps.
12452 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
12453 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
12454 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
12455 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
12456 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
12457 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
12458 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
12459 }
12460 }
12461 }
12462 }
12463 }
12464 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
12465 // tail (a nearly flat cell the window leans on has a tiny denominator),
12466 // and at p = 1 that tail slams into the clamp. libaom reads its own
12467 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
12468 // sweeps the exponent, 1 being the raw ratio.
12469 let power = std::env::var("EC_AV1_TPL_P")
12470 .ok()
12471 .and_then(|v| v.parse::<f64>().ok())
12472 .filter(|p| p.is_finite() && *p > 0.0)
12473 .unwrap_or(TPL_POWER);
12474 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
12475 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
12476 // `0` to take either back out); `FLOOR` defaults to off.
12477 //
12478 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
12479 // frame's own mean intra cost. A cell of flat content has a near-zero
12480 // MAD, so its ratio explodes exactly where coding is cheap.
12481 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
12482 // and mc_dep are summed over the 64x64 superblock first -- libaom's
12483 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
12484 // per-16x16 numbers), which is also what makes the ratio survive one
12485 // flat cell next to a busy one.
12486 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
12487 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
12488 // harder than the `p` exponent alone can.
12489 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
12490 .ok()
12491 .and_then(|v| v.parse::<f64>().ok())
12492 .filter(|f| f.is_finite() && *f >= 0.0)
12493 .unwrap_or(0.0);
12494 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
12495 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
12496 let intra_mean =
12497 intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
12498 let floor = floor_frac * intra_mean;
12499 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
12500 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
12501 // every cell under it. The edge groups are partial and summed as they are.
12502 let ratio: Vec<f64> = if sb_agg {
12503 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
12504 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
12505 for cy in 0..cells_y {
12506 for cx in 0..cells_x {
12507 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
12508 e.0 += mc_dep[0][cy * cells_x + cx];
12509 e.1 += denom(cy * cells_x + cx);
12510 }
12511 }
12512 (0..cells)
12513 .map(|c| {
12514 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
12515 dep / den.max(1.0)
12516 })
12517 .collect()
12518 } else {
12519 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
12520 };
12521 let mut out: Vec<f64> = ratio
12522 .iter()
12523 .map(|&r| {
12524 let r = if log_beta { (1.0 + r).log2() } else { r };
12525 (1.0 + k * r).powf(-power)
12526 })
12527 .collect();
12528 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
12529 for f in &mut out {
12530 *f = (*f / mean).clamp(0.25, 4.0);
12531 }
12532 TPL_NANOS.fetch_add(
12533 start.elapsed().as_nanos() as u64,
12534 std::sync::atomic::Ordering::Relaxed,
12535 );
12536 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
12537 let mut hist = [0usize; 8];
12538 for &f in &out {
12539 hist[((f * 4.0) as usize).min(7)] += 1;
12540 }
12541 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
12542 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
12543 eprintln!(
12544 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
12545 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
12546 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
12547 );
12548 }
12549 (out, ratio)
12550}
12551
12552/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
12553/// references name, which slot it refreshes, whether it is shown when it is
12554/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
12555/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
12556/// 0/2 alternation, every frame shown, every reference in the past).
12557///
12558/// The sign bias is carried rather than derived here because only the caller
12559/// knows what order hint each slot holds; it is armed onto the tile writer
12560/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
12561/// the writer scans the same stacks the decoder will.
12562#[derive(Debug, Clone, Copy)]
12563pub(crate) struct PyramidFrame {
12564 /// The slot `LAST_FRAME` (and every reference this encoder does not name
12565 /// apart) reads.
12566 pub last_slot: u8,
12567 /// The single slot `refresh_frame_flags` sets.
12568 pub self_slot: u8,
12569 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
12570 /// pyramid, which is what makes `sign_bias`'s last entry true.
12571 pub altref_slot: u8,
12572 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
12573 /// picture (the leaf chain alternates its refresh between two slots, so
12574 /// the frame before `LAST` is still intact). `None` leaves
12575 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
12576 /// wrote before, and the caller then passes no `last2` picture either.
12577 pub last2_slot: Option<u8>,
12578 /// `show_frame`: false for a hidden frame, output later by a
12579 /// `show_existing_frame` header.
12580 pub show_frame: bool,
12581 /// lane-arfq: which level's `delta_q` strength this frame reads
12582 /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid
12583 /// one share `Level::Arf` and differ only by their q offset.
12584 pub dq_level: DqLevel,
12585 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
12586 pub sign_bias: crate::mvstack::SignBiasTable,
12587}
12588
12589/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
12590/// `temporal_filter` in the small: every 16x16 luma block of `src` is
12591/// motion-compensated from each picture of `window` (the group's own display
12592/// neighbours, nearest first) and averaged in with weight
12593/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
12594/// nothing and one that matches well cancels the grain the block's residual
12595/// would otherwise have to code.
12596///
12597/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
12598/// rides the luma block's own vector (halved), which is what libaom does at
12599/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
12600/// grid tiles it exactly.
12601///
12602/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
12603/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
12604/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
12605/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
12606/// quality the ARF is coded at, so the substitution itself costs little.
12607// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and
12608// `ARF_TF_WIN_FUT` future ones); this takes every picture in it.
12609pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
12610 const SIDE: usize = 16;
12611 let neighbours: Vec<&Picture> = window
12612 .iter()
12613 .filter(|p| p.width == src.width && p.height == src.height)
12614 .collect();
12615 if neighbours.is_empty() || strength <= 0.0 {
12616 return src.clone();
12617 }
12618 let mut out = src.clone();
12619 // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
12620 // `None` when the displaced block leaves the picture.
12621 let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
12622 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
12623 if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
12624 return None;
12625 }
12626 let (sy, sx) = (sy as usize, sx as usize);
12627 let mut acc = 0u64;
12628 for row in 0..SIDE {
12629 let c = &src.y[(by + row) * src.width + bx..][..SIDE];
12630 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
12631 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
12632 }
12633 Some((acc, (sy, sx)))
12634 };
12635 // The log-step diamond `arf_pred_census` priced this with.
12636 let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
12637 let mut best = sad(r, bx, by, (0, 0))?;
12638 let mut centre = (0isize, 0isize);
12639 let mut step = 16isize;
12640 while step >= 1 {
12641 let from = centre;
12642 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
12643 let mv = (from.0 + dy * step, from.1 + dx * step);
12644 if let Some(s) = sad(r, bx, by, mv) {
12645 if s.0 < best.0 {
12646 best = s;
12647 centre = mv;
12648 }
12649 }
12650 }
12651 step /= 2;
12652 }
12653 Some(best.1)
12654 };
12655 let (cw, ch) = (src.width / 2, src.height / 2);
12656 for by in (0..src.height).step_by(SIDE) {
12657 for bx in (0..src.width).step_by(SIDE) {
12658 if by + SIDE > src.height || bx + SIDE > src.width {
12659 continue;
12660 }
12661 let mut y_acc = vec![0f64; SIDE * SIDE];
12662 let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
12663 let mut wsum = 1.0f64;
12664 // Chroma keeps its OWN weight sum: an edge block whose halved
12665 // vector leaves the chroma plane contributes to luma only, and
12666 // dividing chroma by the luma sum would darken it (class
12667 // `metric blind to a plane`, on the encoder side).
12668 let mut cwsum = 1.0f64;
12669 for row in 0..SIDE {
12670 for col in 0..SIDE {
12671 y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
12672 }
12673 }
12674 for row in 0..SIDE / 2 {
12675 for col in 0..SIDE / 2 {
12676 let i = (by / 2 + row) * cw + bx / 2 + col;
12677 c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
12678 c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
12679 }
12680 }
12681 for r in &neighbours {
12682 let Some((sy, sx)) = search(r, bx, by) else { continue };
12683 let mut sse = 0f64;
12684 for row in 0..SIDE {
12685 for col in 0..SIDE {
12686 let d = f64::from(src.y[(by + row) * src.width + bx + col])
12687 - f64::from(r.y[(sy + row) * r.width + sx + col]);
12688 sse += d * d;
12689 }
12690 }
12691 let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
12692 for row in 0..SIDE {
12693 for col in 0..SIDE {
12694 y_acc[row * SIDE + col] +=
12695 w * f64::from(r.y[(sy + row) * r.width + sx + col]);
12696 }
12697 }
12698 // Chroma reads the luma vector halved; a block on the picture
12699 // edge whose halved vector would leave the chroma plane is
12700 // left to luma alone rather than clamped to a different
12701 // displacement than the luma it must stay registered with.
12702 let (cy, cx) = (sy / 2, sx / 2);
12703 if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
12704 for row in 0..SIDE / 2 {
12705 for col in 0..SIDE / 2 {
12706 let i = (cy + row) * cw + cx + col;
12707 c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
12708 c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
12709 }
12710 }
12711 cwsum += w;
12712 }
12713 wsum += w;
12714 }
12715 for row in 0..SIDE {
12716 for col in 0..SIDE {
12717 out.y[(by + row) * src.width + bx + col] =
12718 (y_acc[row * SIDE + col] / wsum).round() as u16;
12719 }
12720 }
12721 for row in 0..SIDE / 2 {
12722 for col in 0..SIDE / 2 {
12723 let i = (by / 2 + row) * cw + bx / 2 + col;
12724 out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
12725 out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
12726 }
12727 }
12728 }
12729 }
12730 out
12731}
12732
12733/// Encodes one picture as an inter frame predicting from `reference`'s
12734/// reconstruction, which the caller decoded (or, for the frame right after
12735/// the key frame, is the key frame's own reconstruction).
12736pub(crate) fn encode_inter_frame(
12737 picture: &Picture,
12738 reference: &Picture,
12739 base_q_idx: u8,
12740 deadzone: f64,
12741 order_hint: u32,
12742 // The order hint each of the seven `ref_frame_idx` entries names, which a
12743 // decoder reads out of its own reference state -- only spec 5.9.22's
12744 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
12745 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
12746 // callers that follow this crate's own flat slot plan.
12747 order_hints: [u32; 7],
12748 render: (usize, usize),
12749 // The tables this frame's writer starts from: what the previous frame
12750 // stored into the slot this one's `primary_ref_frame` names. `None`
12751 // starts from the defaults, which is right only for the frame straight
12752 // after a key frame.
12753 start_cdfs: Option<&crate::cdf_state::Cdfs>,
12754 // The key frame's own (padded) reconstruction, which every frame of the
12755 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
12756 // with `LAST_FRAME` alone, exactly as before.
12757 golden: Option<&Picture>,
12758 // The frame two back, held in the slot this frame is about to refresh
12759 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
12760 // inter frames of a GOP, where the frame two back IS the key frame.
12761 altref: Option<&Picture>,
12762 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
12763 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
12764 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
12765 // take. `None` (every caller but the pyramid leaves) codes the frame
12766 // with the reference set unchanged.
12767 last2: Option<&Picture>,
12768 fctx: &crate::decode::FrameCtx,
12769 // Where this frame sits in the coding-order pyramid; `None` is the flat
12770 // one-shown-frame-per-picture stream this encoder wrote before.
12771 pyramid: Option<PyramidFrame>,
12772 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
12773 // them), padded like this one -- the lookahead window the per-block
12774 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
12775 // EMPTY slice codes the frame at one lambda, as before.
12776 lookahead: &[Picture],
12777) -> Result<Encoded> {
12778 picture.check()?;
12779 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
12780 return Err(Error::unsupported(
12781 "AV1 encode",
12782 "an inter frame is coded only for a picture that is a whole number \
12783 of 64x64 superblocks -- the inter tile writer never splits a \
12784 superblock's partition below that",
12785 ));
12786 }
12787 if reference.width != picture.width || reference.height != picture.height {
12788 return Err(Error::unsupported(
12789 "AV1 encode",
12790 "the reference picture must be the same size as the one being coded",
12791 ));
12792 }
12793
12794 // The single slot this crate's inter frames ever predict from or
12795 // refresh (`inter_frame_headers`'s contract): every frame both reads and
12796 // overwrites slot 0, so the frame just coded is always what the next one
12797 // predicts against.
12798 const LAST_SLOT: u8 = 0;
12799 // Slot 0 and slot 2 alternate so the frame two back survives one more
12800 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
12801 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
12802 // in the very slot it will overwrite.
12803 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
12804 let last_slot = pyramid.map_or(
12805 if order_hint <= 1 {
12806 LAST_SLOT
12807 } else if (order_hint - 1) % 2 == 1 {
12808 0
12809 } else {
12810 2
12811 },
12812 |p| p.last_slot,
12813 );
12814 // `render`, not `picture.width`/`picture.height`: `picture` here is
12815 // already padded to a whole number of superblocks (`encode_sequence`'s
12816 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
12817 // every true-edge clamp downstream) must come from the frame's real,
12818 // unpadded size, same as `key_frame_headers_colour` takes `render` and
12819 // not the padded picture in `encode_key_frame_inner`.
12820 let (seq, mut header) = inter_frame_headers_slots(
12821 render.0,
12822 render.1,
12823 base_q_idx,
12824 order_hint,
12825 last_slot,
12826 self_slot,
12827 match pyramid {
12828 Some(p) => p.altref_slot,
12829 None if altref.is_some() => self_slot,
12830 None => GOLDEN_SLOT,
12831 },
12832 )?;
12833 header.render_width = render.0 as u32;
12834 header.render_height = render.1 as u32;
12835 // lane-refs: this frame's motion-compensation kernel, written into the
12836 // header AND armed on the context every prediction reads, in one place so
12837 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
12838 // tile decodes to different pixels than the encoder scored).
12839 header.interpolation_filter = frame_interp_filter();
12840 fctx.interp_filter.set(mc::InterpFilterKind::from_header(header.interpolation_filter));
12841 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
12842 // The order hint behind each `ref_frame_idx` entry. The flat path's own
12843 // slot plan (`inter_frame_headers_slots`) is: every reference but
12844 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
12845 // `ALTREF_FRAME`, which reads the frame two back when there is one;
12846 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
12847 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
12848 header.order_hints = order_hints;
12849 // lane-last2: `inter_frame_headers_slots` points every un-named
12850 // reference at `last_slot`; the pyramid's leaf chain retains a second,
12851 // older picture and names it here. The caller's `sign_bias` /
12852 // `order_hints` entry 1 is derived from this same slot, so the stack
12853 // scans and `skipModeAllowed` read what the decoder will.
12854 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
12855 header.ref_frame_idx[1] = slot;
12856 }
12857 header.reference_select = reference_select();
12858 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
12859 // per-reference order-hint distance is read by the block SEARCH, which
12860 // runs long before the writer arms these (the distance-scaled search step
12861 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
12862 // never reached the tool).
12863 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
12864 // lane-hpmv: armed here for the same reason the order hints are -- the
12865 // block SEARCH reads it (its eighth-pel stage) long before the writer.
12866 let hp_mv = header.allow_high_precision_mv;
12867 crate::tile::arm_high_precision_mv(hp_mv);
12868 if let Some(p) = pyramid {
12869 header.show_frame = p.show_frame;
12870 header.showable_frame = !p.show_frame;
12871 header.ref_frame_sign_bias = p.sign_bias;
12872 }
12873 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
12874 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
12875 // block inside this frame codes and searches its own `tx_depth`, the same
12876 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
12877 let tx_select = tx_select() && tx_select_inter();
12878 if tx_select {
12879 header.tx_mode = TxMode::Select;
12880 }
12881
12882 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
12883 // lane-palw: the encoder's own in-process reconstruct reads its palette
12884 // colour-index maps back through `decode::palette_onscreen`, which takes
12885 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
12886 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
12887 // them here so the reconstruct clamps a block cut by the frame edge
12888 // exactly as the writer now does.
12889 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
12890 fctx.seg_mi_dims.set(frame_mi_dims);
12891 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
12892 // here (see `encode_key_frame_inner`).
12893 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
12894 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
12895 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
12896 // This frame's own `allow_screen_content_tools`. It can only be set when
12897 // the SEQUENCE offers the bit at all, which is the key frame's decision
12898 // ([`SEQ_SCREEN`]): a frame header that contradicts
12899 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
12900 // encode.
12901 let screen = seq_screen()
12902 && screen_content(&picture_y8, picture.width, true_width, true_height);
12903 header.allow_screen_content_tools = screen;
12904 // lane-txi, as on the key frame: the header bit the writer's own
12905 // `Cdfs` then reads for every luma `tx_type` symbol.
12906 header.reduced_tx_set = !wide_tx_set(screen);
12907 // lane-intertx, desync (a): the frame context this value is read back
12908 // through ([`decode::reduce_inherited_chroma_tx_type`] inside
12909 // `recode_inter_chroma`, and every inter decode helper the search's own
12910 // trial decode shares) must carry THIS frame's bit, not whatever the
12911 // previous frame's trial decode last left in the shared cell -- a stale
12912 // `true` here narrows the chroma allowance the search reconstructs
12913 // against under the one the header's bit actually allows.
12914 fctx.reduced_tx_set_inter.set(header.reduced_tx_set);
12915 // The search prices coefficients against the tables this frame's writer
12916 // starts from, not against the defaults (lane-av1txbits) -- but only on a
12917 // frame the screen detector said no to (lane-av1price2): armed HERE, after
12918 // `screen` exists, and again on every search/tile worker below.
12919 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
12920 let mut luma = Plane {
12921 source: &picture_y8,
12922 reconstruction: vec![128; picture_y8.len()],
12923 width: picture.width,
12924 height: picture.height,
12925 true_width,
12926 true_height,
12927 tile_x0: 0,
12928 tile_y0: 0,
12929 tile_x1: picture.width,
12930 tile_y1: picture.height,
12931 ctx: CoefCtxMap::default(),
12932 };
12933 let mut chroma = [
12934 Plane {
12935 source: &picture_u8,
12936 reconstruction: vec![128; picture_u8.len()],
12937 width: picture.width / 2,
12938 height: picture.height / 2,
12939 true_width: true_width / 2,
12940 true_height: true_height / 2,
12941 tile_x0: 0,
12942 tile_y0: 0,
12943 tile_x1: picture.width / 2,
12944 tile_y1: picture.height / 2,
12945 ctx: CoefCtxMap::default(),
12946 },
12947 Plane {
12948 source: &picture_v8,
12949 reconstruction: vec![128; picture_v8.len()],
12950 width: picture.width / 2,
12951 height: picture.height / 2,
12952 true_width: true_width / 2,
12953 true_height: true_height / 2,
12954 tile_x0: 0,
12955 tile_y0: 0,
12956 tile_x1: picture.width / 2,
12957 tile_y1: picture.height / 2,
12958 ctx: CoefCtxMap::default(),
12959 },
12960 ];
12961
12962 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
12963 let top_arf = matches!(
12964 pyramid,
12965 Some(p) if p.dq_level == DqLevel::TopArf
12966 );
12967 let arfmode_v = arfmode();
12968 let search = Search {
12969 base_q_idx,
12970 deadzone,
12971 lambda: lambda_scale()
12972 * match pyramid {
12973 Some(p) if !p.show_frame => hidden_lambda_factor(),
12974 _ => 1.0,
12975 }
12976 * step
12977 * step,
12978 modes: &KEY_FRAME_MODES,
12979 top_k: prune_top_k_inter(),
12980 screen,
12981 // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose
12982 // offset is the pyramid's own `arf_q_offset`) reads its leaf offer
12983 // set from [`crate::speed::ARFMODE`]; every other frame -- the mid
12984 // and quarter hidden frames, the leaves, the flat path -- keeps the
12985 // full set.
12986 arf_leaf_intra: !top_arf || arfmode_v & 1 == 0,
12987 arf_leaf8: !top_arf || arfmode_v & 2 == 0,
12988 arf_leaf_compound: !top_arf || arfmode_v & 4 == 0,
12989 };
12990 let mode_bits_table = inter_mode_bits();
12991 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
12992 // this frame the NEXT one predicts from. Off (`None`) without a
12993 // lookahead picture or at strength 0.
12994 let tpl_k = tpl_strength();
12995 let window: Vec<&Picture> = lookahead
12996 .iter()
12997 .take_while(|n| n.width == picture.width && n.height == picture.height)
12998 .collect();
12999 let tpl_sources: Vec<Vec<u8>> =
13000 window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect();
13001 let tpl_cells_x = picture.width / 16;
13002 // `.1` is the propagating map's raw per-cell dependence ratio, which only
13003 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
13004 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> =
13005 (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| {
13006 if tpl_propagating() {
13007 let mut frames: Vec<&[u8]> = vec![&picture_y8];
13008 frames.extend(tpl_sources.iter().map(Vec::as_slice));
13009 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
13010 (f, Some(r))
13011 } else {
13012 // The shipped map is one factor per 64x64; it is spread over that
13013 // superblock's own 16 cells so the application site below (which
13014 // averages the four cells of a 32x32 block) reads exactly the
13015 // superblock factor, whichever map fed it.
13016 let map =
13017 tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
13018 let cells_y = picture.height / 16;
13019 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
13020 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
13021 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
13022 .collect();
13023 (f, None)
13024 }
13025 });
13026 let (tpl_factors, tpl_ratio) = match tpl_both {
13027 Some((f, r)) => (Some(f), r),
13028 None => (None, None),
13029 };
13030
13031 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
13032 // coding surface's: `blocks` carries one entry per 32x32 block the tile
13033 // writer will actually visit, same count it checks `blocks.len()`
13034 // against, which is fewer than the padded surface's own block count
13035 // whenever the true size is not a 64x64 multiple.
13036 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
13037 let (cols, rows) = (cols as usize, rows as usize);
13038 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
13039 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
13040 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
13041 // only when the map is, and `delta_q_res` follows straight into the frame
13042 // header (`write_delta_q_params`) and into the tile writer's own plan.
13043 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
13044 // measured the per-superblock quantizer as a win on both films and a
13045 // 0.5 loss vs libaom on the desktop capture, so a frame that set
13046 // `allow_screen_content_tools` codes no delta syntax at all and stays
13047 // byte-identical to the pre-lane encoder.
13048 // lane-arfq: the level whose `delta_q` strength this frame reads; the
13049 // flat path (no pyramid) is a leaf.
13050 let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level);
13051 let deltaq_res: Option<i32> = tpl_factors
13052 .as_ref()
13053 .filter(|_| !screen)
13054 .and(deltaq_res_log2().map(|r| 1i32 << r));
13055 // The same 16-cell mean the superblock's own lambda takes, clamped to the
13056 // map the frame actually has -- read over the factors or over the raw
13057 // dependence ratios, whichever mapping is asking.
13058 let sb_mean = |m: &[f64], sb: usize| {
13059 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
13060 (0..16)
13061 .map(|i| {
13062 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
13063 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
13064 })
13065 .sum::<f64>()
13066 / 16.0
13067 };
13068 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
13069 // raw dependence ratio; without it (and always without a ratio map, i.e.
13070 // on the one-frame area map) the shipped derivation stands.
13071 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
13072 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
13073 match (libaom, tpl_ratio.as_deref(), r_frame) {
13074 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
13075 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
13076 }
13077 };
13078 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
13079 (Some(f), Some(res)) => {
13080 let libaom = dq_tpl_strength(dq_level);
13081 let mut g: Vec<u8> =
13082 (0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect();
13083 // lane-b128m: under 128 superblocks the delta_q syntax is coded
13084 // ONCE per 128 root (the reader's own unit), so all four 64x64
13085 // cells of a root have to be searched -- and quantized -- at the
13086 // one qindex the root's top-left cell codes.
13087 if sb128_on() {
13088 for sb_r in 0.._sb_rows {
13089 for sb_c in 0..sb_cols {
13090 let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
13091 g[sb_r * sb_cols + sb_c] = q;
13092 }
13093 }
13094 }
13095 Some(g)
13096 }
13097 _ => None,
13098 };
13099 // lane-dq census: both mappings on the SAME superblocks, whether or not
13100 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
13101 // off, and the census then prices the default `res = 4` grid).
13102 if dq_census() {
13103 if let Some(f) = &tpl_factors {
13104 let res = deltaq_res.unwrap_or(4);
13105 let off = |libaom: Option<f64>| -> Vec<i32> {
13106 (0..sb_cols * _sb_rows)
13107 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
13108 .collect()
13109 };
13110 let strength = dq_tpl_strength(dq_level);
13111 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
13112 let coded = match (deltaq_res.is_some(), strength) {
13113 (false, _) => "none".to_string(),
13114 (true, None) => "ours".to_string(),
13115 (true, Some(k)) => format!("libaom k={k}"),
13116 };
13117 eprintln!(
13118 "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
13119 sb_cols * _sb_rows,
13120 r_frame.unwrap_or(f64::NAN),
13121 dq_summary(&ours),
13122 dq_summary(&aom),
13123 );
13124 }
13125 }
13126 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
13127 header.delta.q_present = true;
13128 header.delta.q_res = res.trailing_zeros() as u8;
13129 }
13130 // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
13131 // below, so the root search prices the group the writer really codes.
13132 let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
13133 if let Some(g) = &sb_q {
13134 let mut levels: Vec<u8> = g.clone();
13135 levels.sort_unstable();
13136 levels.dedup();
13137 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
13138 }
13139 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
13140 // This frame's tile grid, as in `encode_key_frame_inner`.
13141 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
13142 let layout =
13143 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
13144 header.tile_info = tile_info_of(&layout, 1);
13145 let header_tile_info = header.tile_info.clone();
13146 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
13147 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
13148 // once per frame (lane-av1rd2), not once per block, which is a whole
13149 // plane's map per 32x32 block and now per leaf too.
13150 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
13151 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
13152 // availability -- intra edges and the MV stack's scans alike -- already
13153 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
13154 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
13155 // giving each job its own planes and its own `MiGrid` therefore leaves
13156 // every decision, and so every coded bit, exactly where the whole-frame
13157 // loop left it, at any tile count and any thread count.
13158 let (frame_width, frame_height) = (picture.width, picture.height);
13159 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
13160 let [cb, cr] = &mut chroma;
13161 let chroma_out = [
13162 crate::par::Shared::new(&mut cb.reconstruction),
13163 crate::par::Shared::new(&mut cr.reconstruction),
13164 ];
13165 let search_tile = |index: usize,
13166 fctx: &crate::decode::FrameCtx|
13167 -> Result<Vec<(usize, Quadrant)>> {
13168 // Thread-local, and this job may be running on a `search_tiles`
13169 // worker: `ref_distance`'s order-hint distance (the scaled motion
13170 // search step) is read by the SEARCH, so every worker arms it or the
13171 // tile's bits depend on the thread count.
13172 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
13173 crate::tile::arm_high_precision_mv(hp_mv);
13174 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
13175 let rect = layout.rect(index);
13176 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
13177 let mut chroma = [
13178 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
13179 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
13180 ];
13181 clip_planes_to_tile(&mut luma, &mut chroma, rect);
13182 let mut grid = MiGrid::new(mi_cols, mi_rows);
13183 grid.set_sign_bias(sign_bias);
13184 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
13185 // built once per tile job (`obmc_prediction`).
13186 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
13187 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
13188 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
13189 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
13190 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
13191 grid.set_tile_bounds(
13192 rect.mi_row0 as usize,
13193 rect.mi_col0 as usize,
13194 rect.mi_row1 as usize,
13195 rect.mi_col1 as usize,
13196 );
13197 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
13198 // lane-b128: under a 128x128 superblock the search walks the roots the
13199 // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
13200 // not plain raster -- a search that visits BL before TR builds every mv
13201 // stack and neighbour context off blocks the writer has not coded yet,
13202 // which is what made the write-time drl clamp fire at all (lane-sb128b).
13203 // At a 64 superblock the two orders are identical and this is the same
13204 // raster loop as before.
13205 let sb128_search = sb128_on();
13206 let root_step = if sb128_search { 2 } else { 1 };
13207 let mut roots: Vec<(usize, usize)> = Vec::new();
13208 {
13209 let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
13210 let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
13211 let mut r = r0;
13212 while r < r1 {
13213 let mut c = c0;
13214 while c < c1 {
13215 roots.push((r, c));
13216 c += root_step;
13217 }
13218 r += root_step;
13219 }
13220 }
13221 for (root_r, root_c) in roots {
13222 // The 64x64 cells of this root, in the writer's own order.
13223 let cells: Vec<(usize, usize)> = if sb128_search {
13224 [(0, 0), (0, 1), (1, 0), (1, 1)]
13225 .into_iter()
13226 .map(|(dr, dc)| (root_r + dr, root_c + dc))
13227 .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
13228 .collect()
13229 } else {
13230 vec![(root_r, root_c)]
13231 };
13232 // What the four cells below really cost, against which the whole
13233 // 128x128 candidate is weighed.
13234 let mark128 = blocks.len();
13235 let mut root_cost = 0.0f64;
13236 // The 128 root's own compound pairs, at its 32x32-mi window (the 64
13237 // root builds the same list one size down, per superblock).
13238 let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13239 if header.reference_select && b128_compound() && !screen && sb128_search {
13240 [
13241 (crate::mvstack::GOLDEN_FRAME, golden),
13242 (crate::mvstack::ALTREF_FRAME, altref),
13243 ]
13244 .into_iter()
13245 .filter_map(|(r, pic)| {
13246 pic.map(|p| {
13247 (
13248 r,
13249 p,
13250 crate::mvstack::find_mv_stack_compound(
13251 &grid,
13252 root_r * 16,
13253 root_c * 16,
13254 32,
13255 32,
13256 (crate::mvstack::LAST_FRAME, r),
13257 mi_cols,
13258 mi_rows,
13259 grid.sign_bias_table(),
13260 &[(0, 0); 7],
13261 None,
13262 ),
13263 )
13264 })
13265 })
13266 .collect()
13267 } else {
13268 Vec::new()
13269 };
13270 let root128 = (sb128_search && b128_root() && cells.len() == 4)
13271 .then(|| search_root_128(
13272 &mut luma,
13273 &mut chroma,
13274 &grid,
13275 (root_r, root_c),
13276 (rows, cols),
13277 (header.mi_cols, header.mi_rows),
13278 search,
13279 &tpl_factors,
13280 sb_q.as_ref(),
13281 sb_cols,
13282 tpl_cells_x,
13283 base_q_idx,
13284 dq_res,
13285 reference,
13286 &root_compound,
13287 fctx,
13288 ))
13289 .flatten();
13290 // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
13291 // are priced; the cheaper one competes with the NONE block and with
13292 // the four superblocks below.
13293 let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
13294 let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
13295 .then(|| {
13296 let mut best: Option<(bool, _)> = None;
13297 for horz in [true, false] {
13298 if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
13299 continue;
13300 }
13301 let Some(found) = search_root_128_rect(
13302 &mut luma,
13303 &mut chroma,
13304 &mut grid,
13305 (root_r, root_c),
13306 (rows, cols),
13307 (header.mi_cols, header.mi_rows),
13308 search,
13309 &tpl_factors,
13310 sb_q.as_ref(),
13311 sb_cols,
13312 tpl_cells_x,
13313 base_q_idx,
13314 dq_res,
13315 reference,
13316 &root_compound,
13317 horz,
13318 fctx,
13319 ) else {
13320 continue;
13321 };
13322 if best.as_ref().is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) {
13323 best = Some((horz, found));
13324 }
13325 }
13326 best
13327 })
13328 .flatten();
13329 // lane-ab128: and the same root as one of the four AB shapes -- two
13330 // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
13331 // the cheapest joins the candidate list below.
13332 let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
13333 let root_ab = (sb128_search
13334 && (b128_ab() || forced_ab != 0)
13335 && cells.len() == 4
13336 && forced_rect == 0)
13337 .then(|| {
13338 let mut best: Option<(usize, _)> = None;
13339 for symbol in 4..=7usize {
13340 if forced_ab != 0 && usize::from(forced_ab) != symbol {
13341 continue;
13342 }
13343 let Some(found) = search_root_128_ab(
13344 &mut luma,
13345 &mut chroma,
13346 &mut grid,
13347 (root_r, root_c),
13348 (rows, cols),
13349 (header.mi_cols, header.mi_rows),
13350 search,
13351 &tpl_factors,
13352 sb_q.as_ref(),
13353 sb_cols,
13354 tpl_cells_x,
13355 base_q_idx,
13356 reference,
13357 &root_compound,
13358 symbol,
13359 fctx,
13360 ) else {
13361 continue;
13362 };
13363 if best.as_ref().is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0) {
13364 best = Some((symbol, found));
13365 }
13366 }
13367 best
13368 })
13369 .flatten();
13370 for (sb_r, sb_c) in cells {
13371 // lane-b64: the whole superblock as ONE 64x64 block, tried before
13372 // its quadrants are (`search_skip_64`) and compared against the
13373 // four of them below. Only a superblock wholly inside the true
13374 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
13375 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
13376 // only that the block's half is inside, and the trial is ranked
13377 // over the inside part alone ([`Plane::block_sse`]).
13378 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
13379 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
13380 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
13381 && x64 + SUPERBLOCK <= luma.true_width
13382 && y64 + SUPERBLOCK <= luma.true_height;
13383 let edge_inside = b64_edge()
13384 && crate::tile::has_half(
13385 sb_c as u32 * crate::tile::SB_MI,
13386 crate::tile::SB_MI,
13387 header.mi_cols,
13388 )
13389 && crate::tile::has_half(
13390 sb_r as u32 * crate::tile::SB_MI,
13391 crate::tile::SB_MI,
13392 header.mi_rows,
13393 );
13394 let sb64_legal = b64_root()
13395 && sb_r * 2 + 1 < rows
13396 && sb_c * 2 + 1 < cols
13397 && (whole_inside || edge_inside);
13398 // One lambda for the whole superblock, the same mean the 32x32
13399 // level takes over its own four tpl cells: the 64-vs-four-32
13400 // comparison below weighs one cost against four, so both sides
13401 // have to be priced at the same lambda.
13402 let sb_search = match &tpl_factors {
13403 // lane-deltaq: with a per-superblock quantizer the lambda
13404 // comes from that quantizer, not from the raw map factor --
13405 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
13406 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),
13407 Some(f) if sb64_legal => {
13408 let mean = (0..16)
13409 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
13410 .sum::<f64>()
13411 / 16.0;
13412 Search { lambda: search.lambda * mean, ..search }
13413 }
13414 _ => search,
13415 };
13416 let mark = blocks.len();
13417 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
13418 let mut sb_cost = 0.0f64;
13419 if sb64_legal {
13420 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
13421 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
13422 let stack =
13423 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
13424 // lane-b64b: the `LAST` + extra-reference pairs at this
13425 // superblock's own 16x16-mi window, the same stacks the tile
13426 // writer's `Whole64` arm rebuilds. Empty unless the frame
13427 // codes `reference_select`, which is what gates the syntax.
13428 // `!screen` for the same reason the residual arm is gated
13429 // there ([`b64_residual`]): a desktop capture's superblocks
13430 // are flat runs the skip arm already codes for nothing, and
13431 // MEASURED, compound at the root cost it +33.4/-23.8 ->
13432 // +33.7/-23.6 while both film rows gained (step 1's table).
13433 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13434 if header.reference_select && b64_compound() && !screen {
13435 [
13436 (crate::mvstack::GOLDEN_FRAME, golden),
13437 (crate::mvstack::ALTREF_FRAME, altref),
13438 ]
13439 .into_iter()
13440 .filter_map(|(r, pic)| {
13441 pic.map(|p| {
13442 (
13443 r,
13444 p,
13445 crate::mvstack::find_mv_stack_compound(
13446 &grid,
13447 mi_row,
13448 mi_col,
13449 16,
13450 16,
13451 (crate::mvstack::LAST_FRAME, r),
13452 mi_cols,
13453 mi_rows,
13454 grid.sign_bias_table(),
13455 &[(0, 0); 7],
13456 None,
13457 ),
13458 )
13459 })
13460 })
13461 .collect()
13462 } else {
13463 Vec::new()
13464 };
13465 if let Some((cost, block)) = search_skip_64(
13466 &mut luma,
13467 &mut chroma,
13468 (x64, y64),
13469 (SUPERBLOCK, SUPERBLOCK),
13470 &sb_search,
13471 b64_residual() && !screen,
13472 reference,
13473 &stack,
13474 &sb_compound,
13475 fctx,
13476 ) {
13477 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
13478 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
13479 let cost = cost
13480 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
13481 sb64 = Some((cost, block, after));
13482 }
13483 }
13484 // A superblock whose 64x64 trial already codes almost nothing per
13485 // pixel is taken outright and its quadrants are never searched --
13486 // the same `split_rd_breakout` shape the 32x32 level uses one
13487 // size up, and where this lever BUYS wall instead of spending it.
13488 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
13489 split_rd_breakout_at(
13490 b64_breakout_threshold(),
13491 *c,
13492 SUPERBLOCK,
13493 sb_search.lambda,
13494 )
13495 });
13496 for quadrant in 0..if early64 { 0 } else { 4 } {
13497 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
13498 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
13499 // decision under it (partition, mode, tx, motion) reads
13500 // `search.lambda`, so scaling the one field here scales all
13501 // of them. 32x32 and not the 16x16 the map is built at
13502 // because the whole-vs-split comparison right below weighs
13503 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
13504 // would make those two numbers incomparable.
13505 let search = match &tpl_factors {
13506 // lane-deltaq: the quantizer is a SUPERBLOCK-level
13507 // symbol, so all four quadrants take their superblock's
13508 // own qindex and the lambda it implies. No granularity is
13509 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
13510 // factor per superblock, shared by its sixteen cells.
13511 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),
13512 Some(f) => {
13513 let mean = (0..4)
13514 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
13515 .sum::<f64>()
13516 / 4.0;
13517 Search { lambda: search.lambda * mean, ..search }
13518 }
13519 None => search,
13520 };
13521 // Same filter as the tile writer's: a quadrant whose own mi
13522 // origin is not inside the true frame is never coded.
13523 if r32 >= rows || c32 >= cols {
13524 continue;
13525 }
13526 // spec `decode_partition`'s hasRows/hasCols recomputed at this
13527 // 32x32 block's own half (`crate::tile::has_half`), same as
13528 // the key frame search: the true frame edge can fall inside a
13529 // quadrant a superblock-level check already let through, and
13530 // such a quadrant cannot be left whole -- it must split into
13531 // the 16x16 leaves that are actually inside the true frame
13532 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
13533 // arm).
13534 let (has_cols32, has_rows32) = (
13535 crate::tile::has_half(
13536 c32 as u32 * crate::tile::BLOCK_MI,
13537 crate::tile::BLOCK_MI,
13538 header.mi_cols,
13539 ),
13540 crate::tile::has_half(
13541 r32 as u32 * crate::tile::BLOCK_MI,
13542 crate::tile::BLOCK_MI,
13543 header.mi_rows,
13544 ),
13545 );
13546 if has_cols32 && has_rows32 {
13547 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
13548 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
13549 let stack =
13550 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
13551 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
13552 (crate::mvstack::LAST2_FRAME, last2),
13553 (crate::mvstack::GOLDEN_FRAME, golden),
13554 (crate::mvstack::ALTREF_FRAME, altref),
13555 ]
13556 .into_iter()
13557 .filter_map(|(r, pic)| {
13558 pic.map(|p| {
13559 (
13560 r,
13561 p,
13562 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
13563 )
13564 })
13565 })
13566 .collect();
13567 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
13568 .iter()
13569 .map(|(r, p, st)| (*r, *p, st))
13570 .collect();
13571 // The COMPOUND stack of each `LAST` + extra pair, off the
13572 // same grid (and the same armed sign bias) the tile writer
13573 // rebuilds it from. Empty unless this frame codes
13574 // `reference_select`, which is what gates the syntax.
13575 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13576 if header.reference_select {
13577 extra_stacks
13578 .iter()
13579 .map(|&(r, p, _)| {
13580 (
13581 r,
13582 p,
13583 crate::mvstack::find_mv_stack_compound(
13584 &grid,
13585 mi_row,
13586 mi_col,
13587 8,
13588 8,
13589 (crate::mvstack::LAST_FRAME, r),
13590 mi_cols,
13591 mi_rows,
13592 grid.sign_bias_table(),
13593 &[(0, 0); 7],
13594 None,
13595 ),
13596 )
13597 })
13598 .collect()
13599 } else {
13600 Vec::new()
13601 };
13602
13603 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
13604 let (block, mut cost_whole) = search_inter_block(
13605 &mut luma,
13606 &mut chroma,
13607 (x, y),
13608 &search,
13609 &mode_bits_table,
13610 reference,
13611 &stack,
13612 &extra,
13613 &compound,
13614 &grid,
13615 (mi_row, mi_col),
13616 (mi_rows, mi_cols),
13617 fctx,
13618 );
13619 cost_whole += search.lambda * partition_bits(BLOCK, false);
13620 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
13621
13622 // What four 16x16 leaves cost instead (spec
13623 // PARTITION_SPLIT at BLOCK_32X32, which
13624 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
13625 // already writes for a straddling quadrant). Each leaf is
13626 // searched against the reconstruction -- and the `mi`
13627 // grid -- the ones before it left, exactly as the writer
13628 // and the decoder will read them.
13629 //
13630 // A block the whole-32 search left skipped (no residual
13631 // at all) is not offered the split: libaom prunes the
13632 // same way at cpu-used 6, and it is where the wall would
13633 // otherwise go on static content.
13634 let leaf_positions: Vec<(usize, usize)> = (0..4)
13635 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
13636 .collect();
13637 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
13638 crate::tile::has_half(
13639 sc as u32 * crate::tile::SUB_MI,
13640 crate::tile::SUB_MI,
13641 header.mi_cols,
13642 ) && crate::tile::has_half(
13643 sr as u32 * crate::tile::SUB_MI,
13644 crate::tile::SUB_MI,
13645 header.mi_rows,
13646 )
13647 });
13648 // The breakout above: a 32x32 block that codes almost
13649 // nothing is not offered the split at all.
13650 let breakout = split_breakout_coeffs();
13651 let split = (!block.skip
13652 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
13653 && (breakout == 0 || block.luma.len() > 4 * breakout)
13654 && leaves_legal
13655 && split_inter_blocks())
13656 .then(|| {
13657 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
13658 let mut cost = search.lambda * partition_bits(BLOCK, true);
13659 let mut leaves = Vec::with_capacity(4);
13660 for &(sr, sc) in &leaf_positions {
13661 let (mi_row, mi_col) = (sr * 4, sc * 4);
13662 let (lx, ly) = (sc * SUB, sr * SUB);
13663 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
13664 let stack = find_mv_stack(
13665 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
13666 );
13667 let cstacks = leaf_compound_stacks(
13668 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
13669 header.reference_select, golden, altref,
13670 );
13671 let (leaf, leaf_cost) = code_square_inter(
13672 &mut luma,
13673 &mut chroma,
13674 (lx, ly),
13675 SUB,
13676 &search,
13677 &mode_bits_table,
13678 reference,
13679 &stack,
13680 &cstacks,
13681 &grid,
13682 (mi_row, mi_col),
13683 (mi_rows, mi_cols),
13684 &obmc_refs,
13685 fctx,
13686 );
13687 let leaf_cost = leaf_cost
13688 + search.lambda * partition_bits(SUB, false);
13689 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
13690
13691 // And what four 8x8 leaves cost instead --
13692 // the same tree one step further down, which
13693 // the writer codes as a real PARTITION_SPLIT
13694 // at BLOCK_16X16 (lane-av1rd2). Same
13695 // skipped-block prune as the level above.
13696 let eight = (!leaf.skip
13697 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
13698 && (breakout == 0 || leaf.luma.len() > breakout)
13699 && split_inter_8()
13700 // lane-arfmode: arm 2 makes 16x16 the top
13701 // ARF's leaf floor -- the RD-optional 8x8
13702 // comparison is not offered. Counted only
13703 // when every other prune let it through,
13704 // so the counter means "refused", not
13705 // "never considered". The spec-forced 8x8s
13706 // at a straddling 16x16 (the
13707 // `sub_positions` path below) are a
13708 // different site and stay.
13709 && (search.arf_leaf8 || arfmode_hit_and_no()))
13710 .then(|| {
13711 restore(
13712 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
13713 );
13714 let mut cost8 = search.lambda
13715 * (partition_bits(SUB, true)
13716 + 4.0 * partition_bits(8, false));
13717 let mut eight = Vec::with_capacity(4);
13718 for i in 0..4 {
13719 let (mr, mc) =
13720 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
13721 let stack8 = find_mv_stack(
13722 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
13723 );
13724 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13725 if header.reference_select && leaf_compound() {
13726 [
13727 (crate::mvstack::GOLDEN_FRAME, golden),
13728 (crate::mvstack::ALTREF_FRAME, altref),
13729 ]
13730 .into_iter()
13731 .filter_map(|(r, pic)| {
13732 pic.map(|p| {
13733 (
13734 r,
13735 p,
13736 crate::mvstack::find_mv_stack_compound(
13737 &grid, mr, mc, 2, 2,
13738 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
13739 grid.sign_bias_table(), &[(0, 0); 7], None,
13740 ),
13741 )
13742 })
13743 })
13744 .collect()
13745 } else {
13746 Vec::new()
13747 };
13748 let (leaf8, cost) = code_square_inter(
13749 &mut luma,
13750 &mut chroma,
13751 (lx + (i % 2) * 8, ly + (i / 2) * 8),
13752 8,
13753 &search,
13754 &mode_bits_table,
13755 reference,
13756 &stack8,
13757 &cstacks8,
13758 &grid,
13759 (mr, mc),
13760 (mi_rows, mi_cols),
13761 &obmc_refs,
13762 fctx,
13763 );
13764 cost8 += cost;
13765 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
13766 eight.push(leaf8);
13767 }
13768 (eight, cost8)
13769 });
13770 match eight {
13771 Some((eight, cost8)) if cost8 < leaf_cost => {
13772 partition_hit(3);
13773 cost += cost8;
13774 leaves.push(BlockCoeffs {
13775 eight: Some(eight),
13776 ..BlockCoeffs::default()
13777 });
13778 continue;
13779 }
13780 Some(_) => restore(
13781 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
13782 ),
13783 None => {}
13784 }
13785 partition_hit(2);
13786 cost += leaf_cost;
13787 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
13788 leaves.push(leaf);
13789 }
13790 (leaves, cost)
13791 });
13792 if let Some((leaves, cost)) = split {
13793 if cost < cost_whole {
13794 // The leaves' own `mi` cells are already in the
13795 // grid, and their reconstruction is what the
13796 // planes hold.
13797 partition_hit(1);
13798 sb_cost += cost;
13799 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
13800 continue;
13801 }
13802 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
13803 }
13804 partition_hit(0);
13805 sb_cost += cost_whole;
13806 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
13807 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
13808 } else {
13809 // The sub-positions actually inside the true frame, same
13810 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
13811 let sub_positions: Vec<(usize, usize)> = (0..4)
13812 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
13813 .filter(|&(sr, sc)| {
13814 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
13815 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
13816 })
13817 .collect();
13818 // Each leaf searches intra against its own `NEARESTMV`
13819 // candidate (`code_square_inter`), same real-inter choice
13820 // `search_inter_block` makes for a whole 32x32 block, at
13821 // this leaf's own 4x4-mi mv-stack window -- unless the
13822 // leaf's own half itself straddles the true edge, which
13823 // it codes as two (or one, at a true corner) 8x8 leaves
13824 // (`crate::tile::write_leaf8`'s inter counterpart),
13825 // mirroring the key frame search's straddling-16x16
13826 // handling above (lane-av1inter8).
13827 let mut leaves = Vec::with_capacity(sub_positions.len());
13828 for (sr, sc) in sub_positions {
13829 let (has_cols16, has_rows16) = (
13830 crate::tile::has_half(
13831 sc as u32 * crate::tile::SUB_MI,
13832 crate::tile::SUB_MI,
13833 header.mi_cols,
13834 ),
13835 crate::tile::has_half(
13836 sr as u32 * crate::tile::SUB_MI,
13837 crate::tile::SUB_MI,
13838 header.mi_rows,
13839 ),
13840 );
13841 if has_cols16 && has_rows16 {
13842 let (x, y) = (sc * SUB, sr * SUB);
13843 let (mi_row, mi_col) = (sr * 4, sc * 4);
13844 let stack = find_mv_stack(
13845 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
13846 );
13847 let cstacks = leaf_compound_stacks(
13848 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
13849 header.reference_select, golden, altref,
13850 );
13851 let (block, _) = code_square_inter(
13852 &mut luma,
13853 &mut chroma,
13854 (x, y),
13855 SUB,
13856 &search,
13857 &mode_bits_table,
13858 reference,
13859 &stack,
13860 &cstacks,
13861 &grid,
13862 (mi_row, mi_col),
13863 (mi_rows, mi_cols),
13864 &obmc_refs,
13865 fctx,
13866 );
13867 // One publication point for every coded leaf
13868 // (`record_mi`): this site used to spell the vote
13869 // out with `ref_frame` pinned to LAST and `mv1`
13870 // to (0,0), which is the encoder-grid-drift class
13871 // -- correct only for as long as a leaf can never
13872 // be compound.
13873 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
13874 leaves.push(block);
13875 } else {
13876 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
13877 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
13878 let mut eight = Vec::with_capacity(2);
13879 for i in 0..4 {
13880 let leaf_x = x_sub + (i % 2) * 8;
13881 let leaf_y = y_sub + (i / 2) * 8;
13882 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
13883 continue;
13884 }
13885 let (mi_row, mi_col) =
13886 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
13887 let stack = find_mv_stack(
13888 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
13889 );
13890 let cstacks = leaf_compound_stacks(
13891 &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows,
13892 header.reference_select, golden, altref,
13893 );
13894 let (leaf, _) = code_square_inter(
13895 &mut luma,
13896 &mut chroma,
13897 (leaf_x, leaf_y),
13898 8,
13899 &search,
13900 &mode_bits_table,
13901 reference,
13902 &stack,
13903 &cstacks,
13904 &grid,
13905 (mi_row, mi_col),
13906 (mi_rows, mi_cols),
13907 &obmc_refs,
13908 fctx,
13909 );
13910 // Same publication point as the 16x16
13911 // straddling leaf above (`record_mi`).
13912 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
13913 eight.push(leaf);
13914 }
13915 leaves.push(BlockCoeffs {
13916 eight: Some(eight),
13917 ..BlockCoeffs::default()
13918 });
13919 }
13920 }
13921 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
13922 }
13923 }
13924 // The 64x64 root against what its four quadrants really cost.
13925 if let Some((cost64, block, after)) = sb64
13926 && (early64
13927 || cost64
13928 < sb_cost
13929 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
13930 {
13931 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13932 if block.inter.is_some_and(|i| i.ref1.is_some()) {
13933 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13934 }
13935 if !whole_inside {
13936 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13937 }
13938 blocks.truncate(mark);
13939 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
13940 // Overwrites every 16x16 mi cell the quadrant searches
13941 // published under this superblock, so the next block's stack
13942 // is built off the block that was really coded.
13943 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
13944 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
13945 for q in 1..4 {
13946 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
13947 blocks.push((r32 * cols + c32, Quadrant::Covered));
13948 }
13949 root_cost += cost64;
13950 } else {
13951 root_cost += sb_cost;
13952 }
13953 }
13954 // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
13955 // `partition_w128` symbol) against what its four superblocks really
13956 // cost, the same weighing the 64 root does one size down. Both sides
13957 // carry their own partition symbol, so the comparison is complete.
13958 // The root candidates, each tagged with the PARTITION symbol its
13959 // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
13960 // shapes (lane-ab128).
13961 let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
13962 if let Some((c, l, b, a)) = root128 {
13963 cands.push((c, l, 0, vec![b], a));
13964 }
13965 if let Some((horz, (c, l, halves, a))) = root_rect {
13966 cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
13967 }
13968 if let Some((symbol, (c, l, pieces, a))) = root_ab {
13969 cands.push((c, l, symbol, pieces.to_vec(), a));
13970 }
13971 // The witness knobs drop every other arm outright: on synthetic
13972 // content the whole block always wins its own comparison.
13973 if forced_rect != 0 {
13974 cands.retain(|c| c.2 == 1 || c.2 == 2);
13975 }
13976 if forced_ab != 0 {
13977 cands.retain(|c| c.2 == usize::from(forced_ab));
13978 }
13979 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
13980 // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
13981 // superblock arm codes the delta_q group too -- the Whole64 writer
13982 // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
13983 // with `!sb128_armed()`) and every smaller shape below it pass
13984 // `is_whole_sb = false` under a 128 grid, so the arm's first
13985 // (root-origin) superblock codes the group even when skipped. Only the skipped 128
13986 // NONE root escapes it, so the split side is charged here at the same
13987 // root lambda the candidates are priced with.
13988 let split_dq =
13989 delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
13990 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
13991 && (cost128
13992 < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
13993 // The witness knobs take the root whatever it costs, so the
13994 // forced block really reaches the writer.
13995 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
13996 || forced_rect != 0
13997 || forced_ab != 0)
13998 {
13999 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
14000 blocks.truncate(mark128);
14001 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
14002 let at = (root_r * 2) * cols + root_c * 2;
14003 match shape {
14004 0 => {
14005 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14006 let block = halves.into_iter().next().expect("the NONE arm's block");
14007 record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
14008 blocks.push((at, Quadrant::Whole128(block)));
14009 }
14010 // lane-ab128: three pieces, published at their own footprints
14011 // in the writer's own order ([`ab128_pieces`]).
14012 symbol @ 4..=7 => {
14013 B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14014 for (((mr, mc), (w, h)), piece) in
14015 ab128_pieces(symbol, (root_r * 16, root_c * 16)).iter().zip(&halves)
14016 {
14017 record_mi_rect(
14018 &mut grid,
14019 *mr,
14020 *mc,
14021 (w / 4, h / 4),
14022 piece.inter,
14023 piece.skip,
14024 );
14025 }
14026 blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
14027 }
14028 symbol => {
14029 let horz = symbol == 1;
14030 if horz {
14031 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14032 } else {
14033 B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14034 }
14035 let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
14036 for (i, half) in halves.iter().enumerate() {
14037 let (mr, mc) = if horz {
14038 (root_r * 16 + i * 16, root_c * 16)
14039 } else {
14040 (root_r * 16, root_c * 16 + i * 16)
14041 };
14042 record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
14043 }
14044 blocks.push((at, Quadrant::Rect128(horz, halves)));
14045 }
14046 }
14047 for q in 1..16 {
14048 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
14049 blocks.push((r32 * cols + c32, Quadrant::Covered));
14050 }
14051 }
14052 }
14053 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
14054 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
14055 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
14056 for (&out, tile) in chroma_out.iter().zip(&chroma) {
14057 copy_rect(
14058 out,
14059 &tile.reconstruction,
14060 frame_width / 2,
14061 x0 / 2,
14062 y0 / 2,
14063 x1.div_ceil(2),
14064 y1.div_ceil(2),
14065 );
14066 }
14067 Ok(blocks)
14068 };
14069 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
14070 .into_iter()
14071 .flatten()
14072 {
14073 blocks[at] = quadrant;
14074 }
14075
14076 // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
14077 // superblock roots the search left whole, so a flat BD result is
14078 // attributable (class `gate-blind-to-feature`). A key frame codes none:
14079 // only the inter writer has a 128x128 block.
14080 if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
14081 let whole = blocks
14082 .iter()
14083 .filter(|q| matches!(q, Quadrant::Whole128(_)))
14084 .count();
14085 let roots = blocks
14086 .iter()
14087 .filter(|q| !matches!(q, Quadrant::Covered))
14088 .count();
14089 // lane-b128r: of those roots, how many code a REAL residual rather
14090 // than the skip-only block lane-b128 shipped -- the fire count this
14091 // arm's own gate row is read against.
14092 let residual = blocks
14093 .iter()
14094 .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
14095 .count();
14096 // lane-b128r: and how many named a second reference (the compound
14097 // arm at the 128 root).
14098 let compound = blocks
14099 .iter()
14100 .filter(|q| {
14101 matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some()))
14102 })
14103 .count();
14104 // lane-b128hv: and how many roots took a rect cut instead, per shape
14105 // -- the HORZ/VERT fire count the gate rows are read against.
14106 let horz = blocks
14107 .iter()
14108 .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
14109 .count();
14110 let vert = blocks
14111 .iter()
14112 .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
14113 .count();
14114 let rect_compound = blocks
14115 .iter()
14116 .filter(|q| {
14117 matches!(q, Quadrant::Rect128(_, hs)
14118 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
14119 })
14120 .count();
14121 // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
14122 // .. _VERT_B order -- the per-shape fire count its gate rows are read
14123 // against.
14124 let ab: [usize; 4] = std::array::from_fn(|i| {
14125 blocks
14126 .iter()
14127 .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
14128 .count()
14129 });
14130 eprintln!(
14131 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
14132 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
14133 compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
14134 {roots} coded blocks ({:.1}% of the frame's area at 128)",
14135 ab[0],
14136 ab[1],
14137 ab[2],
14138 ab[3],
14139 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
14140 / blocks.len().max(1) as f64,
14141 );
14142 }
14143 let modes = blocks
14144 .iter()
14145 .flat_map(Quadrant::blocks)
14146 .map(|b| b.mode)
14147 .collect::<Vec<_>>();
14148 let inter_block_share = blocks
14149 .iter()
14150 .flat_map(Quadrant::blocks)
14151 .filter(|b| b.inter.is_some())
14152 .count() as f64
14153 / modes.len() as f64;
14154 for block in blocks.iter().flat_map(Quadrant::blocks) {
14155 if let Some(info) = block.inter {
14156 let r = (info.ref_frame as usize).min(7);
14157 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14158 }
14159 }
14160 #[cfg(test)]
14161 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
14162 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
14163 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
14164 // next frame's writer starts from them -- exactly what
14165 // `crate::stream::stored_cdfs_for` hands the decoder.
14166 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
14167 let mut cdfs = start_cdfs
14168 .cloned()
14169 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
14170 // lane-txi: set per frame, never inherited from the snapshot the
14171 // previous frame stored -- the content gate can flip the bit between
14172 // frames (class `per-tile-state-not-reset`).
14173 cdfs.reduced_tx_set = header.reduced_tx_set;
14174 let start_cdfs = CdfSnapshot(cdfs);
14175 let reference_select_bit = header.reference_select;
14176 let switchable_motion_mode = header.is_motion_mode_switchable;
14177 let warped_motion = header.allow_warped_motion;
14178 let order_hint_bits = seq.order_hint_bits;
14179 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
14180 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
14181 // What this frame stores is the LARGEST tile's end-of-tile tables --
14182 // its own header's `context_update_tile_id` (spec 7.20), which
14183 // `tile_info_of` set to exactly that tile.
14184 let store_tile = layout.largest_tile();
14185 let end_cdfs = std::cell::RefCell::new(None);
14186 // As in `encode_key_frame_inner`: every tile starts from this frame's
14187 // own tables, so no tile depends on any other.
14188 let code_tiles = |bits: u8,
14189 sb_cols: usize,
14190 cdef_grid: &[u8],
14191 units: &[Option<crate::restoration::WienerInfo>]|
14192 -> Result<Vec<Vec<u8>>> {
14193 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
14194 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
14195 crate::tile::arm_delta_q(
14196 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
14197 sb_cols,
14198 sb_q.clone().unwrap_or_default(),
14199 base_q_idx,
14200 );
14201 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
14202 crate::tile::arm_sb128(sb128_on());
14203 crate::tile::arm_sign_bias(sign_bias);
14204 // Thread-locals: every tile job arms its own worker.
14205 crate::tile::arm_reference_select(reference_select_bit);
14206 crate::tile::arm_motion_mode(switchable_motion_mode);
14207 crate::tile::arm_warped_motion(warped_motion);
14208 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
14209 crate::tile::arm_high_precision_mv(hp_mv);
14210 crate::tile::arm_screen(screen);
14211 crate::tile::arm_frame_mi_dims(frame_mi_dims);
14212 crate::tile::arm_filter_intra(filter_intra_on());
14213 let mut cdfs = start_cdfs.0.clone();
14214 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
14215 // Each tile's own MV grid: a candidate scan never reaches past
14216 // the tile's bounds, so a grid holding only this tile's own
14217 // blocks reads exactly as the decoder's frame-wide one does
14218 // under `MiGrid::set_tile_bounds`.
14219 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
14220 mv_grid.set_sign_bias(sign_bias);
14221 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
14222 mi_cols,
14223 mi_rows,
14224 base_q_idx,
14225 &blocks,
14226 tx_select,
14227 &mut cdfs,
14228 layout.rect(index),
14229 &mut mv_grid,
14230 )?;
14231 Ok((bytes, Some(cdfs)))
14232 })?;
14233 if let Some(cdfs) = stored {
14234 *end_cdfs.borrow_mut() = Some(cdfs);
14235 }
14236 Ok(out)
14237 };
14238 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
14239 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
14240 // this tile against the same single-slot reference this encoder predicted
14241 // from, under each candidate level.
14242 // The reference a DECODER holds is this frame's cropped size, not the
14243 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
14244 // reference whose height is not the header's own `frame_height` (spec
14245 // 7.9's compatible-size rule), and the chained-decode round trips prove
14246 // the two predict identically.
14247 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
14248 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
14249 reference.clone()
14250 } else {
14251 Picture {
14252 width: fw,
14253 height: fh,
14254 y: crop_plane(&reference.y, reference.width, fw, fh),
14255 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
14256 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
14257 }
14258 };
14259 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
14260 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
14261 // blocks may name GOLDEN needs that plane too, cropped the same way.
14262 let trial_golden = golden.map(|g| {
14263 if (g.width, g.height) == (fw, fh) {
14264 g.clone()
14265 } else {
14266 Picture {
14267 width: fw,
14268 height: fh,
14269 y: crop_plane(&g.y, g.width, fw, fh),
14270 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
14271 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
14272 }
14273 }
14274 });
14275 let trial_altref = altref.map(|a| {
14276 if (a.width, a.height) == (fw, fh) {
14277 a.clone()
14278 } else {
14279 Picture {
14280 width: fw,
14281 height: fh,
14282 y: crop_plane(&a.y, a.width, fw, fh),
14283 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
14284 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
14285 }
14286 }
14287 });
14288 let trial_last2 = last2.map(|l| {
14289 if (l.width, l.height) == (fw, fh) {
14290 l.clone()
14291 } else {
14292 Picture {
14293 width: fw,
14294 height: fh,
14295 y: crop_plane(&l.y, l.width, fw, fh),
14296 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
14297 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
14298 }
14299 }
14300 });
14301 let mut refs: [Option<&Picture>; 8] = [None; 8];
14302 refs[1] = Some(&trial_ref);
14303 refs[2] = trial_last2.as_ref();
14304 refs[4] = trial_golden.as_ref();
14305 refs[7] = trial_altref.as_ref();
14306 let refpix = crate::decode::RefPix::ready(refs);
14307 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
14308 // sum the block search believed it was minimising. Against the
14309 // post-filter per-frame PSNR the gate prints, this separates a trial
14310 // whose reconstruction is a lie from a filter stage that undoes the win.
14311 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
14312 let sse: u64 = luma
14313 .reconstruction
14314 .chunks(luma.width)
14315 .take(luma.true_height)
14316 .zip(picture_y8.chunks(luma.width))
14317 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
14318 .map(|(&r, &s)| {
14319 let d = i64::from(r) - i64::from(s);
14320 (d * d) as u64
14321 })
14322 .sum();
14323 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
14324 }
14325 let post = |luma: &Plane<'_>, tag: &str| {
14326 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
14327 return;
14328 }
14329 let sse: u64 = luma
14330 .reconstruction
14331 .chunks(luma.width)
14332 .take(luma.true_height)
14333 .zip(picture_y8.chunks(luma.width))
14334 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
14335 .map(|(&r, &s)| {
14336 let d = i64::from(r) - i64::from(s);
14337 (d * d) as u64
14338 })
14339 .sum();
14340 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
14341 };
14342 pick_and_apply_filters(
14343 &mut header,
14344 &mut luma,
14345 &mut chroma,
14346 [&picture_y8, &picture_u8, &picture_v8],
14347 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
14348 // this frame's own `tx_select`, so the search runs under inter
14349 // `TxMode::Select` too (it used to skip and leave every inter frame
14350 // unfiltered once Select became the default).
14351 true,
14352 &mut tiles,
14353 search.lambda,
14354 fctx,
14355 &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows),
14356 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
14357 // are what the NEXT frame writes from, so the winning re-code
14358 // publishes its own into `end_cdfs` -- the first write's are stale
14359 // the moment a second tile is coded.
14360 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
14361 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
14362 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
14363 crate::decode::decode_inter_frame_tiles_lr(
14364 &payloads,
14365 &header_tile_info,
14366 h.mi_cols,
14367 h.mi_rows,
14368 base_q_idx,
14369 h.frame_width,
14370 h.frame_height,
14371 &refpix,
14372 cdef,
14373 lf,
14374 h.allow_high_precision_mv,
14375 h.force_integer_mv,
14376 Some(fctx.interp_filter.get()),
14377 seq.enable_dual_filter,
14378 h.reference_select,
14379 // lane-txi: this frame's own bit, not the hardcoded `true`
14380 // the wrapper used to pass.
14381 h.reduced_tx_set,
14382 tx_select,
14383 lr,
14384 // The trial decode re-reads the tile the writer just wrote,
14385 // so it starts from the same tables the writer did (this
14386 // frame's `start_cdfs`), not from the defaults.
14387 Some(start_cdfs.0.clone()),
14388 sign_bias,
14389 h.allow_screen_content_tools,
14390 switchable_motion_mode,
14391 h.allow_warped_motion,
14392 seq.enable_filter_intra,
14393 // lane-deltaq: this frame's own delta_q/delta_lf params, so
14394 // the trial decode reads the per-superblock `delta_qindex`
14395 // syntax the writer just wrote.
14396 h.delta.clone(),
14397 fctx,
14398 )
14399 },
14400 )?;
14401 post(&luma, "EC_POSTFILTER");
14402 let mut cdfs = end_cdfs
14403 .into_inner()
14404 .unwrap_or_else(|| start_cdfs.0.clone());
14405 cdfs.reset_counts();
14406 let next_cdfs = CdfSnapshot(cdfs);
14407 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
14408 header.tile_info.tile_size_bytes = tile_size_bytes;
14409 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
14410 let mut stream = temporal_delimiter();
14411 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
14412
14413 let [u, v] = chroma;
14414 Ok(Encoded {
14415 stream,
14416 modes,
14417 inter_block_share,
14418 reconstruction: Picture {
14419 width: luma.width,
14420 height: luma.height,
14421 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14422 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14423 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14424 },
14425 tile,
14426 mi_cols: header.mi_cols,
14427 mi_rows: header.mi_rows,
14428 base_q_idx,
14429 tx_select,
14430 switchable_motion_mode,
14431 screen,
14432 reduced_tx_set: header.reduced_tx_set,
14433 start_cdfs,
14434 next_cdfs,
14435 loop_filter: header.loop_filter,
14436 cdef: header.cdef,
14437 loop_restoration: header.loop_restoration,
14438 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
14439 // intra frames only).
14440 allow_intrabc: false,
14441 delta: header.delta.clone(),
14442 })
14443}
14444
14445/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
14446/// frame's temporal unit followed by one inter frame's temporal unit per
14447/// remaining picture, all sharing the key frame's sequence header -- and
14448/// each frame's own [`Encoded`], in coding order.
14449#[derive(Clone, Debug)]
14450pub struct EncodedSequence {
14451 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
14452 /// sequence header and the key frame) followed by each later frame's
14453 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
14454 /// the sequence header the key frame carried).
14455 pub stream: Vec<u8>,
14456 /// One entry per picture, in DISPLAY order — the order a decoder outputs
14457 /// them and the order `pictures` came in. Without a pyramid that is also
14458 /// the coding order; with one the two differ, and `coding_order` is the
14459 /// map between them.
14460 pub frames: Vec<Encoded>,
14461 /// The index into `frames` of each coded frame, in CODING order — what a
14462 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
14463 /// `0..frames.len()` on the flat path.
14464 pub coding_order: Vec<usize>,
14465}
14466
14467/// Encodes a sequence of pictures as a key frame followed by one inter frame
14468/// per remaining picture, each predicting from the previous frame's own
14469/// decoded reconstruction — never from the source, which is what a decoder
14470/// cannot see. Every picture must be the same even size (any even width and
14471/// height — each is padded to a whole number of 64x64 superblocks
14472/// internally, which is what lets an inter frame's reference always match
14473/// the frame being coded against it), and `pictures` must be non-empty.
14474///
14475/// # Errors
14476/// Returns an error when `pictures` is empty, when any picture besides the
14477/// first is not the same size as the first, or under the same conditions
14478/// [`encode_key_frame`] and the inter frame path do.
14479pub(crate) fn encode_sequence_with_ctx(
14480 pictures: &[Picture],
14481 base_q_idx: u8,
14482 deadzone: f64, fctx: &crate::decode::FrameCtx,
14483) -> Result<EncodedSequence> {
14484 let Some((first, rest)) = pictures.split_first() else {
14485 return Err(Error::unsupported(
14486 "AV1 encode",
14487 "a sequence needs at least one picture",
14488 ));
14489 };
14490 first.check_even()?;
14491 let render = (first.width, first.height);
14492 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
14493 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
14494 // the leaves that predict backward off it, and a `show_existing_frame`
14495 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
14496 // an A/B. Screen content stays flat (the content gate in
14497 // `Av1Encoder::encode_frames`, whose detector this asks first so the
14498 // whole sequence path is decided in one place), and so does a run that
14499 // asks for a quantizer rounding offset the facade does not carry: the
14500 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
14501 // the ablations' -- must keep the flat path rather than be silently
14502 // ignored.
14503 //
14504 // The reordering itself is NOT reimplemented here: it is the facade's
14505 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
14506 // called with this sequence's shape, so the two paths cannot drift.
14507 let pyramid = crate::encoder::Pyramid::from_env()
14508 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
14509 .filter(|_| !picture_is_screen(first));
14510 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
14511 if let Some(pyramid) = pyramid {
14512 for picture in rest {
14513 picture.check_even()?;
14514 if (picture.width, picture.height) != render {
14515 return Err(Error::unsupported(
14516 "AV1 encode",
14517 "every picture in a sequence must be the same size as the first",
14518 ));
14519 }
14520 }
14521 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
14522 pictures,
14523 base_q_idx,
14524 pyramid,
14525 armed_tiles(),
14526 );
14527 }
14528 // The key frame and every inter frame after it are coded at the same
14529 // padded size, so the reference each inter frame predicts from -- the
14530 // previous frame's own uncropped reconstruction, at the size a decoder's
14531 // reference buffer actually holds -- always matches the frame being
14532 // coded against it.
14533 let key = encode_key_frame_inner(
14534 &first.padded_to(SUPERBLOCK),
14535 base_q_idx,
14536 deadzone,
14537 &KEY_FRAME_MODES,
14538 split_blocks(),
14539 render,
14540 unspecified_color_config(), fctx,
14541 )?;
14542 let mut stream = key.stream.clone();
14543 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
14544 // key frame refreshes every slot, each inter frame only slot 0), which is
14545 // what `GOLDEN_FRAME` names.
14546 let golden = key.reconstruction.clone();
14547 // The frame two back, once there is one that is not the key frame
14548 // itself (which `GOLDEN_FRAME` already names).
14549 let mut prev2: Option<Picture> = None;
14550 let mut carried = key.next_cdfs.clone();
14551 let mut reference = key.reconstruction.clone();
14552 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
14553 for (i, picture) in rest.iter().enumerate() {
14554 picture.check_even()?;
14555 // lane-av1tpl2: the lookahead window the per-block lambda weighting
14556 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
14557 // sources at this frame's coded (padded) size. The tail of the
14558 // sequence gets a shorter window, and the last frame none at all.
14559 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
14560 .iter()
14561 .take(tpl_depth() - 1)
14562 .map(|n| n.padded_to(SUPERBLOCK))
14563 .collect();
14564 if (picture.width, picture.height) != render {
14565 return Err(Error::unsupported(
14566 "AV1 encode",
14567 "every picture in a sequence must be the same size as the first",
14568 ));
14569 }
14570 let order_hint = (i + 1) as u32;
14571 let inter = encode_inter_frame(
14572 &picture.padded_to(SUPERBLOCK),
14573 &reference,
14574 base_q_idx,
14575 deadzone,
14576 order_hint,
14577 flat_order_hints(order_hint, 0, prev2.is_some()),
14578 render,
14579 Some(&carried.0),
14580 Some(&golden),
14581 prev2.as_ref(),
14582 None,
14583 fctx,
14584 None,
14585 &lookahead,
14586 )?;
14587 stream.extend_from_slice(&inter.stream);
14588 carried = inter.next_cdfs.clone();
14589 prev2 = Some(std::mem::replace(
14590 &mut reference,
14591 inter.reconstruction.clone(),
14592 ));
14593 frames.push(crop_encoded(&inter, render.0, render.1));
14594 }
14595 Ok(EncodedSequence {
14596 stream,
14597 coding_order: (0..frames.len()).collect(),
14598 frames,
14599 })
14600}
14601
14602#[cfg(test)]
14603mod tests {
14604
14605 /// Every (site, frame type, block side) the census can be called with
14606 /// lands in its own ten-counter bucket, inside the array (class
14607 /// `enumerate-table-domain`: an off-by-one here would silently add two
14608 /// sites' trials together).
14609 #[test]
14610 fn the_split_census_buckets_are_distinct_and_in_bounds() {
14611 let mut seen = std::collections::BTreeSet::new();
14612 for site in 0..2 {
14613 for key in [true, false] {
14614 for side in [8usize, 16, 32, 64] {
14615 let base = super::split_census_base(site, key, side);
14616 assert!(base + 10 <= super::SPLIT_CENSUS.len(), "{site} {key} {side}");
14617 assert!(seen.insert(base), "{site} {key} {side} collides");
14618 }
14619 }
14620 }
14621 assert_eq!(seen.len(), 16);
14622 }
14623
14624 /// An [`crate::mvstack::MvStack`] with every context at zero and no
14625 /// neighbours, for the pricer tests below to fill the one band each of
14626 /// them is about.
14627 /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
14628 /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
14629 /// against the same stack -- an offer the writer clamps prices the
14630 /// residual against a predictor the decoder never derives, which is the
14631 /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
14632 /// side, so the stream stays legal; here the pricer's own offer set is
14633 /// enumerated, class `enumerate-table-domain`).
14634 ///
14635 /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
14636 #[test]
14637 fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
14638 for n in 0..=4usize {
14639 let mut stack = bare_stack();
14640 for i in 0..n {
14641 stack.entries.push(crate::mvstack::StackEntry {
14642 mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
14643 weight: 1,
14644 });
14645 stack.drl_ctx.push(0);
14646 }
14647 stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
14648 stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
14649 stack.pred_mv = stack.nearest_mv;
14650 // Aim the vector at each entry in turn, so every index the offer
14651 // set holds is the one that wins at least once.
14652 for target in 0..n.max(1) {
14653 let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
14654 let (_, idx) = best_new_mv_syntax(&stack, mv)
14655 .expect("a zero residual is always codable");
14656 let idx = usize::from(idx);
14657 assert_eq!(
14658 crate::tile::signalled_drl_idx(n, 0, idx),
14659 idx,
14660 "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
14661 );
14662 }
14663 // The NEARMV arm's own offer set (`search_inter_block`,
14664 // `search_skip_64`): indices 1 and 2, offered only when the stack
14665 // really holds that entry.
14666 for idx in 1..=2usize {
14667 if stack.entries.get(idx).is_some() {
14668 assert_eq!(
14669 crate::tile::signalled_drl_idx(n, 1, idx),
14670 idx,
14671 "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
14672 );
14673 }
14674 }
14675 }
14676 }
14677
14678 fn bare_stack() -> crate::mvstack::MvStack {
14679 crate::mvstack::MvStack {
14680 entries: Default::default(),
14681 nearest_mv: (0, 0),
14682 near_mv: (0, 0),
14683 pred_mv: (0, 0),
14684 new_mv_ctx: 0,
14685 ref_mv_ctx: 0,
14686 zero_mv_ctx: 0,
14687 drl_ctx: Default::default(),
14688 above_refs: (None, None),
14689 left_refs: (None, None),
14690 above_nbr: None,
14691 left_nbr: None,
14692 above_skip: false,
14693 left_skip: false,
14694 }
14695 }
14696
14697 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
14698 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
14699 /// own neighbour-derived context. Red before lane-ctx, where the pricer
14700 /// spent four constants at CDF row 0 that assumed the pair was
14701 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
14702 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
14703 #[test]
14704 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
14705 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
14706 use crate::encode::symbol_bits as b;
14707 use crate::mvstack::{
14708 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
14709 LAST_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
14710 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
14711 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
14712 };
14713 // (pair, unidirectional?, the tree's symbols as (table, p index,
14714 // context selector, value)) -- transcribed from the writer.
14715 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
14716 type Sym = (char, usize, usize, usize);
14717 let cases: [((i8, i8), bool, &[Sym]); 7] = [
14718 ((LAST_FRAME, LAST2_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 0)]),
14719 (
14720 (LAST_FRAME, LAST3_FRAME),
14721 true,
14722 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
14723 ),
14724 (
14725 (LAST_FRAME, GOLDEN_FRAME),
14726 true,
14727 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
14728 ),
14729 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
14730 (
14731 (LAST_FRAME, ALTREF_FRAME),
14732 false,
14733 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
14734 ),
14735 (
14736 (LAST_FRAME, BWDREF_FRAME),
14737 false,
14738 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 0)],
14739 ),
14740 (
14741 (LAST_FRAME, ALTREF2_FRAME),
14742 false,
14743 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 1)],
14744 ),
14745 ];
14746 let nbr = |ref0, ref1: Option<i8>| {
14747 Some(NeighbourRef {
14748 is_inter: true,
14749 ref0,
14750 ref1,
14751 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
14752 })
14753 };
14754 // No neighbours (every context zero), then a mixed pair that puts the
14755 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
14756 for (above_nbr, left_nbr, above_refs, left_refs) in [
14757 (None, None, (None, None), (None, None)),
14758 (
14759 nbr(LAST_FRAME, None),
14760 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
14761 (Some(LAST_FRAME), None),
14762 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
14763 ),
14764 ] {
14765 let stack = crate::mvstack::MvStack {
14766 above_nbr,
14767 left_nbr,
14768 above_refs,
14769 left_refs,
14770 ..bare_stack()
14771 };
14772 let (a, a1) = above_refs;
14773 let (l, l1) = left_refs;
14774 let ctx_of = |sel: usize| match sel {
14775 1 => single_ref_p1_ctx(a, a1, l, l1),
14776 2 => single_ref_p2_ctx(a, a1, l, l1),
14777 3 => single_ref_p3_ctx(a, a1, l, l1),
14778 4 => single_ref_p4_ctx(a, a1, l, l1),
14779 5 => single_ref_p5_ctx(a, a1, l, l1),
14780 6 => single_ref_p6_ctx(a, a1, l, l1),
14781 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
14782 };
14783 for (pair, unidir, symbols) in cases {
14784 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
14785 + b(
14786 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
14787 usize::from(!unidir),
14788 );
14789 for &(table, p, sel, v) in symbols {
14790 let row = ctx_of(sel);
14791 want += match table {
14792 'u' => b(&UNI_COMP_REF[row][p], v),
14793 'c' => b(&COMP_REF[row][p], v),
14794 _ => b(&COMP_BWDREF[row][p], v),
14795 };
14796 }
14797 let got = super::compound_ref_bits(pair, &stack);
14798 assert!(
14799 (got - want).abs() < 1e-9,
14800 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
14801 priced {got} bits, writer codes {want}"
14802 );
14803 }
14804 }
14805 }
14806
14807 /// The `skip` and `is_inter` symbols are priced at the SAME context
14808 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
14809 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
14810 /// on every neighbour configuration whose context is not zero (class
14811 /// pricer-context-zero).
14812 #[test]
14813 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
14814 use crate::cdf::{INTRA_INTER, SKIP};
14815 use crate::encode::symbol_bits as b;
14816 use crate::mvstack::NeighbourRef;
14817 let nbr = |is_inter| NeighbourRef {
14818 is_inter,
14819 ref0: if is_inter { crate::mvstack::LAST_FRAME } else { 0 },
14820 ref1: None,
14821 uni: false,
14822 };
14823 for (above, left, above_skip, left_skip) in [
14824 (None, None, false, false),
14825 (Some(nbr(true)), Some(nbr(true)), true, false),
14826 (Some(nbr(false)), Some(nbr(false)), true, true),
14827 (Some(nbr(false)), None, false, true),
14828 (None, Some(nbr(true)), true, true),
14829 ] {
14830 let stack = crate::mvstack::MvStack {
14831 above_nbr: above,
14832 left_nbr: left,
14833 above_skip,
14834 left_skip,
14835 ..bare_stack()
14836 };
14837 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
14838 let ii_ctx = crate::tile::intra_inter_ctx(
14839 above.is_some(),
14840 left.is_some(),
14841 above.is_some_and(|n| n.is_inter),
14842 left.is_some_and(|n| n.is_inter),
14843 );
14844 for v in [false, true] {
14845 let (got, want) = (
14846 super::skip_bits_at(&stack, v),
14847 b(&SKIP[skip_ctx], usize::from(v)),
14848 );
14849 assert!(
14850 (got - want).abs() < 1e-9,
14851 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
14852 );
14853 let (got, want) = (
14854 super::intra_inter_bits_at(&stack, v),
14855 b(&INTRA_INTER[ii_ctx], usize::from(v)),
14856 );
14857 assert!(
14858 (got - want).abs() < 1e-9,
14859 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
14860 );
14861 }
14862 }
14863 }
14864
14865 /// [`super::single_ref_bits`] pays exactly what tile.rs'
14866 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
14867 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
14868 /// the context that symbol's own `single_ref_p*_ctx` derives from the
14869 /// block's above/left neighbours. Red before lane-pricer, where every
14870 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
14871 #[test]
14872 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
14873 use crate::cdf::SINGLE_REF as SR;
14874 use crate::encode::symbol_bits as b;
14875 use crate::mvstack::{
14876 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
14877 LAST_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
14878 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
14879 };
14880 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
14881 above_refs,
14882 left_refs,
14883 above_nbr,
14884 left_nbr,
14885 ..bare_stack()
14886 };
14887 let nbr = |ref0, ref1| {
14888 Some(crate::mvstack::NeighbourRef { is_inter: true, ref0, ref1, uni: false })
14889 };
14890 // (reference, the symbols `write_single_ref` emits as (p index, value))
14891 let cases: [(i8, &[(usize, usize)]); 7] = [
14892 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
14893 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
14894 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
14895 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
14896 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
14897 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
14898 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
14899 ];
14900 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
14901 // that puts every p* context on a different row -- the second with a
14902 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
14903 // off row 0.
14904 for (above_refs, left_refs, above_nbr, left_nbr) in [
14905 ((None, None), (None, None), None, None),
14906 (
14907 (Some(LAST_FRAME), None),
14908 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
14909 nbr(LAST_FRAME, None),
14910 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
14911 ),
14912 ] {
14913 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
14914 let (a, a1) = above_refs;
14915 let (l, l1) = left_refs;
14916 let ctx_of = |p: usize| match p {
14917 0 => single_ref_p1_ctx(a, a1, l, l1),
14918 1 => single_ref_p2_ctx(a, a1, l, l1),
14919 2 => single_ref_p3_ctx(a, a1, l, l1),
14920 3 => single_ref_p4_ctx(a, a1, l, l1),
14921 4 => single_ref_p5_ctx(a, a1, l, l1),
14922 _ => single_ref_p6_ctx(a, a1, l, l1),
14923 };
14924 for (ref_frame, symbols) in cases {
14925 // Plus the `comp_mode = 0` symbol the writer codes ahead of
14926 // the reference syntax on a `reference_select` frame.
14927 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
14928 if super::reference_select() {
14929 want += b(
14930 &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(
14931 above_nbr, left_nbr,
14932 )],
14933 0,
14934 );
14935 }
14936 let got = super::single_ref_bits(ref_frame, &stack);
14937 assert!(
14938 (got - want).abs() < 1e-9,
14939 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
14940 priced {got} bits, writer codes {want}"
14941 );
14942 }
14943 }
14944 }
14945
14946 /// lane-av1tpl2's propagated map, on the two properties every decision
14947 /// under it rests on: a frame the whole lookahead window repeats exactly
14948 /// (uniform texture) leans on every cell alike, so every factor is 1 and
14949 /// the weighting is a no-op; and where the window really does save bits
14950 /// by predicting -- the textured half of a frame whose other half is
14951 /// flat -- the factor FALLS below 1, i.e. that half is coded more
14952 /// distortion-averse than the half nothing gains from.
14953 /// The distortion metric itself (lane-sse): a block the true frame edge
14954 /// cuts through is scored over its INSIDE part only, so a difference that
14955 /// lives entirely in the padding costs nothing and a block wholly past
14956 /// the edge scores zero. Before this, the search ranked modes,
14957 /// transforms and partition trees on samples the display crop throws
14958 /// away -- which lane-b64b had fixed for the 64x64 root alone.
14959 #[test]
14960 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
14961 // A 40x40 true frame on a 64x64 padded coding surface.
14962 let source = vec![10u8; 64 * 64];
14963 let plane = fresh_plane(&source, 64, 64, 40, 40);
14964 let mut reconstruction = vec![10u8; 64 * 64];
14965 // Off by 190 at (50, 50) -- past the true edge in both axes.
14966 reconstruction[50 * 64 + 50] = 200;
14967 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored");
14968 // Off by 10 at (39, 39) -- the last sample the decoder shows.
14969 reconstruction[39 * 64 + 39] = 20;
14970 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored");
14971 // A 16x16 block whose every sample is padding.
14972 let block = vec![200u8; 16 * 16];
14973 assert_eq!(plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored");
14974 // A 16x16 block the edge cuts: 8 of its columns are inside.
14975 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
14976 }
14977
14978 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
14979 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
14980 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
14981 #[test]
14982 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
14983 let (base, res) = (162u8, 4i32);
14984 let rf = 2.0;
14985 // A superblock the window leans on more than the frame average is
14986 // coded FINER (lower qindex); a slack one coarser; the average one
14987 // exactly at the base.
14988 assert!(super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, "leaned-on SB must go finer");
14989 assert!(super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, "idle SB must go coarser");
14990 assert_eq!(super::deltaq_libaom(base, rf, rf, 1.0, res), base, "the average SB moves 0");
14991 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
14992 let max = ((res * 9 - 1) / res) * res;
14993 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
14994 for k in [0.5f64, 1.0, 1.5] {
14995 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
14996 let d = q - i32::from(base);
14997 assert_eq!(d % res, 0, "r={r} k={k}: offset {d} is not a whole {res}-step");
14998 assert!(d.abs() <= max, "r={r} k={k}: offset {d} past libaom's +-{max}");
14999 }
15000 }
15001 // The clamp is REACHED from both ends, so the bound is a real bound
15002 // and not a formula that never gets there.
15003 assert_eq!(i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), -max);
15004 assert_eq!(i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), max);
15005 // A stronger `k` never moves less than a weaker one.
15006 let d = |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs();
15007 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));
15008 // The frame reference is libaom's log-mean: flat in, the same value out.
15009 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
15010 }
15011
15012 /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
15013 /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
15014 /// shipped default, and the multiplier reaches the strength.
15015 #[test]
15016 fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
15017 let d = crate::speed::DQ_LEVEL_K;
15018 assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
15019 assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
15020 // Short and broken fields fall back per SLOT, not per spec.
15021 assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
15022 assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
15023 assert_eq!(super::DqLevel::TopArf as usize, 0);
15024 assert_eq!(super::DqLevel::MidArf as usize, 1);
15025 assert_eq!(super::DqLevel::Leaf as usize, 2);
15026 }
15027
15028 #[test]
15029 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
15030 // Four 64x64 superblocks across: the shipped map forms its ratio per
15031 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
15032 // only ever produce one ratio -- and one ratio, mean-normalised, is
15033 // the flat map, whatever the content underneath it.
15034 let (w, h) = (256usize, 64usize);
15035 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
15036 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
15037 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
15038 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
15039 for (i, &v) in f.iter().enumerate() {
15040 assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda");
15041 }
15042
15043 // Left half textured, right half constant: the window saves bits
15044 // predicting the left half and nothing at all on the right.
15045 let split: Vec<u8> = (0..w * h)
15046 .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 })
15047 .collect();
15048 let frames: Vec<&[u8]> = vec![&split, &split, &split];
15049 let cells_x = w / 16;
15050 for k in [0.25f64, 0.5, 1.0, 2.0] {
15051 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
15052 for r in 0..h / 16 {
15053 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
15054 assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1");
15055 assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1");
15056 }
15057 }
15058 }
15059
15060 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
15061 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
15062 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
15063 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
15064 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
15065 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
15066 /// only a quarter of the 16x8 table and read the wrong byte for every
15067 /// block row but the first (silently wrong above-right/below-left
15068 /// availability -- wrong pixels, no error).
15069 #[test]
15070 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
15071 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
15072 let (bw_log2, bh_log2) =
15073 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
15074 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
15075 for (name, table) in
15076 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
15077 {
15078 assert_eq!(
15079 table.len() * 8,
15080 rows * cols,
15081 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
15082 );
15083 let mut seen = vec![0u32; table.len() * 8];
15084 for blk_row in 0..rows {
15085 for blk_col in 0..cols {
15086 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
15087 assert!(
15088 idx < seen.len(),
15089 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
15090 );
15091 seen[idx] += 1;
15092 }
15093 }
15094 assert!(
15095 seen.iter().all(|&n| n == 1),
15096 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
15097 (row stride is not {cols})"
15098 );
15099 }
15100 }
15101 }
15102 use super::*;
15103 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
15104 use crate::probe::run_with_stdin;
15105 use std::process::{Command, Stdio};
15106
15107 /// Every rectangular shape this decoder codes, at every position a block
15108 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
15109 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
15110 /// (`reconintra.c`) answer, whose bodies are ported below.
15111 ///
15112 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
15113 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
15114 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
15115 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
15116 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
15117 /// oracle's own arrays, so a re-routed or truncated table fails here even
15118 /// where the two rows happen to agree.
15119 ///
15120 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
15121 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
15122 /// callers handle by predicting each transform unit as its own block.
15123 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
15124 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
15125 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
15126 /// (the horizontal shapes, which those partitions never produce).
15127 #[test]
15128 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
15129 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
15130 // it pins the 64 reach explicitly instead of following the process's
15131 // own superblock knob (`for_encoder`), which made it red under
15132 // `EC_AV1_SB128=1` for no defect of the code under test.
15133 let fctx = &crate::decode::FrameCtx::new();
15134 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
15135 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
15136 (4, 8, 64, 9280, 64, 550),
15137 (8, 4, 64, 3712, 64, 9630),
15138 (8, 16, 16, 2352, 16, 134),
15139 (16, 8, 16, 960, 16, 2400),
15140 (16, 32, 4, 620, 4, 32),
15141 (32, 16, 4, 32, 4, 184),
15142 (32, 64, 1, 127, 1, 0),
15143 (64, 32, 1, 19, 1, 34),
15144 (4, 16, 32, 5472, 32, 14),
15145 (16, 4, 32, 960, 32, 6464),
15146 (8, 32, 8, 1400, 8, 2),
15147 (32, 8, 8, 32, 8, 1136),
15148 (16, 64, 2, 382, 2, 0),
15149 (64, 16, 2, 4, 2, 84),
15150 ];
15151 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
15152 /// a block whose transform covers it whole (`row_off == col_off == 0`,
15153 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
15154 /// superblock (`sb_mi_size == 16`).
15155 fn libaom_reach(
15156 bw: usize,
15157 bh: usize,
15158 x: usize,
15159 y: usize,
15160 width: usize,
15161 height: usize, _fctx: &crate::decode::FrameCtx,
15162 ) -> (bool, bool) {
15163 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
15164 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
15165 let sb_mi_size = 16usize;
15166 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
15167 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
15168 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
15169 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
15170 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
15171 // has_top_right: top_available && right_available, then row_off == 0.
15172 let top_right = if y == 0 || x + bw >= width {
15173 false
15174 } else if blk_row_in_sb == 0 {
15175 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
15176 // `bw_unit < bw_unit`, false for a whole-block transform.)
15177 true
15178 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
15179 false
15180 } else {
15181 bit(tr_table)
15182 };
15183 // has_bottom_left: bottom_available && left_available, col_off == 0.
15184 let bottom_left = if x == 0 || y + bh >= height {
15185 false
15186 } else if blk_col_in_sb == 0 {
15187 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
15188 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
15189 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
15190 false
15191 } else {
15192 bit(bl_table)
15193 };
15194 (top_right, bottom_left)
15195 }
15196 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
15197 let (tr, bl) = rect_reach_tables(bw, bh);
15198 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
15199 assert_eq!(
15200 (tr.len(), sum(tr), bl.len(), sum(bl)),
15201 (tr_len, tr_sum, bl_len, bl_sum),
15202 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
15203 );
15204 // Two superblocks across and down, so the superblock-relative
15205 // position (and not the frame position) is what decides.
15206 for sb_y in [0usize, 64] {
15207 for sb_x in [0usize, 64] {
15208 for y in (sb_y..sb_y + 64).step_by(bh) {
15209 for x in (sb_x..sb_x + 64).step_by(bw) {
15210 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
15211 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
15212 assert_eq!(
15213 (got.above_right, got.below_left),
15214 want,
15215 "{bw}x{bh} at ({x}, {y})"
15216 );
15217 }
15218 }
15219 }
15220 }
15221 }
15222 }
15223
15224 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
15225 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
15226 /// aomenc gate decodes its stream through ffmpeg and is meaningless
15227 /// without it -- turns it into a hard failure. Without this the require
15228 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
15229 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
15230 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
15231 fn have_ffmpeg() -> bool {
15232 let present = Command::new("ffmpeg")
15233 .arg("-version")
15234 .stdout(Stdio::null())
15235 .stderr(Stdio::null())
15236 .status()
15237 .is_ok_and(|s| s.success());
15238 assert!(
15239 present
15240 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
15241 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
15242 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
15243 );
15244 present
15245 }
15246
15247 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
15248 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
15249 fn have_encoder(encoder: &str) -> bool {
15250 Command::new("ffmpeg")
15251 .args(["-hide_banner", "-encoders"])
15252 .stderr(Stdio::null())
15253 .output()
15254 .is_ok_and(|o| {
15255 String::from_utf8_lossy(&o.stdout)
15256 .lines()
15257 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
15258 })
15259 }
15260
15261 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
15262 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
15263 let out = run_with_stdin(
15264 Command::new("ffmpeg").args([
15265 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
15266 ]),
15267 stream,
15268 );
15269 assert!(
15270 out.status.success(),
15271 "ffmpeg refused the stream: {}",
15272 String::from_utf8_lossy(&out.stderr)
15273 );
15274 let (luma, chroma) = (width * height, width * height / 4);
15275 assert_eq!(
15276 out.stdout.len(),
15277 luma + 2 * chroma,
15278 "expected one 4:2:0 frame"
15279 );
15280 Picture {
15281 width,
15282 height,
15283 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
15284 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
15285 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
15286 }
15287 }
15288
15289 /// A picture with something of everything in it: a gradient, an edge, a
15290 /// ripple and a block of flat colour, none of them aligned to the block
15291 /// grid.
15292 /// The in-loop filters actually FIRE and the stream still decodes to
15293 /// exactly what the encoder kept as its reconstruction
15294 /// (gate-blind-to-feature: a filter search that always answered "off"
15295 /// would leave every other test just as green, and the BD gate that
15296 /// would notice is `#[ignore]`d).
15297 ///
15298 /// Run:
15299 /// cargo test -p ec-av1 --release --lib -- \
15300 /// encode::tests::the_filter_search_picks_real_filters
15301 #[test]
15302 fn the_filter_search_picks_real_filters() {
15303 let _knobs = crate::speed::knob_read();
15304 let fctx = &crate::decode::FrameCtx::for_encoder();
15305 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
15306 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
15307 let fired = encoded
15308 .frames
15309 .iter()
15310 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
15311 .count();
15312 assert!(
15313 fired > 0,
15314 "no frame of this sequence chose any in-loop filtering: {:?}",
15315 encoded
15316 .frames
15317 .iter()
15318 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
15319 .collect::<Vec<_>>()
15320 );
15321 // The reconstruction the encoder predicts from is the FILTERED one,
15322 // and it is what a decoder of the stream produces -- byte for byte,
15323 // frame for frame.
15324 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
15325 assert_eq!(decoded.len(), encoded.frames.len());
15326 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
15327 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
15328 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
15329 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
15330 }
15331 }
15332
15333 fn test_card(width: usize, height: usize) -> Picture {
15334 let mut picture = Picture::grey(width, height);
15335 for y in 0..height {
15336 for x in 0..width {
15337 let gradient = x as f64 * 200.0 / width as f64;
15338 let ripple = 30.0
15339 * (x as f64 * std::f64::consts::PI / 23.0).sin()
15340 * (y as f64 * std::f64::consts::PI / 37.0).cos();
15341 let edge = if x > width * 3 / 7 && y > height / 3 {
15342 40.0
15343 } else {
15344 0.0
15345 };
15346 picture.y[y * width + x] =
15347 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
15348 }
15349 }
15350 for y in 0..height / 2 {
15351 for x in 0..width / 2 {
15352 let i = y * width / 2 + x;
15353 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
15354 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
15355 }
15356 }
15357 picture
15358 }
15359
15360 fn psnr(a: &[u16], b: &[u16]) -> f64 {
15361 let squared: f64 = a
15362 .iter()
15363 .zip(b)
15364 .map(|(&x, &y)| {
15365 let d = f64::from(x) - f64::from(y);
15366 d * d
15367 })
15368 .sum();
15369 if squared == 0.0 {
15370 return f64::INFINITY;
15371 }
15372 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
15373 }
15374
15375 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
15376 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
15377 /// frame's new root fires on most superblocks -- and what BOTH decoders
15378 /// produce is the encoder's own reconstruction, sample for sample.
15379 ///
15380 /// The fire count is the `gate-blind-to-feature` guard: without it every
15381 /// assert below passes on a stream that codes no whole superblock at all.
15382 #[test]
15383 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
15384 let _knobs = crate::speed::knob_read();
15385 let fctx = &crate::decode::FrameCtx::for_encoder();
15386 // 4 x 3 superblocks, all of them wholly inside the frame.
15387 let (width, height) = (256usize, 192usize);
15388 let mut picture = Picture::grey(width, height);
15389 for y in 0..height {
15390 for x in 0..width {
15391 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
15392 }
15393 }
15394 for y in 0..height / 2 {
15395 for x in 0..width / 2 {
15396 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
15397 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
15398 }
15399 }
15400 let _ = take_i64_root_hits();
15401 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
15402 let [roots, _offered, _edge] = take_i64_root_hits();
15403 // The counters are process-global, so another test encoding in
15404 // parallel can only ADD to them -- the per-FRAME fact is the mode
15405 // list, which carries one entry per coded block and so exactly 12
15406 // when every superblock was coded as one 64x64 intra block.
15407 assert_eq!(
15408 encoded.modes.len(),
15409 12,
15410 "not every superblock was coded as one 64x64 intra block"
15411 );
15412 assert!(
15413 roots >= 8,
15414 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
15415 );
15416 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
15417
15418 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
15419 assert_eq!(ours.len(), 1, "our decoder's frames");
15420 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
15421 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
15422 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
15423
15424 if !have_ffmpeg() {
15425 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15426 return;
15427 }
15428 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15429 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15430 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15431 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15432 }
15433
15434 /// The claim the whole encoder rests on: what a decoder produces is what
15435 /// the encoder said it would, sample for sample, on every plane.
15436 ///
15437 /// Prediction reads the reconstruction, so a single sample of drift
15438 /// anywhere would spread into every block below and to the right of it —
15439 /// which is why this is an equality and not a tolerance.
15440 #[test]
15441 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
15442 let _knobs = crate::speed::knob_read();
15443 let fctx = &crate::decode::FrameCtx::for_encoder();
15444 if !have_ffmpeg() {
15445 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
15446 return;
15447 }
15448 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48), (248, 152)] {
15449 let picture = test_card(width, height);
15450 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15451 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15452 assert_eq!(
15453 decoded.y, encoded.reconstruction.y,
15454 "{width}x{height}: luma"
15455 );
15456 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
15457 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
15458 }
15459 // One q index from each of the four coefficient-CDF contexts
15460 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
15461 let (width, height) = (64usize, 64usize);
15462 let picture = test_card(width, height);
15463 let _ = take_tx_depth_hits();
15464 for &q in &[15u8, 45, 100, 200] {
15465 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15466 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15467 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
15468 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
15469 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
15470 }
15471 // lane-av1tx: the exactness above is only a claim about SPLIT
15472 // transforms if some block actually split one (`gate-blind-to-feature`
15473 // -- with `tx_depth` stuck at 0 every assert here passes on the
15474 // pre-lane stream). The test card's edges split at these four
15475 // quantizers; the counter is per-process (another test encoding in
15476 // parallel can only ADD to it, so this can be masked, never falsely
15477 // failed), so it is read once for the whole q ladder.
15478 let depths = take_tx_depth_hits();
15479 assert!(
15480 depths[1] + depths[2] > 0,
15481 "no block split its transform: depths {depths:?}"
15482 );
15483 }
15484
15485 /// A synthetic screen-content picture -- a few flat colours in a grid of
15486 /// boxes with hard edges and text-like bars, the shape a desktop capture
15487 /// has -- so the palette path is exercised on content it is for.
15488 #[cfg(test)]
15489 fn screen_card(width: usize, height: usize) -> Picture {
15490 const INK: [u16; 4] = [16, 90, 180, 235];
15491 let mut picture = Picture::grey(width, height);
15492 for y in 0..height {
15493 for x in 0..width {
15494 let cell = (x / 24 + y / 24) % 2;
15495 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
15496 picture.y[y * width + x] = INK[cell * 2 + bar];
15497 }
15498 }
15499 // Four chroma colours, not two: a two-colour chroma block only ever
15500 // codes a `PaletteSizeUV` of 2, which leaves
15501 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
15502 // deltas and the neighbour cache flags, exercised only when
15503 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
15504 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
15505 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
15506 for y in 0..height / 2 {
15507 for x in 0..width / 2 {
15508 let cell = (x / 12 + 2 * (y / 12)) % 4;
15509 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
15510 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
15511 }
15512 }
15513 picture
15514 }
15515
15516 /// The lane's own end-to-end check: on screen content the detector fires,
15517 /// blocks really take a palette (fire count, class
15518 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
15519 /// symbol this lane writes -- reconstructs exactly what the encoder did.
15520 /// The film-shaped `test_card` must NOT trip the detector, which is what
15521 /// keeps every non-screen stream byte-identical.
15522 #[test]
15523 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
15524 let _knobs = crate::speed::knob_read();
15525 let fctx = &crate::decode::FrameCtx::for_encoder();
15526 let (width, height) = (192usize, 96usize);
15527 let _ = crate::tile::take_palette_hits();
15528 let picture = screen_card(width, height);
15529 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15530 assert!(
15531 encoded.screen,
15532 "the detector did not fire on screen content -- no palette syntax was coded at all"
15533 );
15534 let hits = crate::tile::take_palette_hits();
15535 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
15536 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
15537 // The chroma half is a claim about the plane-1 syntax only if some
15538 // block really took a chroma palette (`gate-blind-to-feature`): every
15539 // exactness assert below passes on a stream that codes
15540 // `palette_uv_mode == 0` everywhere.
15541 let uv_hits = crate::tile::take_palette_uv_hits();
15542 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
15543 let uv_cached = crate::tile::take_palette_uv_cache_hits();
15544 eprintln!(
15545 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
15546 uv_hits[0],
15547 &uv_hits[2..]
15548 );
15549 assert!(
15550 uv_cached > 0,
15551 "no chroma base colour came out of the neighbour cache -- \
15552 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
15553 );
15554 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
15555 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
15556 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
15557 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
15558 if !have_ffmpeg() {
15559 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15560 return;
15561 }
15562 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15563 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15564 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15565 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15566 // A whole GOP: the inter frames' own intra blocks carry the palette
15567 // syntax too (the three intra arms of the inter writers), which only
15568 // ffmpeg reading the frames back can prove.
15569 let moved: Vec<Picture> = (0..4)
15570 .map(|f| {
15571 let base = screen_card(width, height);
15572 let mut out = Picture::grey(width, height);
15573 for y in 0..height {
15574 for x in 0..width {
15575 let sx = (x + f * 7) % width;
15576 out.y[y * width + x] = base.y[y * width + sx];
15577 }
15578 }
15579 for y in 0..height / 2 {
15580 for x in 0..width / 2 {
15581 let sx = (x + f * 3) % (width / 2);
15582 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
15583 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
15584 }
15585 }
15586 out
15587 })
15588 .collect();
15589 let _ = crate::tile::take_palette_hits();
15590 let _ = crate::tile::take_palette_uv_hits();
15591 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
15592 let gop_hits = crate::tile::take_palette_hits();
15593 let gop_uv_hits = crate::tile::take_palette_uv_hits();
15594 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
15595 eprintln!(
15596 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
15597 {} chroma palette blocks",
15598 inter_screen, gop_hits[0], gop_uv_hits[0]
15599 );
15600 assert!(
15601 gop_uv_hits[0] > 0,
15602 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
15603 );
15604 assert!(
15605 inter_screen > 0,
15606 "no inter frame set allow_screen_content_tools"
15607 );
15608 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
15609 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
15610 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
15611 }
15612 if have_ffmpeg() {
15613 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
15614 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
15615 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
15616 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
15617 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
15618 }
15619 }
15620
15621 // The other half of the keep rule: film-shaped content leaves the
15622 // detector (and so the whole sequence header) alone.
15623 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
15624 assert!(!film.screen, "the detector fired on the film-shaped test card");
15625 }
15626
15627 /// The lane's keep-rule measurement: the gate's own screen capture, one
15628 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
15629 /// Setting the bit forces deblocking, CDEF and loop restoration off for
15630 /// that frame, so the table is exactly the filter loss against the bytes
15631 /// the copied blocks save.
15632 #[test]
15633 #[ignore = "needs the real-library manifest and ffmpeg"]
15634 fn probe_intrabc_key_frame() {
15635 let _knobs = crate::speed::knob_write();
15636 let fctx = &crate::decode::FrameCtx::for_encoder();
15637 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
15638 .join("../../fixtures");
15639 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
15640 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
15641 return;
15642 };
15643 let Some(clip) = manifest
15644 .lines()
15645 .skip(1)
15646 .filter_map(|l| l.split('\t').next())
15647 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
15648 else {
15649 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
15650 return;
15651 };
15652 let (width, height) = (1280usize, 768usize);
15653 let picture = clip_frame(clip, "0", width, height);
15654 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
15655 for q in [5u8, 20, 35, 45] {
15656 for on in [false, true] {
15657 force_intrabc(Some(on));
15658 let _ = crate::tile::take_intrabc_hits();
15659 let _ = take_intrabc_search();
15660 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15661 let hits = crate::tile::take_intrabc_hits();
15662 let search = take_intrabc_search();
15663 eprintln!(
15664 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
15665 if encoded.allow_intrabc { "on" } else { "off" },
15666 encoded.stream.len(),
15667 psnr_all(&encoded.reconstruction, &picture),
15668 hits[0],
15669 &hits[1..],
15670 search[0], search[1], search[2],
15671 );
15672 }
15673 }
15674 force_intrabc(None);
15675 }
15676
15677 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
15678 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
15679 /// take a block vector (fire count + DV histogram, class
15680 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
15681 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
15682 /// exactly what the encoder did.
15683 #[test]
15684 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
15685 let _knobs = crate::speed::knob_write();
15686 let fctx = &crate::decode::FrameCtx::for_encoder();
15687 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
15688 // superblocks of 64) and tall enough for a source superblock row
15689 // above the blocks that copy from it.
15690 let (width, height) = (512usize, 256usize);
15691 let picture = screen_card(width, height);
15692 let _ = crate::tile::take_intrabc_hits();
15693 // The default is OFF (it measured worse on the real screen capture --
15694 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
15695 // the arm on for its own encode and puts it back straight after.
15696 force_intrabc(Some(true));
15697 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15698 force_intrabc(None);
15699 assert!(
15700 encoded.allow_intrabc,
15701 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
15702 intrabc_source_share() * 100.0
15703 );
15704 let hits = crate::tile::take_intrabc_hits();
15705 eprintln!(
15706 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
15707 hits[0],
15708 &hits[1..],
15709 intrabc_source_share() * 100.0
15710 );
15711 let search = take_intrabc_search();
15712 eprintln!(
15713 "intrabc searches {} found-valid {} won-RD {}",
15714 search[0], search[1], search[2]
15715 );
15716 assert!(
15717 hits[0] > 0,
15718 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
15719 );
15720 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
15721 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
15722 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
15723 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
15724 if !have_ffmpeg() {
15725 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15726 return;
15727 }
15728 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15729 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15730 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15731 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15732 }
15733
15734 /// The minimal repro that isolated the inter-residual desync: a key frame
15735 /// followed by one inter frame whose single superblock carries one
15736 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
15737 /// coefficient, its three sibling blocks all `skip: true`. Before the
15738 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
15739 /// found when processing input") even though every symbol either block
15740 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
15741 /// same coefficient syntax decodes clean on every intra key-frame gate).
15742 #[test]
15743 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
15744 let _knobs = crate::speed::knob_write();
15745 let fctx = &crate::decode::FrameCtx::for_encoder();
15746 if !have_ffmpeg() {
15747 eprintln!(
15748 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
15749 );
15750 return;
15751 }
15752 let (width, height) = (64usize, 64usize);
15753 let picture = Picture::grey(width, height);
15754 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15755
15756 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
15757 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
15758
15759 let residual_block = BlockCoeffs {
15760 luma_tx_types: Vec::new(),
15761 angle_delta_y: 0,
15762 cfl_alphas: None,
15763 filter_intra: None,
15764 luma: vec![Coeff {
15765 row: 0,
15766 col: 0,
15767 level: 4,
15768 }],
15769 u: Vec::new(),
15770 v: Vec::new(),
15771 mode: 0,
15772 uv_mode: 0,
15773 skip: false,
15774 eight: None,
15775 dv: None,
15776 palette: None,
15777 palette_uv: None,
15778 tx_depth: 0,
15779 inter: Some(InterInfo {
15780 ref1: None,
15781 mv1: (0, 0),
15782 ref_frame: crate::mvstack::LAST_FRAME,
15783 mode: InterMode::NearestMv,
15784 mv: (0, 0),
15785 ref_mv_idx: 0,
15786 }),
15787 motion_mode: 0,
15788 };
15789 let skipped_block = BlockCoeffs {
15790 skip: true,
15791 inter: Some(InterInfo {
15792 ref1: None,
15793 mv1: (0, 0),
15794 ref_frame: crate::mvstack::LAST_FRAME,
15795 mode: InterMode::NearestMv,
15796 mv: (0, 0),
15797 ref_mv_idx: 0,
15798 }),
15799 ..BlockCoeffs::default()
15800 };
15801 let blocks = vec![
15802 Quadrant::Whole(residual_block),
15803 Quadrant::Whole(skipped_block.clone()),
15804 Quadrant::Whole(skipped_block.clone()),
15805 Quadrant::Whole(skipped_block),
15806 ];
15807 // lane-av1obmc: the header this tile is decoded under carries
15808 // `is_motion_mode_switchable`, so the writer must be armed with it
15809 // too or the decoder reads a `motion_mode` symbol nobody wrote.
15810 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
15811 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
15812 let tile =
15813 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
15814 .unwrap();
15815
15816 // `key.stream` is already a temporal delimiter, the sequence header
15817 // and the key frame's own OBU (`encode_key_frame` built it from the
15818 // same `key_frame_headers(width, height, 100)` this test calls), so
15819 // the inter frame's OBU is appended straight onto it rather than
15820 // re-deriving the key frame's tile bytes.
15821 let mut stream = key.stream.clone();
15822 stream.extend_from_slice(&temporal_delimiter());
15823 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
15824
15825 ffmpeg_decode_sequence(&stream, width, height, 2);
15826 }
15827
15828 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
15829 /// frame size an AV1 decoder allocates, not necessarily the render size
15830 /// (see [`a_frame_round_trips_at_its_own_size`]).
15831 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
15832 // Distinct per call, not per process: the test binary runs callers on
15833 // parallel threads, and a shared name lets one test's cleanup delete
15834 // the stream another test's ffprobe is still reading.
15835 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
15836 let path = std::env::temp_dir().join(format!(
15837 "ec-av1-probe-{}-{}.obu",
15838 std::process::id(),
15839 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
15840 ));
15841 let _ = std::fs::remove_file(&path);
15842 std::fs::write(&path, stream).expect("writing the probe stream");
15843 let out = Command::new("ffprobe")
15844 .args([
15845 "-v",
15846 "error",
15847 "-f",
15848 "obu",
15849 "-select_streams",
15850 "v:0",
15851 "-show_entries",
15852 "stream=width,height",
15853 "-of",
15854 "csv=p=0",
15855 ])
15856 .arg(&path)
15857 .output()
15858 .expect("ffprobe failed to run");
15859 let _ = std::fs::remove_file(&path);
15860 assert!(
15861 out.status.success(),
15862 "ffprobe refused the stream: {}",
15863 String::from_utf8_lossy(&out.stderr)
15864 );
15865 let text = String::from_utf8_lossy(&out.stdout);
15866 let mut fields = text.trim().split(',');
15867 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
15868 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
15869 (width, height)
15870 }
15871
15872 /// lane-av1cap: the final filter replay against the capture decode it
15873 /// replaced, at the block-padded and straddling sizes the whole-frame
15874 /// tests cover -- `set_verify_final_replay` makes
15875 /// [`pick_and_apply_filters`] run both on every frame and assert, per
15876 /// frame, that the spliced picture and the two filter stages the
15877 /// restoration search reads are bit-identical over the frame's own crop.
15878 #[test]
15879 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
15880 let _knobs = crate::speed::knob_write();
15881 let fctx = &crate::decode::FrameCtx::for_encoder();
15882 crate::decode::set_verify_final_replay(true);
15883 for &(width, height) in
15884 &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)]
15885 {
15886 eprintln!("--- {width}x{height}");
15887 let picture = test_card(width, height);
15888 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15889 }
15890 crate::decode::set_verify_final_replay(false);
15891 }
15892
15893 /// A key frame at an arbitrary even size round-trips through ffmpeg over
15894 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
15895 /// picture's own size, and what ffmpeg decodes over that same top-left
15896 /// region equals it sample for sample.
15897 ///
15898 /// This does not check that `ffprobe` reports the picture's own size,
15899 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
15900 /// (block-padded) frame size, the same one libaom itself would code for
15901 /// a non-block-aligned picture. `render_width`/`render_height` (which
15902 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
15903 /// decoder is required to crop pixels by, and ffmpeg's does not --
15904 /// checked empirically against ffprobe here and against a real libaom
15905 /// encode separately. So the coded size, not the render size, is what
15906 /// `ffprobe` is asserted to report below.
15907 #[test]
15908 fn a_frame_round_trips_at_its_own_size() {
15909 let _knobs = crate::speed::knob_read();
15910 let fctx = &crate::decode::FrameCtx::for_encoder();
15911 if !have_ffmpeg() {
15912 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
15913 return;
15914 }
15915 // 854x480 is covered separately by
15916 // `an_854x480_picture_round_trips_through_its_padding`, which its own
15917 // doc comment explains was worth keeping as its own test.
15918 for &(width, height) in &[
15919 (1920usize, 1080usize),
15920 (640, 352),
15921 (1280, 720),
15922 (64, 56),
15923 (854, 480),
15924 (216, 96),
15925 (192, 120),
15926 ] {
15927 let picture = test_card(width, height);
15928 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15929 assert_eq!(
15930 (encoded.reconstruction.width, encoded.reconstruction.height),
15931 (width, height),
15932 "{width}x{height}: reconstruction is cropped to the picture's own size"
15933 );
15934 assert_eq!(
15935 ffprobe_size(&encoded.stream),
15936 (width as u32, height as u32),
15937 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
15938 );
15939 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15940 assert_eq!(
15941 decoded.y, encoded.reconstruction.y,
15942 "{width}x{height}: luma"
15943 );
15944 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
15945 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
15946 }
15947 }
15948
15949 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
15950 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
15951 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
15952 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
15953 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
15954 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
15955 /// col`) -- different bits of an 8-byte table, one true, one false. The
15956 /// stride libaom indexes by is fixed at its compile-time maximum
15957 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
15958 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
15959 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
15960 /// row/col position within the (correctly 64-relative) superblock stayed
15961 /// right, only the table's own row stride was wrong. Fixed in
15962 /// `Reach::table_stride`; not an arithmetic-coder desync (an
15963 /// EC_RNG-per-symbol trace against the same debug decoder found the
15964 /// bitstream byte-for-byte identical to libaom's across all 51188
15965 /// symbols of this frame before this bug was found).
15966 ///
15967 /// Since the frame header started writing the true (unpadded) display
15968 /// size into `frame_width`/`frame_height` rather than the padded coded
15969 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
15970 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
15971 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
15972 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
15973 /// the header's own size before output).
15974 #[test]
15975 fn an_854x480_picture_round_trips_through_its_padding() {
15976 let _knobs = crate::speed::knob_read();
15977 let fctx = &crate::decode::FrameCtx::for_encoder();
15978 if !have_ffmpeg() {
15979 return;
15980 }
15981 let (width, height) = (854usize, 480usize);
15982 let picture = test_card(width, height);
15983 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15984 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15985 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
15986 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
15987 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
15988 }
15989
15990 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
15991 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
15992 /// superblock, both partition tables:
15993 ///
15994 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
15995 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
15996 /// wiring the TU sites onto it changes no existing stream;
15997 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
15998 /// NULL in libaom because that lookup never happens, and reading a
15999 /// 4x4 row out of the three-row vert tables is what crashed a real
16000 /// `--enable-tx-size-search=1` stream (r2);
16001 /// 3. and it must be the BLOCK's vert answer where the two tables
16002 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
16003 /// row 1, column 0 reads its above-right samples from the 8x8 to its
16004 /// upper right, which a vertical AB partition codes AFTER it
16005 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
16006 #[test]
16007 fn of_tu_follows_the_block_row_including_under_vert_ab() {
16008 let fctx = &crate::decode::FrameCtx::for_encoder();
16009 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
16010 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
16011 // above-right answer is the BLOCK's, which is the whole reason a unit
16012 // asks the block instead of looking itself up (the
16013 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
16014 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
16015 assert_eq!(
16016 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
16017 plain.above_right,
16018 "ordinary table: the top-right TX4 unit takes the block's row"
16019 );
16020 let guard = Reach::vert_ab_partition();
16021 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
16022 assert_eq!(
16023 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
16024 vert.above_right,
16025 "vert AB: the unit follows the vert row the block just picked"
16026 );
16027 assert_ne!(
16028 plain.above_right, vert.above_right,
16029 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
16030 );
16031 drop(guard);
16032 }
16033
16034 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
16035 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
16036 /// reconintra.c`), for every 16x16 and 32x32 block position across three
16037 /// superblocks square -- interior and every superblock edge (top row,
16038 /// left column, right column, bottom row) both sizes reach. Written to
16039 /// catch the class the `table_stride` bug was: an index stride silently
16040 /// wrong for one block size while looking plausible for the other.
16041 #[test]
16042 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
16043 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
16044 // it pins the 64 reach explicitly instead of following the process's
16045 // own superblock knob (`for_encoder`), which made it red under
16046 // `EC_AV1_SB128=1` for no defect of the code under test.
16047 let fctx = &crate::decode::FrameCtx::new();
16048 // Transcribed from has_top_right/has_bottom_left's row_off==0,
16049 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
16050 // 128px reference grid) pinned as libaom pins it, independent of the
16051 // 64px superblock this crate actually codes.
16052 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
16053 if y == 0 || x + side >= width {
16054 return false;
16055 }
16056 let (row, col, per_side) = (
16057 (y % SUPERBLOCK) / side,
16058 (x % SUPERBLOCK) / side,
16059 SUPERBLOCK / side,
16060 );
16061 if row == 0 {
16062 return true;
16063 }
16064 if col + 1 == per_side {
16065 return false;
16066 }
16067 let stride = 128 / side;
16068 let index = row * stride + col;
16069 let table = if side == BLOCK {
16070 [95u8, 87].to_vec()
16071 } else {
16072 vec![255, 85, 119, 85, 127, 85, 119, 85]
16073 };
16074 (table[index / 8] >> (index % 8)) & 1 != 0
16075 }
16076
16077 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
16078 if x == 0 || y + side >= height {
16079 return false;
16080 }
16081 let (row, col, per_side) = (
16082 (y % SUPERBLOCK) / side,
16083 (x % SUPERBLOCK) / side,
16084 SUPERBLOCK / side,
16085 );
16086 if col == 0 {
16087 return row * side + side < SUPERBLOCK;
16088 }
16089 if row + 1 == per_side {
16090 return false;
16091 }
16092 let stride = 128 / side;
16093 let index = row * stride + col;
16094 let table = if side == BLOCK {
16095 [4u8, 4].to_vec()
16096 } else {
16097 vec![84, 16, 84, 0, 84, 16, 84, 0]
16098 };
16099 (table[index / 8] >> (index % 8)) & 1 != 0
16100 }
16101
16102 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
16103 for side in [16usize, BLOCK] {
16104 for y in (0..height).step_by(side) {
16105 for x in (0..width).step_by(side) {
16106 let reach = Reach::of(side, x, y, width, height, fctx);
16107 assert_eq!(
16108 reach.above_right,
16109 libaom_top_right(side, x, y, width, height),
16110 "side={side} x={x} y={y}: above_right"
16111 );
16112 assert_eq!(
16113 reach.below_left,
16114 libaom_bottom_left(side, x, y, height, fctx),
16115 "side={side} x={x} y={y}: below_left"
16116 );
16117 }
16118 }
16119 }
16120 }
16121
16122 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
16123 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
16124 /// column inside the superblock) may read the below-left samples the
16125 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
16126 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
16127 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
16128 /// stream that partitions that small first hits the still-refused
16129 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
16130 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
16131 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
16132 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
16133 /// pixels -- lane-palette2 r12: the square multi-TU path used the
16134 /// standalone-block tables instead of this rule and granted a 16x16
16135 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
16136 #[test]
16137 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
16138 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
16139 // *_count_unit = tx size / 4.
16140 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
16141 let (plane_bw_unit, count) = (bw / 4, tx / 4);
16142 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
16143 let _ = bh;
16144 if row_off_u > 0 {
16145 col_off_u + count < plane_bw_unit
16146 } else if col_off_u + count < plane_bw_unit {
16147 true
16148 } else {
16149 blk
16150 }
16151 }
16152 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
16153 let (plane_bh_unit, count) = (bh / 4, tx / 4);
16154 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
16155 let _ = bw;
16156 if col_off_u > 0 {
16157 false
16158 } else if row_off_u + count < plane_bh_unit {
16159 true
16160 } else {
16161 blk
16162 }
16163 }
16164 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
16165 for &tx in &[4usize, 8, 16, 32] {
16166 if tx > bw.min(bh) {
16167 continue;
16168 }
16169 for row_off in (0..bh).step_by(tx) {
16170 for col_off in (0..bw).step_by(tx) {
16171 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
16172 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
16173 assert_eq!(
16174 got.above_right,
16175 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
16176 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
16177 );
16178 assert_eq!(
16179 got.below_left,
16180 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
16181 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
16182 );
16183 }
16184 }
16185 }
16186 }
16187 }
16188 }
16189
16190 #[test]
16191 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
16192 let fctx = &crate::decode::FrameCtx::for_encoder();
16193 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
16194 // Interior superblock, so neither the frame edge nor the col == 0 /
16195 // last-row early returns answer instead of the table.
16196 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
16197 let mut flipped = 0;
16198 for row in 0..8 {
16199 for col in 1..8 {
16200 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
16201 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
16202 let vert = {
16203 let _guard = Reach::vert_ab_partition();
16204 Reach::of(8, x, y, width, height, fctx).below_left
16205 };
16206 // The TR square of a VERT_A/_B sits at an even row, odd
16207 // column; every other slot must be untouched by the guard.
16208 if row % 2 == 0 && col % 2 == 1 {
16209 assert!(!raster, "raster below_left at row={row} col={col}");
16210 assert!(vert, "vert below_left at row={row} col={col}");
16211 flipped += 1;
16212 } else {
16213 assert_eq!(raster, vert, "guard moved row={row} col={col}");
16214 }
16215 }
16216 }
16217 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
16218 // The guard is scoped: it must not leak past its own block.
16219 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
16220 }
16221
16222 /// An odd width or height is refused by name, not by however the padder
16223 /// or the block coder would happen to fail on it.
16224 #[test]
16225 fn odd_dimensions_are_refused() {
16226 let _knobs = crate::speed::knob_read();
16227 let fctx = &crate::decode::FrameCtx::for_encoder();
16228 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
16229 let picture = Picture::grey(width, height);
16230 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
16231 .expect_err(&format!("{width}x{height} is odd and must be refused"));
16232 assert!(
16233 err.to_string().contains("even"),
16234 "{width}x{height}: error was {err}"
16235 );
16236 }
16237 }
16238
16239 /// A sequence at a size that is not a multiple of the block grid decodes
16240 /// to the right frame count and the right size for every frame,
16241 /// including the inter frames whose reference is the previous frame's
16242 /// own (padded) reconstruction.
16243 #[test]
16244 fn sequence_round_trips_at_a_non_multiple_size() {
16245 let _knobs = crate::speed::knob_read();
16246 let fctx = &crate::decode::FrameCtx::for_encoder();
16247 if !have_ffmpeg() {
16248 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
16249 return;
16250 }
16251 let (width, height) = (160usize, 96usize);
16252 let pictures: Vec<Picture> = (0..3)
16253 .map(|i| panned_test_card(width, height, i * 3))
16254 .collect();
16255 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16256 assert_eq!(encoded.frames.len(), 3);
16257 for (i, frame) in encoded.frames.iter().enumerate() {
16258 assert_eq!(
16259 (frame.reconstruction.width, frame.reconstruction.height),
16260 (width, height),
16261 "frame {i}: reconstruction size"
16262 );
16263 }
16264 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
16265 // true (display) size a sequence's frames share, not the padded one.
16266 assert_eq!(
16267 ffprobe_size(&encoded.stream),
16268 (width as u32, height as u32),
16269 "sequence: ffprobe reports the true (display) size"
16270 );
16271 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
16272 assert_eq!(decoded.len(), 3, "decoded frame count");
16273 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16274 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16275 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16276 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16277 }
16278 }
16279
16280 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
16281 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
16282 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
16283 /// `pos + side_mi / 2 < bound` boundary), which is the case
16284 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
16285 /// refusing. A key frame alone already covered this size; this proves the
16286 /// inter tile writer's parity with it across a real multi-frame export.
16287 #[test]
16288 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
16289 let _knobs = crate::speed::knob_read();
16290 let fctx = &crate::decode::FrameCtx::for_encoder();
16291 if !have_ffmpeg() {
16292 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
16293 return;
16294 }
16295 let (width, height) = (1280usize, 720usize);
16296 let pictures: Vec<Picture> = (0..3)
16297 .map(|i| panned_test_card(width, height, i * 3))
16298 .collect();
16299 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16300 assert_eq!(encoded.frames.len(), 3);
16301 for (i, frame) in encoded.frames.iter().enumerate() {
16302 assert_eq!(
16303 (frame.reconstruction.width, frame.reconstruction.height),
16304 (width, height),
16305 "frame {i}: reconstruction size"
16306 );
16307 }
16308 assert_eq!(
16309 ffprobe_size(&encoded.stream),
16310 (width as u32, height as u32),
16311 "ffprobe reports the true (display) 1280x720 size"
16312 );
16313 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
16314 assert_eq!(decoded.len(), 3, "decoded frame count");
16315 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16316 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16317 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16318 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16319 }
16320 }
16321
16322 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
16323 /// leaf's own half (`has_half` at the SUB level) itself straddles the
16324 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
16325 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
16326 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
16327 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
16328 /// straddling-16x16 branch), so an inter frame no longer refuses this
16329 /// size either. This only proves the encoder does not error out -- see
16330 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
16331 /// decoder-clean proof (a 3-frame sequence, so the inter path is
16332 /// actually exercised).
16333 #[test]
16334 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
16335 let _knobs = crate::speed::knob_read();
16336 let fctx = &crate::decode::FrameCtx::for_encoder();
16337 let (width, height) = (640usize, 360usize);
16338 let picture = Picture::grey(width, height);
16339 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
16340
16341 // `encode_sequence`'s second frame is the inter path: same size, now
16342 // wired the same way.
16343 let pictures = vec![picture.clone(), picture];
16344 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
16345 .expect("inter frame now codes the mod-32==8 straddle too");
16346 }
16347
16348 /// The r15 fix at production size: three 640x360 key frames (inter is
16349 /// still refused at this size, per the test above, so this stands in for
16350 /// the charter's "3-frame sequence" using three independent key frames of
16351 /// shifted content), each proven decoder-clean through ffmpeg rather than
16352 /// only encoder-clean.
16353 #[test]
16354 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
16355 let _knobs = crate::speed::knob_read();
16356 let fctx = &crate::decode::FrameCtx::for_encoder();
16357 if !have_ffmpeg() {
16358 eprintln!(
16359 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
16360 no ffmpeg"
16361 );
16362 return;
16363 }
16364 let (width, height) = (640usize, 360usize);
16365 for shift in [0i64, 7, 19] {
16366 let picture = panned_test_card(width, height, shift);
16367 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16368 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16369 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
16370 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
16371 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
16372 }
16373 }
16374
16375 /// The 640x360 straddle class, but through the inter path an actual
16376 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
16377 /// proves the leaf-8 inter stream this round wires up is not just
16378 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
16379 #[test]
16380 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
16381 let _knobs = crate::speed::knob_read();
16382 let fctx = &crate::decode::FrameCtx::for_encoder();
16383 if !have_ffmpeg() {
16384 eprintln!(
16385 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
16386 );
16387 return;
16388 }
16389 let (width, height) = (640usize, 360usize);
16390 let pictures: Vec<Picture> = (0..4)
16391 .map(|i| panned_test_card(width, height, i * 3))
16392 .collect();
16393 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16394 assert_eq!(encoded.frames.len(), 4);
16395 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
16396 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
16397 }
16398 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
16399 assert_eq!(decoded.len(), 4, "decoded frame count");
16400 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16401 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16402 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16403 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16404 }
16405 }
16406
16407 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
16408 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
16409 let out = Command::new("ffmpeg")
16410 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
16411 .args(["-vf", &format!("scale={width}:{height}")])
16412 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
16413 .output()
16414 .expect("ffmpeg failed to run");
16415 assert!(
16416 out.status.success(),
16417 "ffmpeg: {}",
16418 String::from_utf8_lossy(&out.stderr)
16419 );
16420 let (luma, chroma) = (width * height, width * height / 4);
16421 assert_eq!(
16422 out.stdout.len(),
16423 luma + 2 * chroma,
16424 "expected one 4:2:0 frame"
16425 );
16426 Picture {
16427 width,
16428 height,
16429 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
16430 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
16431 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
16432 }
16433 }
16434
16435 /// Prints what the mode search saves over DC prediction alone, for the
16436 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
16437 /// weight the search puts on rate can be swept.
16438 #[test]
16439 #[ignore = "a sweep, not a gate"]
16440 fn probe_lambda() {
16441 let _knobs = crate::speed::knob_read();
16442 let fctx = &crate::decode::FrameCtx::for_encoder();
16443 let mut pictures = vec![
16444 ("test card".to_string(), test_card(160, 96)),
16445 ("stripes".to_string(), stripes(160, 96, true)),
16446 ];
16447 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
16448 for entry in clips.split(':').filter(|e| !e.is_empty()) {
16449 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
16450 let name = path.rsplit('/').next().unwrap_or(path).to_string();
16451 pictures.push((name, clip_frame(path, skip, 640, 352)));
16452 }
16453 }
16454 for (name, picture) in pictures {
16455 let dc = ladder(&picture, &[DC_PRED], fctx);
16456 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
16457 println!(
16458 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
16459 bd_rate(&dc, &searched) * 100.0,
16460 10f64.powf(searched[1].1),
16461 searched[1].0,
16462 10f64.powf(dc[1].1),
16463 dc[1].0,
16464 );
16465 }
16466 }
16467
16468 /// Prints the whole mode-search ladder, so two builds of the search can be
16469 /// compared against each other rather than each against its own baseline.
16470 #[test]
16471 #[ignore = "a sweep, not a gate"]
16472 fn probe_ladder() {
16473 let _knobs = crate::speed::knob_read();
16474 let fctx = &crate::decode::FrameCtx::for_encoder();
16475 for (name, picture) in sweep_pictures() {
16476 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
16477 let points = all
16478 .iter()
16479 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
16480 .collect::<Vec<_>>()
16481 .join(" ");
16482 println!("ladder {name}: {points}");
16483 }
16484 }
16485
16486 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
16487 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
16488 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
16489 #[test]
16490 #[ignore = "a sweep, not a gate"]
16491 fn probe_split() {
16492 let _knobs = crate::speed::knob_read();
16493 let fctx = &crate::decode::FrameCtx::for_encoder();
16494 for (name, picture) in sweep_pictures() {
16495 let ladder = |split: bool| {
16496 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
16497 .iter()
16498 .map(|&q| {
16499 let encoded = encode_key_frame_inner(
16500 &picture,
16501 q,
16502 0.5,
16503 &KEY_FRAME_MODES,
16504 split,
16505 (picture.width, picture.height),
16506 unspecified_color_config(), fctx,
16507 )
16508 .unwrap();
16509 (
16510 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
16511 (encoded.stream.len() as f64).log10(),
16512 )
16513 })
16514 .collect();
16515 points.sort_by(|a, b| a.0.total_cmp(&b.0));
16516 points
16517 };
16518 let (whole, split) = (ladder(false), ladder(true));
16519 let blocks = encode_key_frame_inner(
16520 &picture,
16521 90,
16522 0.5,
16523 &KEY_FRAME_MODES,
16524 true,
16525 (picture.width, picture.height),
16526 unspecified_color_config(), fctx,
16527 )
16528 .unwrap()
16529 .modes
16530 .len();
16531 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
16532 println!(
16533 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
16534 bd_rate(&whole, &split) * 100.0
16535 );
16536 }
16537 }
16538
16539 /// A striped picture, running one way or the other. The stripes are what
16540 /// separates a vertical predictor from a horizontal one: a mode search
16541 /// reading a transposed edge would pick the wrong one of the pair, which no
16542 /// symmetric picture would show.
16543 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
16544 let mut picture = Picture::grey(width, height);
16545 for y in 0..height {
16546 for x in 0..width {
16547 let along = if vertical { x } else { y };
16548 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
16549 }
16550 }
16551 picture
16552 }
16553
16554 /// Where two planes first disagree, and by how much: a mismatch reported as
16555 /// a position says which block and which sample of it went wrong, which a
16556 /// pair of thousand-sample arrays does not.
16557 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
16558 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
16559 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
16560 Some(format!(
16561 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
16562 i % width,
16563 i / width,
16564 ours[i],
16565 theirs[i]
16566 ))
16567 }
16568
16569 /// Every mode the encoder offers has to predict what the decoder predicts,
16570 /// not just the ones a particular picture happens to choose: each is forced
16571 /// over a whole picture and the reconstruction gated against ffmpeg.
16572 #[test]
16573 fn every_mode_decodes_to_what_the_encoder_predicted() {
16574 let _knobs = crate::speed::knob_write();
16575 let fctx = &crate::decode::FrameCtx::for_encoder();
16576 if !have_ffmpeg() {
16577 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
16578 return;
16579 }
16580 // A mode ablation measures the MODE search: a filter-intra block is
16581 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
16582 // "the encoder coded something else" check for a reason that is not
16583 // about the mode search at all.
16584 force_filter_intra(Some(false));
16585 // 128 wide is a whole number of superblocks and 160 is not: the last
16586 // superblock of a 160-wide row is half a one, whose blocks have no
16587 // above-right samples inside the frame at all.
16588 for (width, height) in [(128, 96), (160, 96)] {
16589 let picture = test_card(width, height);
16590 for mode in KEY_FRAME_MODES {
16591 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
16592 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16593 for (plane, ours, theirs, stride) in [
16594 ("luma", &encoded.reconstruction.y, &decoded.y, width),
16595 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
16596 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
16597 ] {
16598 assert!(
16599 first_difference(ours, theirs, stride).is_none(),
16600 "{width}x{height} mode {mode}, {plane}: {}",
16601 first_difference(ours, theirs, stride).unwrap()
16602 );
16603 }
16604 assert!(
16605 encoded.modes.iter().all(|&m| m == mode),
16606 "mode {mode}: the encoder coded something else"
16607 );
16608 }
16609 }
16610 }
16611
16612 /// The search has to follow the picture: vertical stripes are cheapest
16613 /// predicted from the row above, horizontal ones from the column to the
16614 /// left. Reading the edges the other way round would swap the two answers
16615 /// while leaving every fidelity gate intact.
16616 #[test]
16617 fn the_search_picks_the_direction_the_picture_runs() {
16618 let _knobs = crate::speed::knob_write();
16619 let fctx = &crate::decode::FrameCtx::for_encoder();
16620 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
16621 // a filter-intra block is coded `DC_PRED` whatever mode the arm
16622 // offers, and these stripes are SCREEN content, where the filter arm
16623 // now searches its own transform depth (lane-fitu) and wins outright
16624 // -- which says nothing about the mode search this gate measures.
16625 force_filter_intra(Some(false));
16626 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
16627 let picture = stripes(128, 96, vertical);
16628 // Only the pair, because on stripes a third mode predicts exactly
16629 // what the right one of the pair does -- PAETH reads the corner and
16630 // the left column, which a striped picture makes equal -- and the
16631 // tie then goes to whichever is cheaper to name, which is not what
16632 // this gate is about.
16633 let encoded =
16634 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
16635 // The first block of the picture has neither neighbour, so it
16636 // cannot tell the modes apart; every other one can.
16637 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
16638 assert!(
16639 picked * 2 > encoded.modes.len() - 1,
16640 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
16641 encoded.modes.len() - 1,
16642 encoded.modes
16643 );
16644 }
16645 }
16646
16647 /// What the search is for: the same picture, at the same quantizer, coded
16648 /// smaller and more faithfully than DC alone can manage.
16649 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
16650 /// between the two rate-distortion curves in log-rate against PSNR, as a
16651 /// fraction of the reference's rate. Negative means the second curve costs
16652 /// less for the same picture.
16653 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
16654 let low = reference[0].0.max(other[0].0);
16655 let high = reference[reference.len() - 1]
16656 .0
16657 .min(other[other.len() - 1].0);
16658 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
16659 // the non-directional one on the synthetic diagonals -- every point
16660 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
16661 // to integrate over any more. A curve that dominates that way has
16662 // saved everything the measure can express (the
16663 // `instrument-at-bound` class: the answer is at the instrument's own
16664 // edge, not undefined), so name it rather than panicking; anything
16665 // less clean than strict dominance still is.
16666 if high <= low {
16667 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
16668 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
16669 let dominates = other[0].0 > reference[reference.len() - 1].0
16670 && other_hi_rate <= ref_lo_rate;
16671 assert!(
16672 dominates,
16673 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
16674 );
16675 return -1.0;
16676 }
16677 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
16678 let i = curve
16679 .windows(2)
16680 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
16681 .unwrap_or(0);
16682 let (x0, y0) = curve[i];
16683 let (x1, y1) = curve[i + 1];
16684 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
16685 };
16686 let steps = 64;
16687 let mut area = 0.0;
16688 for step in 0..steps {
16689 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
16690 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
16691 }
16692 10f64.powf(area / f64::from(steps)) - 1.0
16693 }
16694
16695 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
16696 /// fidelity.
16697 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
16698 // A mode ablation measures the MODE search: the palette would code
16699 // these synthetic two-colour pictures losslessly under every arm and
16700 // leave nothing to compare (see [`force_screen`]).
16701 force_screen(Some(false));
16702 // Same reason, for the filter-intra candidate: it wins blocks under
16703 // BOTH arms of a mode ablation and so cancels the difference the
16704 // ablation measures (class `gate-recipe-confound`).
16705 force_filter_intra(Some(false));
16706 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
16707 .iter()
16708 .map(|&q| {
16709 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
16710 (
16711 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
16712 (encoded.stream.len() as f64).log10(),
16713 )
16714 })
16715 .collect();
16716 points.sort_by(|a, b| a.0.total_cmp(&b.0));
16717 points
16718 }
16719
16720 /// What the search is for: the same pictures cost less to code at the same
16721 /// fidelity than DC prediction alone can manage. A picture that runs one
16722 /// way saves far more than a busy one, which is the shape a working
16723 /// directional pair has.
16724 #[test]
16725 fn the_search_beats_dc_alone() {
16726 let _knobs = crate::speed::knob_read();
16727 let fctx = &crate::decode::FrameCtx::for_encoder();
16728 for (name, picture, want) in [
16729 ("test card", test_card(160, 96), -0.05),
16730 ("stripes", stripes(160, 96, true), -0.40),
16731 ] {
16732 let saved = bd_rate(
16733 &ladder(&picture, &[DC_PRED], fctx),
16734 &ladder(&picture, &NON_DIRECTIONAL, fctx),
16735 );
16736 assert!(
16737 saved < want,
16738 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
16739 saved * 100.0,
16740 -want * 100.0
16741 );
16742 }
16743 }
16744
16745 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
16746 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
16747 fn sweep_pictures() -> Vec<(String, Picture)> {
16748 let mut pictures = vec![
16749 ("test card".to_string(), test_card(160, 96)),
16750 ("stripes".to_string(), stripes(160, 96, true)),
16751 ("diagonal".to_string(), diagonal(160, 96, true)),
16752 ];
16753 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
16754 for entry in clips.split(':').filter(|e| !e.is_empty()) {
16755 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
16756 let name = path.rsplit('/').next().unwrap_or(path).to_string();
16757 pictures.push((name, clip_frame(path, skip, 640, 352)));
16758 }
16759 }
16760 pictures
16761 }
16762
16763 /// What the six directional modes are worth, per picture, at whatever
16764 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
16765 /// no further, and how often the search picks one.
16766 #[test]
16767 #[ignore = "a sweep, not a gate"]
16768 fn probe_directional() {
16769 let _knobs = crate::speed::knob_write();
16770 let fctx = &crate::decode::FrameCtx::for_encoder();
16771 for (name, picture) in sweep_pictures() {
16772 let dc = ladder(&picture, &[DC_PRED], fctx);
16773 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
16774 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
16775 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
16776 let directional = encoded
16777 .modes
16778 .iter()
16779 .filter(|&&m| (3..=8).contains(&m))
16780 .count();
16781 // A picture whose ladders sit at different fidelities altogether
16782 // has no BD-rate to report -- see the flat-sample-window class.
16783 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
16784 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
16785 };
16786 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
16787 if overlap(a, b) {
16788 format!("{:+.2}%", bd_rate(a, b) * 100.0)
16789 } else {
16790 "no overlap".to_string()
16791 }
16792 };
16793 println!(
16794 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
16795 against(&flat, &all),
16796 against(&dc, &all),
16797 encoded.modes.len(),
16798 );
16799 }
16800 }
16801
16802 /// A picture whose stripes run along a diagonal, one way or the other.
16803 /// This is to the directional modes what [`stripes`] is to the vertical and
16804 /// horizontal pair: a predictor that walked the edge in the wrong direction
16805 /// would answer the two pictures the same way round.
16806 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
16807 let mut picture = Picture::grey(width, height);
16808 for y in 0..height {
16809 for x in 0..width {
16810 let along = if down_right { x + height - y } else { x + y };
16811 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
16812 }
16813 }
16814 picture
16815 }
16816
16817 /// The mode picked by the most blocks of a picture, ignoring the first
16818 /// block, which has no neighbours to tell the modes apart with.
16819 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
16820 // A mode ablation measures the MODE search: the palette would code
16821 // these synthetic two-colour pictures losslessly under every arm and
16822 // leave nothing to compare (see [`force_screen`]).
16823 force_screen(Some(false));
16824 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
16825 let blocks = &encoded.modes[1..];
16826 let mut counts = [0usize; 13];
16827 for &mode in blocks {
16828 counts[usize::from(mode)] += 1;
16829 }
16830 let (mode, count) = counts
16831 .iter()
16832 .enumerate()
16833 .max_by_key(|&(_, count)| *count)
16834 .expect("thirteen modes");
16835 (mode as u8, *count, blocks.len())
16836 }
16837
16838 /// The search has to follow a diagonal the way it runs: stripes down and to
16839 /// the right are cheapest predicted at 135 degrees, stripes down and to the
16840 /// left at 45. A walk that stepped the wrong way along the edge, or read
16841 /// the above row where it should read the left column, would swap these.
16842 #[test]
16843 fn the_search_picks_the_diagonal_the_picture_runs() {
16844 let _knobs = crate::speed::knob_write();
16845 let fctx = &crate::decode::FrameCtx::for_encoder();
16846 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
16847 let picture = diagonal(160, 96, down_right);
16848 let (mode, count, blocks) = favourite_mode(&picture, fctx);
16849 assert_eq!(
16850 mode, want,
16851 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
16852 );
16853 }
16854 }
16855
16856 /// What the directional modes are for: a picture that runs along a diagonal
16857 /// costs far less to code with them than the seven that read only their own
16858 /// edges can manage, and a picture that runs no particular way costs no
16859 /// more. The second half is the one that bites: a mode set the search
16860 /// cannot price is a mode set that loses rate on content that does not want
16861 /// it, which is what costing the mode symbol is for.
16862 #[test]
16863 fn the_diagonals_beat_the_modes_that_read_no_further() {
16864 let _knobs = crate::speed::knob_read();
16865 let fctx = &crate::decode::FrameCtx::for_encoder();
16866 for (name, picture, want) in [
16867 ("down-right", diagonal(160, 96, true), -0.20),
16868 ("down-left", diagonal(160, 96, false), -0.20),
16869 ("test card", test_card(160, 96), 0.01),
16870 ] {
16871 let saved = bd_rate(
16872 &ladder(&picture, &NON_DIRECTIONAL, fctx),
16873 &ladder(&picture, &KEY_FRAME_MODES, fctx),
16874 );
16875 assert!(
16876 saved < want,
16877 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
16878 saved * 100.0,
16879 -want * 100.0
16880 );
16881 }
16882 }
16883
16884 /// A mode the encoder cannot predict must be refused rather than coded as
16885 /// something else, and a search with nothing to choose from likewise.
16886 #[test]
16887 fn a_mode_the_encoder_cannot_predict_is_refused() {
16888 let _knobs = crate::speed::knob_read();
16889 let fctx = &crate::decode::FrameCtx::for_encoder();
16890 let picture = test_card(64, 64);
16891 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
16892 .unwrap_err()
16893 .to_string();
16894 assert!(
16895 message.contains("intra mode 13"),
16896 "the refusal must name the mode, got {message}"
16897 );
16898 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
16899 }
16900
16901 /// The picture that comes back is the picture that went in, to within the
16902 /// quantizer. A prediction that read the wrong neighbours, or a block
16903 /// written into the wrong place, would still decode to what the encoder
16904 /// reconstructed — it is this gate that says the reconstruction is of the
16905 /// right picture.
16906 #[test]
16907 fn the_encoded_picture_is_the_one_that_went_in() {
16908 let _knobs = crate::speed::knob_read();
16909 let fctx = &crate::decode::FrameCtx::for_encoder();
16910 let picture = test_card(160, 96);
16911 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16912 let luma = psnr(&encoded.reconstruction.y, &picture.y);
16913 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
16914 for (plane, (got, want)) in [
16915 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
16916 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
16917 ]
16918 .iter()
16919 .enumerate()
16920 {
16921 let chroma = psnr(got, want);
16922 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
16923 }
16924 }
16925
16926 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
16927 /// does the opposite. Both are monotone, which is what a rate-distortion
16928 /// loop above this will assume.
16929 #[test]
16930 fn fidelity_and_rate_move_with_the_quantizer() {
16931 let _knobs = crate::speed::knob_read();
16932 let fctx = &crate::decode::FrameCtx::for_encoder();
16933 let picture = test_card(128, 128);
16934 let mut previous: Option<(usize, f64)> = None;
16935 for &q in &[70u8, 90, 110] {
16936 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16937 let quality = psnr(&encoded.reconstruction.y, &picture.y);
16938 if let Some((bytes, better)) = previous {
16939 assert!(
16940 encoded.stream.len() < bytes,
16941 "q {q}: {} bytes",
16942 encoded.stream.len()
16943 );
16944 assert!(quality < better, "q {q}: PSNR {quality}");
16945 }
16946 previous = Some((encoded.stream.len(), quality));
16947 }
16948
16949 // The deadzone half of this claim lives in
16950 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
16951 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
16952 // every zeroing, the deadzone no longer moves a coded stream
16953 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
16954 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
16955 // job, not a quantiser defect.
16956
16957 // Bytes must not jump up across a q-context boundary: a wrong CDF
16958 // table for the far side would show up as a rate discontinuity here,
16959 // even though a coarser quantizer always codes no more than a finer
16960 // one on the same picture.
16961 //
16962 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
16963 // chroma searches its own mode, a coarser quantizer can pick a
16964 // *different* uv_mode on a block whose modes now cost nearly the
16965 // same, and the search prices that symbol against the static default
16966 // CDF while the writer codes it against an adapted one -- 311 -> 319
16967 // bytes at q 120->121 on this picture. The table this gate is really
16968 // watching would move the rate by far more than the mode churn does.
16969 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
16970 // same block can also change transform DEPTH between two neighbouring
16971 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
16972 // symbol is priced off the static CDF row 0 for the same reason the
16973 // uv_mode one is.
16974 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
16975 // path is pricing through the adapting CDF state (what
16976 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
16977 // drift of), after which the exact bound comes back.
16978 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
16979 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
16980 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
16981 assert!(
16982 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
16983 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
16984 );
16985 }
16986 }
16987
16988 /// A flat picture is a flat stream: every block predicts its neighbours'
16989 /// average, which is the picture's own value, and codes nothing.
16990 #[test]
16991 fn a_flat_picture_costs_almost_nothing() {
16992 let _knobs = crate::speed::knob_read();
16993 let fctx = &crate::decode::FrameCtx::for_encoder();
16994 let mut picture = Picture::grey(128, 128);
16995 picture.y.fill(97);
16996 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16997 // The first block has no neighbour and predicts 128, so it carries a
16998 // DC; every block after it predicts 97 and carries nothing.
16999 assert!(
17000 encoded.stream.len() < 100,
17001 "{} bytes for a flat picture",
17002 encoded.stream.len()
17003 );
17004 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
17005 assert_eq!(s, 97, "sample {i} of a flat picture");
17006 }
17007 }
17008
17009 /// The sizes the encoder refuses, refused for a reason rather than by
17010 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
17011 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
17012 /// lands past the halfway point of whichever block it falls in, so
17013 /// `PARTITION_NONE` or a single gathered split flag still says everything
17014 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
17015 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
17016 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
17017 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
17018 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
17019 /// refusal here claimed otherwise and was wrong; see
17020 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
17021 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
17022 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
17023 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
17024 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
17025 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
17026 /// still refused is a malformed picture.
17027 #[test]
17028 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
17029 let _knobs = crate::speed::knob_read();
17030 let fctx = &crate::decode::FrameCtx::for_encoder();
17031 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
17032 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
17033 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
17034 .expect("36 luma columns still round up to an even MiCols");
17035
17036 let mut short = Picture::grey(64, 64);
17037 short.u.truncate(10);
17038 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
17039 }
17040
17041 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
17042 /// column half only (`has_half` false on cols, true on rows) -- exactly
17043 /// the single-axis straddle lane-av1-rect r7 wires through
17044 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
17045 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
17046 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
17047 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
17048 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
17049 /// `partition_context_lookup` entry this writer ever produces (no 4x4
17050 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
17051 /// leaf regardless of neighbour state -- our writer already agreed with
17052 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
17053 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
17054 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
17055 /// it does not regress the gate. r11 tell-for-tell traced two further,
17056 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
17057 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
17058 /// leaves, when the second leaf's true above (or left) neighbour is the
17059 /// first leaf itself -- fixed by threading the first leaf's mode into the
17060 /// second leaf's context, mi-precise, like `record_mi` already does for
17061 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
17062 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
17063 /// `reduced_tx_set` is false), but this crate's key frames set
17064 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
17065 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
17066 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
17067 /// symbol bits to desync everything after it. Fixed with a new
17068 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
17069 /// eset/size slot). Both fixes are provably correct against libaom
17070 /// source and each closed part of the gap (leaf0's `eob` went from a
17071 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
17072 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
17073 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
17074 /// (do not reuse r11's committed logs, which predate its own fixes) and
17075 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
17076 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
17077 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
17078 /// every other `write_block` caller at 16x16 and up already passes
17079 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
17080 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
17081 /// different amount of arithmetic range and derailed everything after
17082 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
17083 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
17084 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
17085 /// never updating those coarse arrays itself -- so a *second* straddling
17086 /// 16x16 quadrant stacked above or left of the first (never covered by
17087 /// r11's same-call `prev_leaf` override, which only threads state
17088 /// between the two leaves of one shared quadrant) read whatever stale
17089 /// mode sat in that slot before either leaf ran. Fixed by writing the
17090 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
17091 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
17092 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
17093 /// offset of a single unit; fixing (3)+(4) together still leaves a
17094 /// residual divergence one leaf further in -- the decoder now reads
17095 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
17096 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
17097 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
17098 /// desyncs the stream by exactly the width of one earlier symbol -- not
17099 /// yet isolated to a single named symbol. r15 found the last bug: the
17100 /// header fix from r14 explained the rng skew fully, and the remaining
17101 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
17102 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
17103 /// loop, once per leaf, so the first leaf's write clobbered the true
17104 /// external neighbour mode the second leaf of the *same* straddling
17105 /// quadrant still needed for its non-adjacency axis (a column-straddle
17106 /// case: two leaves share one `outer_at` column index, so leaf 1's
17107 /// write to `left_mode[r]` overwrote the real western neighbour before
17108 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
17109 /// doing it once, after the whole leaf loop, from the last (bottom/
17110 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
17111 #[test]
17112 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
17113 let _knobs = crate::speed::knob_read();
17114 let fctx = &crate::decode::FrameCtx::for_encoder();
17115 if !have_ffmpeg() {
17116 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
17117 return;
17118 }
17119 let (width, height) = (40usize, 32usize);
17120 let picture = test_card(width, height);
17121 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17122 assert_eq!(
17123 (encoded.reconstruction.width, encoded.reconstruction.height),
17124 (width, height)
17125 );
17126 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
17127 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
17128 }
17129 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17130 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
17131 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
17132 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
17133 }
17134
17135 /// A frame of real video, rather than a picture built to be easy.
17136 ///
17137 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
17138 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
17139 /// encoder's reconstruction has to survive the same equality gate as the
17140 /// synthetic pictures — real video reaches contexts a test card does not.
17141 #[test]
17142 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
17143 let _knobs = crate::speed::knob_read();
17144 let fctx = &crate::decode::FrameCtx::for_encoder();
17145 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
17146 eprintln!(
17147 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
17148 set EC_AV1_CLIP to a clip"
17149 );
17150 return;
17151 };
17152 if !have_ffmpeg() {
17153 eprintln!(
17154 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
17155 );
17156 return;
17157 }
17158 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
17159 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
17160 // test quick while still spanning many superblocks.
17161 let (width, height) = (640usize, 352usize);
17162 let picture = clip_frame(&clip, &skip, width, height);
17163
17164 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17165 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17166 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
17167 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
17168 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
17169 eprintln!(
17170 "{} bytes, luma PSNR {:.2} dB",
17171 encoded.stream.len(),
17172 psnr(&decoded.y, &picture.y)
17173 );
17174 }
17175
17176 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
17177 /// sequence of these is a translation a motion search can actually find
17178 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
17179 /// inter frame's rate against the key frame's is measuring the same
17180 /// picture moving, not two different pictures.
17181 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
17182 let mut picture = Picture::grey(width, height);
17183 for y in 0..height {
17184 for x in 0..width {
17185 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
17186 let gradient = sx * 200.0 / width as f64;
17187 let ripple = 30.0
17188 * (sx * std::f64::consts::PI / 23.0).sin()
17189 * (y as f64 * std::f64::consts::PI / 37.0).cos();
17190 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
17191 40.0
17192 } else {
17193 0.0
17194 };
17195 picture.y[y * width + x] =
17196 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
17197 }
17198 }
17199 for y in 0..height / 2 {
17200 for x in 0..width / 2 {
17201 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
17202 let i = y * width / 2 + x;
17203 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
17204 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
17205 }
17206 }
17207 picture
17208 }
17209
17210 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
17211 fn ffmpeg_decode_sequence(
17212 stream: &[u8],
17213 width: usize,
17214 height: usize,
17215 frames: usize,
17216 ) -> Vec<Picture> {
17217 let out = run_with_stdin(
17218 Command::new("ffmpeg").args([
17219 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
17220 ]),
17221 stream,
17222 );
17223 assert!(
17224 out.status.success(),
17225 "ffmpeg refused the stream: {}",
17226 String::from_utf8_lossy(&out.stderr)
17227 );
17228 let (luma, chroma) = (width * height, width * height / 4);
17229 let frame_bytes = luma + 2 * chroma;
17230 assert_eq!(
17231 out.stdout.len(),
17232 frame_bytes * frames,
17233 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
17234 String::from_utf8_lossy(&out.stderr)
17235 );
17236 (0..frames)
17237 .map(|i| {
17238 let base = i * frame_bytes;
17239 Picture {
17240 width,
17241 height,
17242 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
17243 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
17244 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
17245 }
17246 })
17247 .collect()
17248 }
17249
17250 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
17251 /// makes for a key frame, extended down the reference chain: each inter
17252 /// frame's reconstruction predicts from the previous frame's own decoded
17253 /// reconstruction, so a single sample of drift anywhere would propagate
17254 /// into every frame after it -- which is why every frame is checked, not
17255 /// just the last one, and why this is an equality and not a tolerance.
17256 #[test]
17257 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
17258 let _knobs = crate::speed::knob_read();
17259 let fctx = &crate::decode::FrameCtx::for_encoder();
17260 if !have_ffmpeg() {
17261 eprintln!(
17262 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
17263 );
17264 return;
17265 }
17266 let (width, height) = (128usize, 64usize);
17267 let pictures: Vec<Picture> = (0..5)
17268 .map(|i| panned_test_card(width, height, i * 3))
17269 .collect();
17270 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17271 assert_eq!(encoded.frames.len(), 5);
17272
17273 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
17274 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17275 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
17276 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
17277 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
17278 }
17279
17280 eprintln!("frame bytes luma PSNR (dB) inter share");
17281 for (i, frame) in encoded.frames.iter().enumerate() {
17282 eprintln!(
17283 "{i:5} {:5} {:14.2} {:11.2}",
17284 frame.stream.len(),
17285 psnr(&frame.reconstruction.y, &pictures[i].y),
17286 frame.inter_block_share
17287 );
17288 }
17289 }
17290
17291 /// The same sequence through OUR OWN decoder, sample-exact against the
17292 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
17293 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
17294 /// divergence point at all, while our decoder can be traced symbol by
17295 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
17296 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
17297 /// names the first differing frame, plane and position.
17298 /// lane-sb128b: the writer used to price a `NEWMV` residual against
17299 /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
17300 /// write-time stack could not carry, while the drl symbols signalled the
17301 /// clamped index -- so the decoder derived a DIFFERENT motion vector with
17302 /// the entropy stream still in sync, and the drift only surfaced frames
17303 /// later as a drl desync (on film B, as the encoder's own trial decode
17304 /// refusing a reference slot).
17305 ///
17306 /// The clamp needs a stack that shrinks between search and write, which
17307 /// is what a 128x128 superblock's visit order does; the counter is the
17308 /// point (class `gate-blind-to-feature`): a green round trip on a clip
17309 /// that never clamps proves nothing.
17310 ///
17311 /// `#[ignore]`: [`force_sb128`] moves a process-global.
17312 ///
17313 /// cargo test -p ec-av1 --release --lib -- --ignored \
17314 /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture
17315 /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
17316 /// and one motion vector where the four 64x64 roots below spend four of
17317 /// each (cen3's L1). The counter is the gate on the fixture (class
17318 /// `gate-blind-to-feature`): a green round trip on a clip that never
17319 /// codes a 128x128 block proves nothing. RED before the search existed
17320 /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
17321 /// root by construction).
17322 ///
17323 /// Both readers: our own decoder sample-exact against the encoder's
17324 /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
17325 /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
17326 ///
17327 /// `#[ignore]`: [`force_sb128`] moves a process-global.
17328 ///
17329 /// cargo test -p ec-av1 --release --lib -- --ignored \
17330 /// a_128_superblock_clip_whose_root_search --nocapture
17331 #[test]
17332 #[ignore = "sets the process-global superblock size: run it alone"]
17333 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
17334 let _knobs = crate::speed::knob_write();
17335 if !have_ffmpeg() {
17336 eprintln!("SKIP: no ffmpeg");
17337 return;
17338 }
17339 force_sb128(true);
17340 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
17341 std::fs::create_dir_all(&dir).unwrap();
17342 let clip = dir.join("smpte-1280x768.y4m");
17343 // A slow horizontal pan over a still pattern: whole 128x128 regions
17344 // share one motion vector, which is exactly what a 128 root can code
17345 // as one block and four 64 roots cannot.
17346 let ok = Command::new("ffmpeg")
17347 .args(["-v", "error", "-y", "-f", "lavfi"])
17348 .args(["-i", "smptebars=size=1600x768:rate=24"])
17349 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17350 .args(["-pix_fmt", "yuv420p"])
17351 .arg(&clip)
17352 .status()
17353 .expect("ffmpeg failed to run")
17354 .success();
17355 assert!(ok, "ffmpeg could not write the synthetic clip");
17356 let (width, height) = (1280usize, 768usize);
17357 let pictures =
17358 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17359 let _ = take_b128_none_hits();
17360 let _ = crate::tile::take_sb128_none_hits();
17361 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17362 let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
17363 eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
17364 assert!(
17365 coded > 0,
17366 "no 128x128 block was coded on this clip, so it cannot witness the root search",
17367 );
17368 assert_eq!(won, coded, "every 128x128 root the search took must be coded as one");
17369 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17370 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17371 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17372 let recon = &frame.reconstruction;
17373 for (plane, got, want) in [
17374 ("luma", &dec.y, &recon.y),
17375 ("U", &dec.u, &recon.u),
17376 ("V", &dec.v, &recon.v),
17377 ] {
17378 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17379 assert_eq!(
17380 differ, 0,
17381 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17382 own reconstruction",
17383 got.len()
17384 );
17385 }
17386 }
17387 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17388 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17389 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17390 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17391 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17392 }
17393 }
17394
17395 /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
17396 /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
17397 /// same pan the skip-only witness above uses, with the arm FORCED
17398 /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
17399 /// about once per frame, which witnesses the shape but not every context
17400 /// it reads, and forcing codes all 420 roots of the clip through it. RED
17401 /// before this lane by construction (`write_inter_block_128` refused
17402 /// every non-skip 128 block, so no such block existed to decode), and RED
17403 /// again on the first draft of the writer, whose neighbour band recorded
17404 /// `skip = true` for a block that carries a residual -- the next root's
17405 /// `skip` symbol then took CDF row 1 where the reader takes row 0.
17406 ///
17407 /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces
17408 /// the skip arm's cost unconditionally (that is what makes the writer see
17409 /// the residual), and the cost model moved under it since lane-b128r --
17410 /// lane-rectdq made every non-skipped root pay its delta_q group and the
17411 /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root
17412 /// lost its partition at ALL 420 roots and the writer coded none. q=60
17413 /// puts 52 written blocks back on this clip; the `coded > 0` assert below
17414 /// is the guard that catches the next such drift.
17415 ///
17416 /// cargo test -p ec-av1 --release --lib -- --ignored \
17417 /// a_128_root_block_with_a_real_residual --nocapture
17418 #[test]
17419 #[ignore = "sets the process-global superblock size: run it alone"]
17420 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
17421 let _knobs = crate::speed::knob_write();
17422 if !have_ffmpeg() {
17423 eprintln!("SKIP: no ffmpeg");
17424 return;
17425 }
17426 force_sb128(true);
17427 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
17428 std::fs::create_dir_all(&dir).unwrap();
17429 let clip = dir.join("smpte-pan-1280x768.y4m");
17430 let ok = Command::new("ffmpeg")
17431 .args(["-v", "error", "-y", "-f", "lavfi"])
17432 .args(["-i", "smptebars=size=1600x768:rate=24"])
17433 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17434 .args(["-pix_fmt", "yuv420p"])
17435 .arg(&clip)
17436 .status()
17437 .expect("ffmpeg failed to run")
17438 .success();
17439 assert!(ok, "ffmpeg could not write the synthetic clip");
17440 let (width, height) = (1280usize, 768usize);
17441 let pictures =
17442 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17443 let _ = take_b128_residual_hits();
17444 let _ = crate::tile::take_sb128_residual_hits();
17445 force_b128_residual(true);
17446 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17447 let (won, coded) =
17448 (take_b128_residual_hits(), crate::tile::take_sb128_residual_hits());
17449 eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
17450 assert!(
17451 coded > 0,
17452 "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
17453 );
17454 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17455 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17456 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17457 let recon = &frame.reconstruction;
17458 for (plane, got, want) in [
17459 ("luma", &dec.y, &recon.y),
17460 ("U", &dec.u, &recon.u),
17461 ("V", &dec.v, &recon.v),
17462 ] {
17463 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17464 assert_eq!(
17465 differ, 0,
17466 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17467 own reconstruction",
17468 got.len()
17469 );
17470 }
17471 }
17472 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17473 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17474 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17475 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17476 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17477 }
17478 }
17479
17480 /// lane-edge128: a 128x128 root block WITH a residual on a clip whose
17481 /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec
17482 /// 5.11.56) codes ONE literal for the block that first reaches a unit and
17483 /// copies it over every unit the block SPANS, so the four units of a 128
17484 /// root share one index -- while the encoder's CDEF search prices a
17485 /// preset per unit and its filter replay applied all four. Only the first
17486 /// reached the stream, so every decoder filtered the other three with the
17487 /// origin's strengths and the encoder's reconstruction (the picture the
17488 /// next frame predicts from) was a filter apart from what a decoder
17489 /// produces. RED before this lane on the native BD gate's bars 2160p row
17490 /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples,
17491 /// the rows above the 128 superblock's own edge); the stream itself was
17492 /// always right -- ffmpeg and our own decoder agreed with each other and
17493 /// disagreed with the encoder.
17494 ///
17495 /// `take_cdef_covered_units` is the gate on the fixture (class
17496 /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair
17497 /// for the whole frame codes no literal at all and witnesses nothing.
17498 ///
17499 /// cargo test -p ec-av1 --release --lib -- --ignored \
17500 /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture
17501 #[test]
17502 #[ignore = "sets the process-global superblock size: run it alone"]
17503 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
17504 let _knobs = crate::speed::knob_write();
17505 if !have_ffmpeg() {
17506 eprintln!("SKIP: no ffmpeg");
17507 return;
17508 }
17509 force_sb128(true);
17510 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
17511 std::fs::create_dir_all(&dir).unwrap();
17512 let clip = dir.join("testsrc2-1280x768.y4m");
17513 // Detailed synthetic content: its CDEF search spends more than one
17514 // strength pair, which is what puts a `cdef_idx` literal in the tile.
17515 let ok = Command::new("ffmpeg")
17516 .args(["-v", "error", "-y", "-f", "lavfi"])
17517 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17518 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17519 .arg(&clip)
17520 .status()
17521 .expect("ffmpeg failed to run")
17522 .success();
17523 assert!(ok, "ffmpeg could not write the synthetic clip");
17524 let (width, height) = (1280usize, 768usize);
17525 let pictures =
17526 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17527 force_b128_root(true);
17528 force_b128_residual(true);
17529 let _ = crate::tile::take_sb128_residual_hits();
17530 let _ = crate::filter_search::take_cdef_covered_units();
17531 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17532 let coded = crate::tile::take_sb128_residual_hits();
17533 let covered = crate::filter_search::take_cdef_covered_units();
17534 eprintln!(
17535 "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17536 another unit's literal: {covered}"
17537 );
17538 assert!(coded > 0, "no 128x128 block carried a residual on this clip");
17539 assert!(
17540 covered > 0,
17541 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17542 cannot witness the rule",
17543 );
17544 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17545 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17546 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17547 for (plane, got, want) in [
17548 ("luma", &dec.y, &frame.reconstruction.y),
17549 ("U", &dec.u, &frame.reconstruction.u),
17550 ("V", &dec.v, &frame.reconstruction.v),
17551 ] {
17552 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17553 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17554 }
17555 }
17556 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17557 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17558 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17559 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17560 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17561 }
17562 }
17563
17564 /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
17565 /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
17566 /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
17567 /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
17568 /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
17569 /// rect partition with [`force_b128_rect`]) so every inter root of the
17570 /// clip goes through it; the `coded > 0` assert is the guard that catches
17571 /// the next fixture drift (the whole-128 twin of this witness went RED
17572 /// twice that way).
17573 ///
17574 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17575 /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
17576 #[test]
17577 #[ignore = "sets the process-global superblock size: run it alone"]
17578 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
17579 let _knobs = crate::speed::knob_write();
17580 if !have_ffmpeg() {
17581 eprintln!("SKIP: no ffmpeg");
17582 return;
17583 }
17584 force_sb128(true);
17585 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
17586 std::fs::create_dir_all(&dir).unwrap();
17587 let clip = dir.join("smpte-pan-1280x768.y4m");
17588 let ok = Command::new("ffmpeg")
17589 .args(["-v", "error", "-y", "-f", "lavfi"])
17590 .args(["-i", "smptebars=size=1600x768:rate=24"])
17591 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17592 .args(["-pix_fmt", "yuv420p"])
17593 .arg(&clip)
17594 .status()
17595 .expect("ffmpeg failed to run")
17596 .success();
17597 assert!(ok, "ffmpeg could not write the synthetic clip");
17598 let (width, height) = (1280usize, 768usize);
17599 let pictures =
17600 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17601 force_b128_rect(1);
17602 force_b128_rectres(true);
17603 let _ = take_b128_rectres_hits();
17604 let _ = crate::tile::take_sb128_rectres_hits();
17605 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17606 let (won, coded) =
17607 (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17608 eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
17609 assert!(
17610 coded > 0,
17611 "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
17612 );
17613 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17614 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17615 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17616 let recon = &frame.reconstruction;
17617 for (plane, got, want) in [
17618 ("luma", &dec.y, &recon.y),
17619 ("U", &dec.u, &recon.u),
17620 ("V", &dec.v, &recon.v),
17621 ] {
17622 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17623 assert_eq!(
17624 differ, 0,
17625 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17626 own reconstruction",
17627 got.len()
17628 );
17629 }
17630 }
17631 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17632 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17633 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17634 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17635 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17636 }
17637 }
17638
17639 /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
17640 /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
17641 /// the two 64x64 squares through the one-chunk arm (the shape libaom's
17642 /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
17643 /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
17644 /// reference picture the GOP has not produced yet, which refuses before
17645 /// any AB root is coded.
17646 ///
17647 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17648 /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
17649 #[test]
17650 #[ignore = "sets the process-global superblock size: run it alone"]
17651 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
17652 let _knobs = crate::speed::knob_write();
17653 if !have_ffmpeg() {
17654 eprintln!("SKIP: no ffmpeg");
17655 return;
17656 }
17657 force_sb128(true);
17658 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
17659 std::fs::create_dir_all(&dir).unwrap();
17660 let clip = dir.join("testsrc2-1280x768.y4m");
17661 let ok = Command::new("ffmpeg")
17662 .args(["-v", "error", "-y", "-f", "lavfi"])
17663 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17664 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17665 .arg(&clip)
17666 .status()
17667 .expect("ffmpeg failed to run")
17668 .success();
17669 assert!(ok, "ffmpeg could not write the synthetic clip");
17670 let (width, height) = (1280usize, 768usize);
17671 let pictures =
17672 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17673 force_b128_ab(4);
17674 force_b128_rectres(true);
17675 let _ = take_b128_rectres_hits();
17676 let _ = crate::tile::take_sb128_rectres_hits();
17677 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17678 let (won, coded) =
17679 (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17680 eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
17681 assert!(
17682 coded > 0,
17683 "no AB piece carried a residual on this clip, so it cannot witness the arm",
17684 );
17685 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17686 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17687 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17688 let recon = &frame.reconstruction;
17689 for (plane, got, want) in [
17690 ("luma", &dec.y, &recon.y),
17691 ("U", &dec.u, &recon.u),
17692 ("V", &dec.v, &recon.v),
17693 ] {
17694 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17695 assert_eq!(
17696 differ, 0,
17697 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17698 own reconstruction",
17699 got.len()
17700 );
17701 }
17702 }
17703 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17704 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17705 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17706 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17707 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17708 }
17709 }
17710
17711 /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
17712 /// half WITH a residual under a clip whose CDEF search codes a
17713 /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
17714 /// and the decoder stamps BOTH units it spans with it, so the owner map
17715 /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
17716 /// collapse the pair -- exactly the bug class that broke bars 2160p at
17717 /// the whole-128 root. RED before this lane by construction: no rect
17718 /// piece could carry a residual, so no such literal existed.
17719 ///
17720 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17721 /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
17722 #[test]
17723 #[ignore = "sets the process-global superblock size: run it alone"]
17724 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
17725 let _knobs = crate::speed::knob_write();
17726 if !have_ffmpeg() {
17727 eprintln!("SKIP: no ffmpeg");
17728 return;
17729 }
17730 force_sb128(true);
17731 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
17732 std::fs::create_dir_all(&dir).unwrap();
17733 let clip = dir.join("testsrc2-1280x768.y4m");
17734 // Detailed synthetic content: its CDEF search spends more than one
17735 // strength pair, which is what puts a `cdef_idx` literal in the tile.
17736 let ok = Command::new("ffmpeg")
17737 .args(["-v", "error", "-y", "-f", "lavfi"])
17738 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17739 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17740 .arg(&clip)
17741 .status()
17742 .expect("ffmpeg failed to run")
17743 .success();
17744 assert!(ok, "ffmpeg could not write the synthetic clip");
17745 let (width, height) = (1280usize, 768usize);
17746 let pictures =
17747 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17748 force_b128_rect(1);
17749 force_b128_rectres(true);
17750 let _ = crate::tile::take_sb128_rectres_hits();
17751 let _ = crate::filter_search::take_cdef_covered_units();
17752 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17753 let coded = crate::tile::take_sb128_rectres_hits();
17754 let covered = crate::filter_search::take_cdef_covered_units();
17755 eprintln!(
17756 "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17757 another unit's literal: {covered}"
17758 );
17759 assert!(coded > 0, "no 128x64 half carried a residual on this clip");
17760 assert!(
17761 covered > 0,
17762 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17763 cannot witness the rule",
17764 );
17765 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17766 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17767 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17768 for (plane, got, want) in [
17769 ("luma", &dec.y, &frame.reconstruction.y),
17770 ("U", &dec.u, &frame.reconstruction.u),
17771 ("V", &dec.v, &frame.reconstruction.v),
17772 ] {
17773 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17774 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17775 }
17776 }
17777 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17778 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17779 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17780 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17781 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17782 }
17783 }
17784
17785 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
17786 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
17787 /// `write_compound_block` chain every smaller compound block takes, at a
17788 /// window it had never been exercised at. RED before this lane: the
17789 /// search passed an empty compound list at the 128 root, so the count was
17790 /// 0 and no such block existed to decode.
17791 ///
17792 /// cargo test -p ec-av1 --release --lib -- --ignored \
17793 /// a_128_root_compound_block --nocapture
17794 #[test]
17795 #[ignore = "sets the process-global superblock size: run it alone"]
17796 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
17797 let _knobs = crate::speed::knob_write();
17798 if !have_ffmpeg() {
17799 eprintln!("SKIP: no ffmpeg");
17800 return;
17801 }
17802 force_sb128(true);
17803 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
17804 std::fs::create_dir_all(&dir).unwrap();
17805 let clip = dir.join("testsrc2-1280x768.y4m");
17806 // Moving objects that occlude each other: a pan is coded by one
17807 // reference outright, and a compound pair only pays where the two
17808 // references disagree.
17809 let ok = Command::new("ffmpeg")
17810 .args(["-v", "error", "-y", "-f", "lavfi"])
17811 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17812 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17813 .arg(&clip)
17814 .status()
17815 .expect("ffmpeg failed to run")
17816 .success();
17817 assert!(ok, "ffmpeg could not write the synthetic clip");
17818 let (width, height) = (1280usize, 768usize);
17819 let pictures =
17820 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17821 // The compound candidate wins the 128 block's own search on this pan
17822 // but the root then loses to its four cells, so the root is forced
17823 // (the residual arm is left at its default, off).
17824 force_b128_root(true);
17825 let _ = take_b128_compound_hits();
17826 let _ = crate::tile::take_sb128_compound_hits();
17827 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17828 let (won, coded) =
17829 (take_b128_compound_hits(), crate::tile::take_sb128_compound_hits());
17830 eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
17831 assert!(coded > 0, "no compound 128x128 block was coded on this clip");
17832 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17833 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17834 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17835 for (plane, got, want) in [
17836 ("luma", &dec.y, &frame.reconstruction.y),
17837 ("U", &dec.u, &frame.reconstruction.u),
17838 ("V", &dec.v, &frame.reconstruction.v),
17839 ] {
17840 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17841 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17842 }
17843 }
17844 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17845 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17846 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17847 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17848 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17849 }
17850 }
17851
17852 /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
17853 /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
17854 /// square. Three passes over one `testsrc2` clip:
17855 ///
17856 /// * HORZ forced at every root ([`force_b128_rect`]), so every context
17857 /// the 128x64 shape reads is exercised rather than the handful the RD
17858 /// would pick;
17859 /// * VERT forced the same way;
17860 /// * UNFORCED, which is the count the gate rows are read against -- the
17861 /// same clip with the RD free to choose among NONE / HORZ / VERT /
17862 /// four superblocks.
17863 ///
17864 /// Each pass is sample-exact against the encoder's own reconstruction
17865 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17866 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17867 /// before this lane by construction: `write_sb128_root` could only name
17868 /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
17869 ///
17870 /// cargo test -p ec-av1 --release --lib -- --ignored \
17871 /// a_128_root_horz_and_vert --nocapture
17872 #[test]
17873 #[ignore = "sets the process-global superblock size: run it alone"]
17874 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
17875 let _knobs = crate::speed::knob_write();
17876 if !have_ffmpeg() {
17877 eprintln!("SKIP: no ffmpeg");
17878 return;
17879 }
17880 force_sb128(true);
17881 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
17882 std::fs::create_dir_all(&dir).unwrap();
17883 let clip = dir.join("testsrc2-1280x768.y4m");
17884 let ok = Command::new("ffmpeg")
17885 .args(["-v", "error", "-y", "-f", "lavfi"])
17886 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17887 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17888 .arg(&clip)
17889 .status()
17890 .expect("ffmpeg failed to run")
17891 .success();
17892 assert!(ok, "ffmpeg could not write the synthetic clip");
17893 let (width, height) = (1280usize, 768usize);
17894 let pictures =
17895 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17896 let mut unforced = (0usize, 0usize);
17897 for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
17898 force_b128_rect(force);
17899 let _ = take_b128_horz_hits();
17900 let _ = take_b128_vert_hits();
17901 let _ = crate::tile::take_sb128_horz_hits();
17902 let _ = crate::tile::take_sb128_vert_hits();
17903 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17904 let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
17905 let (coded_h, coded_v) = (
17906 crate::tile::take_sb128_horz_hits(),
17907 crate::tile::take_sb128_vert_hits(),
17908 );
17909 eprintln!(
17910 "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
17911 {coded_h} 128x64 + {coded_v} 64x128 halves"
17912 );
17913 match force {
17914 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
17915 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
17916 // The unforced count is REPORTED, not asserted: it is the
17917 // number the gate is read against, and a zero here would be
17918 // an RD result, not a defect (the forced passes already prove
17919 // the writer and the reader agree on the shape).
17920 _ => unforced = (won_h, won_v),
17921 }
17922 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17923 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
17924 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17925 for (plane, got, want) in [
17926 ("luma", &dec.y, &frame.reconstruction.y),
17927 ("U", &dec.u, &frame.reconstruction.u),
17928 ("V", &dec.v, &frame.reconstruction.v),
17929 ] {
17930 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17931 assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
17932 }
17933 }
17934 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17935 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17936 assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
17937 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
17938 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
17939 }
17940 }
17941 force_b128_rect(0);
17942 eprintln!(
17943 "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
17944 unforced.0, unforced.1
17945 );
17946 }
17947
17948 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
17949 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
17950 /// Five passes over the same `testsrc2` clip
17951 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
17952 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
17953 /// context and every visit order the shape reads is exercised rather than
17954 /// the handful the RD would pick, and then an UNFORCED pass whose
17955 /// per-shape count is REPORTED (it is the number the gate rows are read
17956 /// against).
17957 ///
17958 /// Each pass is sample-exact against the encoder's own reconstruction
17959 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17960 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17961 /// before this lane by construction: `write_sb128_root` could only name
17962 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
17963 ///
17964 /// cargo test -p ec-av1 --release --lib -- --ignored \
17965 /// a_128_root_ab_shapes --nocapture
17966 #[test]
17967 #[ignore = "sets the process-global superblock size: run it alone"]
17968 fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
17969 let _knobs = crate::speed::knob_write();
17970 if !have_ffmpeg() {
17971 eprintln!("SKIP: no ffmpeg");
17972 return;
17973 }
17974 force_sb128(true);
17975 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
17976 std::fs::create_dir_all(&dir).unwrap();
17977 let clip = dir.join("testsrc2-1280x768.y4m");
17978 let ok = Command::new("ffmpeg")
17979 .args(["-v", "error", "-y", "-f", "lavfi"])
17980 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17981 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17982 .arg(&clip)
17983 .status()
17984 .expect("ffmpeg failed to run")
17985 .success();
17986 assert!(ok, "ffmpeg could not write the synthetic clip");
17987 let (width, height) = (1280usize, 768usize);
17988 let pictures =
17989 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17990 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
17991 let mut unforced = [0usize; 4];
17992 for force in [4u8, 5, 6, 7, 0] {
17993 force_b128_ab(force);
17994 let label = if force == 0 { "unforced" } else { names[usize::from(force) - 4] };
17995 let _ = take_b128_ab_hits();
17996 let _ = crate::tile::take_sb128_ab_hits();
17997 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17998 let won = take_b128_ab_hits();
17999 let coded = crate::tile::take_sb128_ab_hits();
18000 eprintln!(
18001 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
18002 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
18003 );
18004 if force == 0 {
18005 // The unforced counts are REPORTED, not asserted: a zero here
18006 // would be an RD result, not a defect (the four forced passes
18007 // already prove the writer and the reader agree on the shape).
18008 unforced = won;
18009 } else {
18010 let i = usize::from(force) - 4;
18011 assert!(coded[i] > 0, "no {label} root was coded with {label} forced");
18012 }
18013 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18014 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
18015 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18016 for (plane, got, want) in [
18017 ("luma", &dec.y, &frame.reconstruction.y),
18018 ("U", &dec.u, &frame.reconstruction.u),
18019 ("V", &dec.v, &frame.reconstruction.v),
18020 ] {
18021 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18022 assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
18023 }
18024 }
18025 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18026 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18027 assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
18028 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
18029 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
18030 }
18031 }
18032 force_b128_ab(0);
18033 eprintln!(
18034 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
18035 unforced[0], unforced[1], unforced[2], unforced[3],
18036 );
18037 }
18038
18039 #[test]
18040 #[ignore = "sets the process-global superblock size: run it alone"]
18041 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
18042 let _knobs = crate::speed::knob_write();
18043 if !have_ffmpeg() {
18044 eprintln!("SKIP: no ffmpeg");
18045 return;
18046 }
18047 force_sb128(true);
18048 let dir = std::env::temp_dir().join(format!("ec-av1-sb128b-{}", std::process::id()));
18049 std::fs::create_dir_all(&dir).unwrap();
18050 let clip = dir.join("mandelbrot-1280x768.y4m");
18051 let ok = Command::new("ffmpeg")
18052 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "mandelbrot=size=1280x768:rate=24"])
18053 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
18054 .arg(&clip)
18055 .status()
18056 .expect("ffmpeg failed to run")
18057 .success();
18058 assert!(ok, "ffmpeg could not write the synthetic clip");
18059 let path = clip.to_str().unwrap();
18060 let (width, height) = (1280usize, 768usize);
18061 let pictures = crate::probe::source(path, "0", "null", width, height, 12);
18062
18063 let _ = crate::tile::take_drl_clamp_hits();
18064 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
18065 let clamps = crate::tile::take_drl_clamp_hits();
18066 assert!(
18067 clamps > 0,
18068 "this clip never asked for a drl index the write-time stack could not carry, \
18069 so it cannot witness the defect"
18070 );
18071 eprintln!("clamped drl indices: {clamps}");
18072
18073 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18074 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18075 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18076 let recon = &frame.reconstruction;
18077 for (plane, got, want) in [
18078 ("luma", &dec.y, &recon.y),
18079 ("U", &dec.u, &recon.u),
18080 ("V", &dec.v, &recon.v),
18081 ] {
18082 let differ = got.iter().zip(want).filter(|(a, b)| a != b).count();
18083 assert_eq!(
18084 differ, 0,
18085 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18086 own reconstruction",
18087 got.len()
18088 );
18089 }
18090 }
18091 }
18092
18093 #[test]
18094 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
18095 let _knobs = crate::speed::knob_read();
18096 let fctx = &crate::decode::FrameCtx::for_encoder();
18097 // 256x128, not the 128x64 this started at: once a leaf could search
18098 // its second reference (lane-av1comp4) the small card's every
18099 // eligible block went to a compound winner, which commits its flat
18100 // transform, and the split below stopped firing on content that
18101 // still splits at every larger size ([[gate-blind-to-feature]] --
18102 // the guard is right, the fixture had shrunk under it).
18103 let (width, height) = (256usize, 128usize);
18104 let pictures: Vec<Picture> =
18105 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
18106 let _ = take_inter_tx_split_hits();
18107 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18108 let raw = take_inter_tx_split_hits();
18109 // Summed over the four block classes the census keys on (leaf/32x32 x
18110 // single/compound): this assert is about the split firing at all.
18111 let split = [
18112 raw.iter().step_by(2).sum::<usize>(),
18113 raw.iter().skip(1).step_by(2).sum::<usize>(),
18114 ];
18115 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
18116 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
18117 // content splits -- a green round trip in which the split never fires
18118 // would prove only the flat path.
18119 if tx_select() && tx_select_inter() {
18120 assert!(split[1] > 0, "the inter var-tx split never fired");
18121 }
18122 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18123 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18124 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18125 let recon = &frame.reconstruction;
18126 for (plane, got, want, stride) in [
18127 ("luma", &dec.y, &recon.y, width),
18128 ("U", &dec.u, &recon.u, width / 2),
18129 ("V", &dec.v, &recon.v, width / 2),
18130 ] {
18131 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
18132 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
18133 panic!(
18134 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
18135 reconstruction {} ({} of {} samples differ)",
18136 at % stride,
18137 at / stride,
18138 got[at],
18139 want[at],
18140 got.iter().zip(want).filter(|(a, b)| a != b).count(),
18141 got.len(),
18142 );
18143 }
18144 }
18145 }
18146 }
18147
18148 /// The rate term the mode search ranks every decision by has to be the
18149 /// rate the writer then spends. The search prices a block's coefficients
18150 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
18151 /// against the default CDFs a tile starts from and the contexts of a
18152 /// block whose neighbours coded nothing -- while the tile writer codes
18153 /// them against a state that has been adapting all frame (the
18154 /// price-the-narrowing class). This measures that drift: the sum of what
18155 /// the search paid for the coefficients it kept, against the bytes the
18156 /// writer actually emitted for the whole tile (which also carries the
18157 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
18158 /// expected to be the larger of the two).
18159 #[test]
18160 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
18161 let _knobs = crate::speed::knob_read();
18162 let fctx = &crate::decode::FrameCtx::for_encoder();
18163 let (width, height) = (256usize, 128usize);
18164 let pictures: Vec<Picture> = (0..5)
18165 .map(|i| panned_test_card(width, height, i * 2))
18166 .collect();
18167 let _ = take_predicted_bits();
18168 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18169 let predicted = take_predicted_bits();
18170 assert_eq!(predicted.len(), encoded.frames.len());
18171
18172 eprintln!("frame predicted bits written bits drift");
18173 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
18174 // defect this gate exists to catch), a positive one is the written
18175 // side carrying syntax the coefficient sum leaves out -- and since
18176 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
18177 // on that side, so the two directions no longer share a bound.
18178 let mut worst_over: f64 = 0.0;
18179 let mut worst_under: f64 = 0.0;
18180 // The census is per CODED frame, so it is zipped in coding order --
18181 // which is not display order under a pyramid.
18182 let coded: Vec<&Encoded> =
18183 encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect();
18184 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
18185 let written = frame.tile.len() as f64 * 8.0;
18186 let drift = (written - bits) / written;
18187 worst_over = worst_over.max(-drift);
18188 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
18189 // all (150-250 bits of tile, nearly all of it partition/mode/mv
18190 // syntax the coefficient sum never counts), so its ratio measures
18191 // that floor rather than any drift. Frames under 512 written bits
18192 // are left out of the under-price bound for that reason; the
18193 // over-price bound -- the defect direction, where the search pays
18194 // MORE than the writer -- still covers every frame.
18195 if written >= 512.0 {
18196 worst_under = worst_under.max(drift);
18197 }
18198 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
18199 }
18200 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
18201 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
18202 // over-prices every frame but the last (its sum EXCLUDES the
18203 // partition/mode/skip/mv syntax the written side carries, so the true
18204 // coefficient over-price is larger still): the writer's CDFs adapt to
18205 // the content while the search's stay at the defaults. The bound is
18206 // set just above the worst measured point -- a widening drift is the
18207 // thing this gate exists to catch.
18208 assert!(
18209 worst_over <= 0.16,
18210 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
18211 worst_over * 100.0
18212 );
18213 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
18214 // the worst inter frame, where nearly every block now codes an MV
18215 // residual and a reference the coefficient sum never counts. Re-measured
18216 // at +29.6% once the encoder's grid published compound blocks properly
18217 // (compound share 8.8% -> 11.5%): a compound block carries a second
18218 // reference tree, a compound mode symbol and -- for the half-new modes
18219 // -- an MV residual, none of which the coefficient sum counts.
18220 // lane-av1txbits: pricing against the tables the frame's writer really
18221 // starts from collapses the over-price above to nothing, so the whole
18222 // remaining gap is the syntax the coefficient sum leaves out. That is
18223 // the default on a non-screen frame since lane-av1price2 (this
18224 // fixture is one), and it reads +32.6% here.
18225 // lane-av1obmc: every eligible single-reference inter block now also
18226 // carries a `motion_mode` symbol the coefficient sum never counts,
18227 // and an OBMC block carries the more expensive of the two values --
18228 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
18229 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
18230 // decisions, so this bound and the byte pins above FAIL BY DESIGN
18231 // under it; the default path (no motion_mode syntax at all) is the
18232 // one they are measured on.
18233 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
18234 // coding pyramid now, so the five frames are a key frame, a hidden
18235 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
18236 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
18237 // near-empty leaves below it. Both bounds stand where they were.
18238 // lane-av1rejudge: local warp is ON by default now, so every eligible
18239 // single-reference block carries that same `motion_mode` symbol (a
18240 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
18241 // +34.9% here, one point past the OBMC reading above. The bound moves
18242 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
18243 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
18244 // symbol and one or two magnitude symbols, none of which the
18245 // coefficient sum counts either -- +36.9% here against the same
18246 // fixture's +34.9% with `EC_AV1_CFL=0`.
18247 // ... and a directional block whose `angle_delta_y` is no longer
18248 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
18249 assert!(
18250 worst_under <= 0.40,
18251 "the writer spent {:.2}% more than the search priced -- more than \
18252 the mode/mv syntax outside the coefficient sum explains",
18253 worst_under * 100.0
18254 );
18255 }
18256
18257 /// The census behind step (1) of the pricer lane: for every transform
18258 /// block the writer really codes, what the search priced those levels at
18259 /// against what the writer spent on them, split by table set and non-zero
18260 /// count. One average hides the interesting part -- the classes the
18261 /// estimate is systematically wrong about (all-zero blocks, the
18262 /// one-coefficient blocks the inter search lives on) -- so the split is
18263 /// printed and only the total is asserted on.
18264 #[test]
18265 fn pricer_error_census_by_block_class() {
18266 let _knobs = crate::speed::knob_read();
18267 let fctx = &crate::decode::FrameCtx::for_encoder();
18268 let (width, height) = (256usize, 128usize);
18269 let pictures: Vec<Picture> = (0..5)
18270 .map(|i| panned_test_card(width, height, i * 2))
18271 .collect();
18272 crate::tile::pricer_census_on();
18273 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18274 let rows = crate::tile::take_pricer_census();
18275 assert!(!rows.is_empty(), "the census saw no transform block");
18276
18277 println!("| set | nz | blocks | priced bits | written bits | error |");
18278 println!("|---|---|---|---|---|---|");
18279 let (mut priced_all, mut written_all) = (0.0, 0.0);
18280 for ((set, bucket), (blocks, priced, written)) in &rows {
18281 priced_all += priced;
18282 written_all += written;
18283 println!(
18284 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
18285 crate::tile::census_bucket_label(*bucket),
18286 if *written > 0.0 {
18287 (priced - written) / written * 100.0
18288 } else {
18289 0.0
18290 }
18291 );
18292 }
18293 println!(
18294 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
18295 rows.values().map(|r| r.0).sum::<u64>(),
18296 (priced_all - written_all) / written_all * 100.0
18297 );
18298 assert!(written_all > 0.0);
18299 }
18300
18301 /// Step (2) of the pricer lane: the same census, but on the REAL clips
18302 /// the BD gate scores -- one film clip and the screen capture -- so the
18303 /// question the film/screen split raises can be answered from data. Real
18304 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
18305 /// the screen capture larger, and the census says why: on a screen
18306 /// capture the frame's own starting tables are the tables of a frame that
18307 /// coded PALETTE and long runs of zero blocks, so they are far from the
18308 /// tables the writer ends the frame with; the pricer error does not fall
18309 /// the way it does on film.
18310 ///
18311 /// Not a gate -- it prints. Run it once per mode:
18312 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
18313 /// --ignored pricer_error_census_on_clips --nocapture
18314 #[test]
18315 #[ignore = "reads the real library, needs ffmpeg"]
18316 fn pricer_error_census_on_clips() {
18317 let _knobs = crate::speed::knob_write();
18318 if !have_ffmpeg() {
18319 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
18320 return;
18321 }
18322 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
18323 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
18324 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
18325 if film.exists() {
18326 clips.push(("film 1080p".to_string(), film));
18327 }
18328 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
18329 && let Some(p) = manifest
18330 .lines()
18331 .skip(1)
18332 .filter_map(|l| l.split('\t').next())
18333 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
18334 {
18335 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
18336 }
18337 assert!(!clips.is_empty(), "no source clip available");
18338 let (width, height, frames) = (640usize, 384usize, 6usize);
18339 for (name, path) in &clips {
18340 let fctx = &crate::decode::FrameCtx::for_encoder();
18341 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
18342 SCREEN_FRAMES.iter().for_each(|c| {
18343 c.store(0, std::sync::atomic::Ordering::Relaxed);
18344 });
18345 let _ = crate::tile::take_pricing_hits();
18346 crate::tile::pricer_census_on();
18347 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18348 let rows = crate::tile::take_pricer_census();
18349 let (price_default, price_real) = crate::tile::take_pricing_hits();
18350 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
18351 println!(
18352 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
18353 {screen_on}, pricer armings default={price_default} real={price_real}"
18354 );
18355 println!("| set | nz | blocks | priced bits | written bits | error |");
18356 println!("|---|---|---|---|---|---|");
18357 let (mut priced_all, mut written_all) = (0.0, 0.0);
18358 for ((set, bucket), (blocks, priced, written)) in &rows {
18359 priced_all += priced;
18360 written_all += written;
18361 println!(
18362 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
18363 crate::tile::census_bucket_label(*bucket),
18364 if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
18365 );
18366 }
18367 println!(
18368 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
18369 rows.values().map(|r| r.0).sum::<u64>(),
18370 (priced_all - written_all) / written_all * 100.0
18371 );
18372 assert!(written_all > 0.0, "{name}: the census saw no transform block");
18373 }
18374 }
18375
18376 /// Low motion has to actually buy something: at least one inter frame of
18377 /// a panning sequence has to cost fewer bytes than the key frame that
18378 /// starts it, and the inter-block share it prints has to be non-zero --
18379 /// a search that never picks an inter mode would still pass a rate gate
18380 /// on a picture with no motion in it (the class this repo calls
18381 /// gate-blind-to-feature), so the share is printed even though it is not
18382 /// asserted on beyond being reachable at all.
18383 #[test]
18384 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
18385 let _knobs = crate::speed::knob_read();
18386 let fctx = &crate::decode::FrameCtx::for_encoder();
18387 let (width, height) = (256usize, 128usize);
18388 let pictures: Vec<Picture> = (0..5)
18389 .map(|i| panned_test_card(width, height, i * 2))
18390 .collect();
18391 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18392
18393 let key_bytes = encoded.frames[0].stream.len();
18394 eprintln!("frame bytes inter share");
18395 for (i, frame) in encoded.frames.iter().enumerate() {
18396 eprintln!(
18397 "{i:5} {:5} {:11.2}",
18398 frame.stream.len(),
18399 frame.inter_block_share
18400 );
18401 }
18402 assert!(
18403 encoded.frames[1..]
18404 .iter()
18405 .any(|f| f.stream.len() < key_bytes),
18406 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
18407 );
18408 assert!(
18409 encoded.frames[1..]
18410 .iter()
18411 .any(|f| f.inter_block_share > 0.0),
18412 "no inter frame coded a single inter block -- the search never fired"
18413 );
18414 }
18415
18416 /// A manual perf probe, not a gate: prints where a key frame's and an
18417 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
18418 /// measures before it optimizes rather than guessing. Run with
18419 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
18420 #[test]
18421 #[ignore = "a perf probe, not a gate"]
18422 fn stage_timing_breakdown() {
18423 let _knobs = crate::speed::knob_read();
18424 let fctx = &crate::decode::FrameCtx::for_encoder();
18425 use std::time::Instant;
18426
18427 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
18428 let picture = test_card(width, height);
18429
18430 let t = Instant::now();
18431 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
18432 let dc_only_t = t.elapsed();
18433
18434 let t = Instant::now();
18435 let non_directional =
18436 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
18437 let non_directional_t = t.elapsed();
18438
18439 let t = Instant::now();
18440 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18441 let all_modes_t = t.elapsed();
18442
18443 eprintln!(
18444 "\n=== key frame {width}x{height} ===\n\
18445 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
18446 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
18447 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
18448 dc_only.stream.len(),
18449 non_directional.stream.len(),
18450 all_modes.stream.len(),
18451 );
18452
18453 // One inter frame predicting off the key frame's own
18454 // reconstruction, the (256, 256)-padded surface encode_sequence
18455 // itself would hand encode_inter_frame.
18456 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
18457 let padded_pic = picture.padded_to(SUPERBLOCK);
18458 let t = Instant::now();
18459 let inter =
18460 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();
18461 let inter_t = t.elapsed();
18462 eprintln!(
18463 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
18464 {:.2})",
18465 inter.stream.len(),
18466 inter.inter_block_share
18467 );
18468 }
18469
18470 // Isolated per-call cost of the trial pipeline's own stages, at both
18471 // transform sizes the search runs, averaged over enough calls to
18472 // rise above `Instant::now`'s own noise.
18473 for side in [16usize, 32] {
18474 const N: u32 = 20_000;
18475 let residual: Vec<i32> = (0..side * side)
18476 .map(|i| ((i * 37 % 61) as i32) - 30)
18477 .collect();
18478
18479 let t = Instant::now();
18480 let mut levels = Vec::new();
18481 for _ in 0..N {
18482 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
18483 }
18484 let forward_t = t.elapsed() / N;
18485
18486 let t = Instant::now();
18487 for _ in 0..N {
18488 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
18489 }
18490 let inverse_t = t.elapsed() / N;
18491
18492 let set = if side == 32 {
18493 crate::cdf_state::TxbSet::Luma32
18494 } else {
18495 crate::cdf_state::TxbSet::Luma16
18496 };
18497 let t = Instant::now();
18498 for _ in 0..N {
18499 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
18500 }
18501 let entropy_t = t.elapsed() / N;
18502
18503 let above = vec![128u8; side * 2];
18504 let left = vec![128u8; side * 2];
18505 let mut prediction = vec![0u8; side * side];
18506 let t = Instant::now();
18507 for _ in 0..N {
18508 intra_predict_u8(
18509 D45_PRED,
18510 0,
18511 Some(&above),
18512 Some(&left),
18513 Some(128),
18514 side,
18515 side,
18516 false,
18517 false,
18518 &mut prediction, fctx,
18519 );
18520 }
18521 let predict_t = t.elapsed() / N;
18522
18523 eprintln!(
18524 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
18525 predict (1 directional mode): {predict_t:>9.2?}\n\
18526 forward_and_quantize: {forward_t:>9.2?}\n\
18527 dequant_and_inverse: {inverse_t:>9.2?}\n\
18528 coeff_bits: {entropy_t:>9.2?}"
18529 );
18530 }
18531 }
18532
18533 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
18534 /// (motion search, [`crate::mc::predict`], transform+quantize,
18535 /// `coeff_bits`), plus what is left over once those are subtracted --
18536 /// the thirteen-mode intra-candidate loop `search_inter_block` still
18537 /// runs on every inter block (its own transform/quant/entropy calls are
18538 /// already inside buckets 2/3, so "left over" here is everything NOT
18539 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
18540 /// symbol-cost lookups outside `coeff_bits`).
18541 ///
18542 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
18543 #[test]
18544 #[ignore = "a perf probe, not a gate"]
18545 fn stage_timing_breakdown_inter() {
18546 let _knobs = crate::speed::knob_read();
18547 let fctx = &crate::decode::FrameCtx::for_encoder();
18548 use std::time::Instant;
18549
18550 let (width, height) = (1280usize, 720);
18551 let picture = test_card(width, height);
18552 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18553 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
18554 let padded_pic = picture.padded_to(SUPERBLOCK);
18555
18556 stage_reset();
18557 let t = Instant::now();
18558 let inter =
18559 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();
18560 let total_t = t.elapsed();
18561 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
18562 let accounted = motion_search + transform_quant + entropy;
18563 // motion_search already contains interpolation's own time (every
18564 // candidate the search costs calls crate::mc::predict), so it is not
18565 // added again here -- interpolation is reported alongside as "of
18566 // which interpolation", not as a fifth additive bucket.
18567 let other = total_t.saturating_sub(accounted);
18568
18569 eprintln!(
18570 "\n=== inter frame {width}x{height}, one frame ===\n\
18571 total: {total_t:>9.2?} ({} bytes)\n\
18572 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
18573 {interpolation:>9.2?})\n\
18574 transform + quantize: {transform_quant:>9.2?}\n\
18575 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
18576 everything else (13-mode intra {other:>9.2?}\n\
18577 candidate loop's own predict/bookkeeping, NEARESTMV's own \
18578 predict, RD glue):",
18579 inter.stream.len(),
18580 );
18581 }
18582
18583 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
18584 /// frames (a dark/flat one, a detailed one, a normal film one) at two
18585 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
18586 /// None`, the baseline this same build produces without
18587 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
18588 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
18589 /// go in the lane report, which is where "ship as default" is decided --
18590 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
18591 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
18592 #[test]
18593 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
18594 fn prune_k_quality_sweep() {
18595 let _knobs = crate::speed::knob_read();
18596 let fctx = &crate::decode::FrameCtx::for_encoder();
18597 if !have_ffmpeg() {
18598 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
18599 return;
18600 }
18601 let (width, height) = (640usize, 352usize);
18602 let frames: &[(&str, &str, &str)] = &[
18603 // (label, clip, seek) -- a near-black scene, a busy one, and an
18604 // ordinary film frame, each from a different real file.
18605 (
18606 "dark/flat",
18607 "/home/user/Videos/reela.mp4",
18608 "3",
18609 ),
18610 (
18611 "detailed",
18612 "/home/user/Downloads/reelb.mkv",
18613 "1200",
18614 ),
18615 (
18616 "film",
18617 "/home/user/Videos/Films/reelc.mkv",
18618 "600",
18619 ),
18620 ];
18621 for &(label, clip, skip) in frames {
18622 if !std::path::Path::new(clip).exists() {
18623 eprintln!("SKIP {label}: {clip} not present on this machine");
18624 continue;
18625 }
18626 let picture = clip_frame(clip, skip, width, height);
18627 for &q in &[60u8, 150] {
18628 // SAFETY (not literally unsafe, just process-global): this is
18629 // a single-threaded #[ignore] probe, run by hand, never
18630 // alongside other tests that read Search::top_k.
18631 set_test_top_k_override(None);
18632 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18633 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
18634 eprint!(
18635 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
18636 baseline.stream.len(),
18637 baseline_psnr
18638 );
18639 for &k in &[3usize, 4, 6] {
18640 set_test_top_k_override(Some(k));
18641 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18642 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
18643 eprint!(
18644 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
18645 pruned.stream.len(),
18646 pruned_psnr,
18647 pruned_psnr - baseline_psnr
18648 );
18649 }
18650 eprintln!();
18651 }
18652 }
18653 set_test_top_k_override(None);
18654 }
18655
18656 /// Two consecutive decoded frames from one clip, for an inter-frame
18657 /// sweep -- [`clip_frame`] alone only ever gives one.
18658 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
18659 let out = Command::new("ffmpeg")
18660 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
18661 .args(["-vf", &format!("scale={width}:{height}")])
18662 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
18663 .output()
18664 .expect("ffmpeg failed to run");
18665 assert!(
18666 out.status.success(),
18667 "ffmpeg: {}",
18668 String::from_utf8_lossy(&out.stderr)
18669 );
18670 let (luma, chroma) = (width * height, width * height / 4);
18671 let frame_len = luma + 2 * chroma;
18672 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
18673 std::array::from_fn(|i| {
18674 let bytes = &out.stdout[i * frame_len..][..frame_len];
18675 Picture {
18676 width,
18677 height,
18678 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
18679 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
18680 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
18681 }
18682 })
18683 }
18684
18685 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
18686 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
18687 /// then one inter frame off it (`search_inter_block`'s own intra
18688 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
18689 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
18690 /// padding step complicates the comparison. Prints bytes and luma PSNR
18691 /// for the inter frame alone, unpruned vs each `K`.
18692 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
18693 #[test]
18694 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
18695 fn prune_k_quality_sweep_inter() {
18696 let _knobs = crate::speed::knob_read();
18697 let fctx = &crate::decode::FrameCtx::for_encoder();
18698 if !have_ffmpeg() {
18699 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
18700 return;
18701 }
18702 let (width, height) = (1280usize, 704usize);
18703 let frames: &[(&str, &str, &str)] = &[
18704 (
18705 "dark/flat",
18706 "/home/user/Videos/reela.mp4",
18707 "3",
18708 ),
18709 (
18710 "detailed",
18711 "/home/user/Downloads/reelb.mkv",
18712 "1200",
18713 ),
18714 (
18715 "film",
18716 "/home/user/Videos/Films/reelc.mkv",
18717 "600",
18718 ),
18719 ];
18720 for &(label, clip, skip) in frames {
18721 if !std::path::Path::new(clip).exists() {
18722 eprintln!("SKIP {label}: {clip} not present on this machine");
18723 continue;
18724 }
18725 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
18726 for &q in &[60u8, 150] {
18727 // SAFETY (not literally unsafe, just process-global): a
18728 // single-threaded #[ignore] probe, run by hand, never
18729 // alongside other tests that read Search::top_k.
18730 set_test_top_k_override_inter(None);
18731 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
18732 let baseline = encode_inter_frame(
18733 &inter_source,
18734 &key.reconstruction,
18735 q,
18736 0.5,
18737 1,
18738 flat_order_hints(1, 0, false),
18739 (width, height), None, None, None, None, fctx, None, &[],
18740 )
18741 .unwrap();
18742 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
18743 eprint!(
18744 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
18745 baseline.stream.len(),
18746 baseline_psnr
18747 );
18748 for &k in &[3usize, 4, 6] {
18749 set_test_top_k_override_inter(Some(k));
18750 let pruned = encode_inter_frame(
18751 &inter_source,
18752 &key.reconstruction,
18753 q,
18754 0.5,
18755 1,
18756 flat_order_hints(1, 0, false),
18757 (width, height), None, None, None, None, fctx, None, &[],
18758 )
18759 .unwrap();
18760 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
18761 eprint!(
18762 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
18763 pruned.stream.len(),
18764 pruned_psnr,
18765 pruned_psnr - baseline_psnr
18766 );
18767 }
18768 eprintln!();
18769 }
18770 }
18771 set_test_top_k_override_inter(None);
18772 }
18773
18774 /// `frames` consecutive pictures out of a real clip, scaled to a whole
18775 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
18776 /// to an arbitrary count for the fixture regression gate below.
18777 fn clip_frames(
18778 clip: &str,
18779 skip: &str,
18780 width: usize,
18781 height: usize,
18782 frames: usize,
18783 ) -> Vec<Picture> {
18784 clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames)
18785 }
18786
18787 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
18788 /// for a native-resolution CROP instead of a downscale (the downscale is
18789 /// what destroys a screen capture's exact repeats -- class
18790 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
18791 fn clip_frames_vf(
18792 clip: &str,
18793 skip: &str,
18794 vf: &str,
18795 width: usize,
18796 height: usize,
18797 frames: usize,
18798 ) -> Vec<Picture> {
18799 // ONE definition of the gate's loader recipe, shared with
18800 // `examples/enc_probe` so the instrument cannot arm a different source
18801 // than the gate it reports on (class `instrument disagrees with the
18802 // gate`; lane-probe).
18803 crate::probe::source(clip, skip, vf, width, height, frames)
18804 }
18805
18806 /// The standing regression gate on real content: 12 frames of a real
18807 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
18808 /// this crate's own input regardless of its own source codec), encoded
18809 /// as an AV1 GOP and checked against three numeric floors so a
18810 /// compatibility or quality regression fails the suite instead of
18811 /// waiting for a downstream repo's gate to catch it (as happened for a
18812 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
18813 /// refusal, both caught only that way).
18814 ///
18815 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
18816 /// that geometry is already covered elsewhere), chosen only so encode
18817 /// time and gate numbers are not muddied by an edge-block class this
18818 /// test is not about.
18819 ///
18820 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
18821 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
18822 /// below carry a margin off those measured numbers (PSNR floor =
18823 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
18824 #[test]
18825 fn real_clip_encodes_within_its_quality_and_size_budget() {
18826 let _knobs = crate::speed::knob_read();
18827 let fctx = &crate::decode::FrameCtx::for_encoder();
18828 if !have_ffmpeg() {
18829 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
18830 return;
18831 }
18832 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18833 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
18834 if !clip.exists() {
18835 eprintln!(
18836 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
18837 clip.display()
18838 );
18839 return;
18840 }
18841 let (width, height, frame_count) = (640usize, 384usize, 12usize);
18842 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
18843 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18844 assert_eq!(encoded.frames.len(), frame_count);
18845
18846 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
18847 // stream and hands back every frame -- a stream a downstream
18848 // decoder refuses is the exact class of regression this gate
18849 // exists for.
18850 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
18851 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
18852
18853 // Gate 2: quality vs the source did not silently collapse.
18854 let mean_psnr: f64 = decoded
18855 .iter()
18856 .zip(&source)
18857 .map(|(d, s)| psnr(&d.y, &s.y))
18858 .sum::<f64>()
18859 / frame_count as f64;
18860 assert!(
18861 mean_psnr >= 44.91,
18862 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
18863 );
18864
18865 // Gate 3: the stream did not silently bloat.
18866 assert!(
18867 encoded.stream.len() <= 80_340,
18868 "stream grew to {} bytes, over the 80340-byte ceiling",
18869 encoded.stream.len()
18870 );
18871 }
18872
18873 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
18874 /// straddle size: 640x384 is exact on both axes (32-aligned), so
18875 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
18876 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
18877 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
18878 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
18879 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
18880 /// card; this one is the real-clip gate, same three floors.
18881 ///
18882 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
18883 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
18884 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
18885 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
18886 #[test]
18887 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
18888 let _knobs = crate::speed::knob_read();
18889 let fctx = &crate::decode::FrameCtx::for_encoder();
18890 if !have_ffmpeg() {
18891 eprintln!(
18892 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
18893 no ffmpeg"
18894 );
18895 return;
18896 }
18897 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18898 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
18899 if !clip.exists() {
18900 eprintln!(
18901 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
18902 {} missing",
18903 clip.display()
18904 );
18905 return;
18906 }
18907 let (width, height, frame_count) = (704usize, 400usize, 8usize);
18908 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
18909 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18910 assert_eq!(encoded.frames.len(), frame_count);
18911
18912 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
18913 // stream and hands back every frame.
18914 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
18915 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
18916
18917 // Gate 2: quality vs the source did not silently collapse.
18918 let mean_psnr: f64 = decoded
18919 .iter()
18920 .zip(&source)
18921 .map(|(d, s)| psnr(&d.y, &s.y))
18922 .sum::<f64>()
18923 / frame_count as f64;
18924 assert!(
18925 mean_psnr >= 44.98,
18926 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
18927 );
18928
18929 // Gate 3: the stream did not silently bloat.
18930 assert!(
18931 encoded.stream.len() <= 62_703,
18932 "stream grew to {} bytes, over the 62703-byte ceiling",
18933 encoded.stream.len()
18934 );
18935 }
18936
18937 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
18938 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
18939 /// facade -- timed end to end, so the edith export-time projection is a
18940 /// real number rather than a guess from the isolated key/inter numbers
18941 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
18942 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
18943 #[test]
18944 #[ignore = "a perf probe, not a gate"]
18945 fn sequence_bench_sanity() {
18946 let _knobs = crate::speed::knob_read();
18947 let fctx = &crate::decode::FrameCtx::for_encoder();
18948 use std::time::Instant;
18949 let (width, height) = (1280usize, 720usize);
18950 let pictures: Vec<Picture> = (0..24)
18951 .map(|i| panned_test_card(width, height, i * 3))
18952 .collect();
18953 let t = Instant::now();
18954 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18955 let elapsed = t.elapsed();
18956 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
18957 eprintln!(
18958 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
18959 elapsed / 24
18960 );
18961 }
18962
18963 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
18964 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
18965 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
18966 /// -- --ignored --nocapture`.
18967 #[test]
18968 #[ignore = "a calibration probe, not a gate"]
18969 fn calibration_sweep_base_q_idx() {
18970 let _knobs = crate::speed::knob_read();
18971 let fctx = &crate::decode::FrameCtx::for_encoder();
18972 if !have_ffmpeg() {
18973 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
18974 return;
18975 }
18976 let (width, height, frames) = (640usize, 384usize, 12usize);
18977 for clip in [
18978 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
18979 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
18980 ] {
18981 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18982 .join("../../fixtures/video")
18983 .join(clip);
18984 if !path.exists() {
18985 eprintln!("SKIP {clip}: fixture missing");
18986 continue;
18987 }
18988 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
18989 eprintln!("--- {clip} ---");
18990 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
18991 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
18992 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
18993 let mean_psnr: f64 = decoded
18994 .iter()
18995 .zip(&source)
18996 .map(|(d, s)| psnr(&d.y, &s.y))
18997 .sum::<f64>()
18998 / frames as f64;
18999 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
19000 eprintln!(
19001 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
19002 encoded.stream.len()
19003 );
19004 }
19005 }
19006 }
19007
19008 // -----------------------------------------------------------------------
19009 // The encoder's standing BD-rate baseline against libaom and rav1e.
19010 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
19011 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
19012 // agreeing with our encoder proves nothing about the bitstream.
19013 // -----------------------------------------------------------------------
19014
19015 /// All-plane PSNR of a decoded picture against its source, on the same
19016 /// 8-bit scale [`psnr`] uses.
19017 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
19018 let cat = |p: &Picture| {
19019 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
19020 v.extend_from_slice(&p.y);
19021 v.extend_from_slice(&p.u);
19022 v.extend_from_slice(&p.v);
19023 v
19024 };
19025 psnr(&cat(decoded), &cat(source))
19026 }
19027
19028 /// The pictures back as the planar 8-bit bytes an encoder reads.
19029 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
19030 let mut raw = Vec::new();
19031 for p in source {
19032 for plane in [&p.y, &p.u, &p.v] {
19033 raw.extend(plane.iter().map(|&s| s as u8));
19034 }
19035 }
19036 raw
19037 }
19038
19039 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
19040 /// through ffmpeg: one point per entry of `points`, each a quality flag
19041 /// set. Returns the ladder ordered by fidelity and the total encode wall
19042 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
19043 /// so both curves are measured by the same decoder.
19044 fn external_ladder(
19045 source: &[Picture],
19046 width: usize,
19047 height: usize,
19048 encoder: &str,
19049 points: &[Vec<String>],
19050 ) -> (Vec<(f64, f64)>, f64) {
19051 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
19052 let dir = std::env::temp_dir();
19053 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
19054 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
19055 let mut ladder = Vec::new();
19056 let mut wall = 0.0;
19057 for (i, params) in points.iter().enumerate() {
19058 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
19059 let start = std::time::Instant::now();
19060 let out = Command::new("ffmpeg")
19061 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
19062 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
19063 .arg(&raw_path)
19064 .args(["-an", "-threads", "1"])
19065 .args(["-g", &source.len().to_string(), "-c:v", encoder])
19066 .args(params)
19067 .args(["-f", "obu"])
19068 .arg(&obu)
19069 .output()
19070 .expect("ffmpeg failed to run");
19071 wall += start.elapsed().as_secs_f64();
19072 assert!(
19073 out.status.success(),
19074 "{encoder} {params:?}: {}",
19075 String::from_utf8_lossy(&out.stderr)
19076 );
19077 let stream = std::fs::read(&obu).expect("reference stream");
19078 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
19079 // lane-dkey: every reference point must also decode through OUR
19080 // decoder, sample-exact against ffmpeg's decode of the same bytes.
19081 // A BD table computed off streams we cannot read is a table about
19082 // an encoder we cannot check; this is the assertion that would
19083 // have caught the `force_integer_mv` defect (its stream decoded to
19084 // 25 dB garbage while this gate stayed green) and the crf-5 key
19085 // frame desync. A failure names the encoder, the point's flags and
19086 // the first differing frame/plane/sample.
19087 // lane-dpm1: a failing reference point is COLLECTED, not panicked
19088 // on, so one run still prints the whole BD table and names every
19089 // bad point instead of stopping at the first. The collection is
19090 // asserted empty by [`assert_ladder_decodes`] at the end of each
19091 // gate.
19092 match crate::stream::decode_stream(&stream) {
19093 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
19094 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
19095 ours.len(),
19096 decoded.len(),
19097 )),
19098 Ok(ours) => {
19099 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
19100 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
19101 note_ladder_failure(format!(
19102 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
19103 decoder decoded {got}, ffmpeg {want}"
19104 ));
19105 break;
19106 }
19107 }
19108 }
19109 Err(e) => note_ladder_failure(format!(
19110 "{encoder} {params:?}: our decoder refused the stream ({e})"
19111 )),
19112 }
19113 let mean: f64 = decoded
19114 .iter()
19115 .zip(source)
19116 .map(|(d, s)| psnr_all(d, s))
19117 .sum::<f64>()
19118 / source.len() as f64;
19119 ladder.push((mean, (stream.len() as f64).log10()));
19120 let _ = std::fs::remove_file(&obu);
19121 }
19122 let _ = std::fs::remove_file(&raw_path);
19123 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19124 (ladder, wall)
19125 }
19126
19127 /// Every reference ladder point that did not decode sample-exactly
19128 /// through our own decoder, collected across a whole gate run so the BD
19129 /// table still prints and EVERY bad point is named
19130 /// (`encoder params frame plane sample`) instead of only the first.
19131 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
19132
19133 fn note_ladder_failure(msg: String) {
19134 eprintln!("LADDER DECODE FAILURE: {msg}");
19135 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
19136 }
19137
19138 /// Fail the gate at its END on everything [`external_ladder`] collected.
19139 fn assert_ladder_decodes() {
19140 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
19141 assert!(
19142 failures.is_empty(),
19143 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
19144 failures.len(),
19145 failures.join("\n"),
19146 );
19147 }
19148
19149 /// First differing sample between two pictures, as
19150 /// `(plane, index, left, right)` -- so a gate failure names the plane and
19151 /// the sample instead of just "differs". A length difference counts as a
19152 /// mismatch of that plane at the first index past the shorter one.
19153 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
19154 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
19155 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
19156 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
19157 }
19158 if l.len() != r.len() {
19159 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
19160 }
19161 }
19162 None
19163 }
19164
19165 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
19166 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
19167 /// stream is decoded twice -- by ffmpeg and by our own
19168 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
19169 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
19170 /// in Y, U and V over every shown frame in display order. That is itself
19171 /// a gate: it proves the bitstream says what the encoder thinks, in the
19172 /// only two decoders that read it.
19173 fn our_ladder(
19174 name: &str,
19175 source: &[Picture],
19176 width: usize,
19177 height: usize,
19178 fctx: &crate::decode::FrameCtx,
19179 ) -> (Vec<(f64, f64)>, f64) {
19180 let mut ladder = Vec::new();
19181 let mut wall = 0.0;
19182 for &q in &[150u8, 120, 90, 60] {
19183 let start = std::time::Instant::now();
19184 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
19185 // the gate has to be able to re-sweep it. 0.5 is the shipped one
19186 // (`crate::encoder::DEADZONE`).
19187 let deadzone = std::env::var("EC_AV1_DEADZONE")
19188 .ok()
19189 .and_then(|v| v.parse().ok())
19190 .unwrap_or(0.5);
19191 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
19192 wall += start.elapsed().as_secs_f64();
19193 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
19194 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19195 assert_eq!(
19196 ours.len(),
19197 source.len(),
19198 "{name} q={q}: our decoder's display-order frame count"
19199 );
19200 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
19201 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
19202 panic!(
19203 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
19204 {got}, the encoder reconstructed {want}"
19205 );
19206 }
19207 }
19208 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
19209 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
19210 panic!(
19211 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
19212 {got}, the encoder reconstructed {want}"
19213 );
19214 }
19215 }
19216 let per_frame: Vec<f64> = decoded.iter().zip(source).map(|(d, s)| psnr_all(d, s)).collect();
19217 // lane-txrd: does a tool's loss start at the FIRST inter frame
19218 // (a local mispricing) or grow down the GOP (propagation into
19219 // the reference chain)? One line per q point answers it.
19220 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
19221 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
19222 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
19223 // lane-txrd: per PLANE, because an all-plane mean hides a
19224 // collapse in one of them (class `metric blind to a plane`).
19225 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
19226 let v: Vec<String> = decoded
19227 .iter()
19228 .zip(source)
19229 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
19230 .collect();
19231 v.join(" ")
19232 };
19233 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
19234 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
19235 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
19236 }
19237 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
19238 ladder.push((mean, (encoded.stream.len() as f64).log10()));
19239 }
19240 // What this clip asked for and what the content gate left it coding
19241 // under: a screen clip requests a pyramid and codes flat, and that
19242 // difference is what keeps its row identical to the flat baseline
19243 // (class `gate-blind-to-feature`).
19244 eprintln!(
19245 "{name}: sequence, pyramid requested {:?} effective {:?}",
19246 crate::encoder::Pyramid::from_env(),
19247 last_sequence_pyramid(),
19248 );
19249 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19250 (ladder, wall)
19251 }
19252
19253 /// [`our_ladder`] through the streaming facade — the surface the editor's
19254 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
19255 /// each stream is also reordered (hidden `ALTREF` first,
19256 /// `show_existing_frame` last per group) and each level is coded at its
19257 /// own quantizer offset; without one it is the flat ladder, which
19258 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
19259 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
19260 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
19261 /// the whole ladder how many frames and how many bytes it spent, and the
19262 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
19263 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
19264 /// flat path, so a requested pyramid can come back `None` here.
19265 fn our_ladder_facade(
19266 name: &str,
19267 source: &[Picture],
19268 width: usize,
19269 height: usize,
19270 pyramid: Option<crate::encoder::Pyramid>,
19271 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) {
19272 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
19273 let slot = |l: Level| match l {
19274 Level::Key => 0,
19275 Level::Arf => 1,
19276 Level::Leaf => 2,
19277 Level::ShowExisting => 3,
19278 };
19279 let mut ladder = Vec::new();
19280 let mut wall = 0.0;
19281 let mut effective = None;
19282 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
19283 for &q in &[150u8, 120, 90, 60] {
19284 let config = EncoderConfig {
19285 width,
19286 height,
19287 base_q_idx: q,
19288 gop: source.len(),
19289 colour: Colour::Unspecified,
19290 tile_cols_log2: 0,
19291 tile_rows_log2: 0,
19292 };
19293 let start = std::time::Instant::now();
19294 let mut enc = match pyramid {
19295 None => Av1Encoder::new(config).unwrap(),
19296 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
19297 };
19298 let mut packets = Vec::new();
19299 for picture in source {
19300 packets.extend(enc.encode_frames(picture).unwrap());
19301 }
19302 packets.extend(enc.flush().unwrap());
19303 wall += start.elapsed().as_secs_f64();
19304 effective = enc.pyramid();
19305 let mut stream = Vec::new();
19306 for p in &packets {
19307 counts[slot(p.level)] += 1;
19308 bytes[slot(p.level)] += p.data.len();
19309 stream.extend_from_slice(&p.data);
19310 }
19311 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
19312 // correct if the DISPLAY-order output still has one frame per
19313 // source picture, in the right order -- checked against our own
19314 // decoder as well as ffmpeg's, both below.
19315 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
19316 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
19317 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
19318 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
19319 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
19320 panic!(
19321 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
19322 decoded {got}, our decoder decoded {want}"
19323 );
19324 }
19325 }
19326 let mean: f64 = decoded
19327 .iter()
19328 .zip(source)
19329 .map(|(d, s)| psnr_all(d, s))
19330 .sum::<f64>()
19331 / source.len() as f64;
19332 ladder.push((mean, (stream.len() as f64).log10()));
19333 }
19334 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19335 (ladder, wall, counts, bytes, effective)
19336 }
19337
19338 /// Byte-exactness gate for encoder work that is meant to change only
19339 /// how long the encoder takes.
19340 ///
19341 /// The BD gate above measures quality, which a speed lane can move by a
19342 /// hair without failing anything; this pins the streams themselves.
19343 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
19344 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
19345 /// in the tile) and again on lane-av1mv's merge of it: an extra
19346 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
19347 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
19348 /// prices coefficients against the tables the frame's writer really
19349 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
19350 /// decision change the BD gate judges. Re-pinned again on
19351 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
19352 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
19353 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
19354 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
19355 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
19356 /// by default ([`warp_on`], a sequence/frame header bit and a new
19357 /// motion_mode symbol on eligible blocks) and
19358 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
19359 /// every inter frame's superblocks now code at their own lambda
19360 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
19361 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
19362 /// and the two var-tx depth searches ([`tx32_depth_search`],
19363 /// [`compound_var_tx`]) are on by default, all three re-judged on the
19364 /// native gate's real film rows.
19365 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
19366 /// every block whose chroma takes it codes a different mode symbol, two
19367 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
19368 /// restores the previous streams. Re-pinned again in the same lane once
19369 /// directional luma winners searched their `angle_delta_y`
19370 /// (`EC_AV1_ANGLE=0` restores that half).
19371 #[test]
19372 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
19373 // These are DEFAULT-PRESET pins: a speed preset switches search levers
19374 // off, so it legitimately moves every byte. Encode at speed 0 whatever
19375 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
19376 let _knobs = crate::speed::knob_write();
19377 let was = crate::speed::speed();
19378 crate::speed::set_speed(0);
19379 if !have_ffmpeg() {
19380 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
19381 return;
19382 }
19383 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19384 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
19385 if !clip.exists() {
19386 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
19387 return;
19388 }
19389 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
19390 // FNV-1a over the stream: a witness that every coded bit is where it
19391 // was, which a byte count alone is not.
19392 let fnv = |b: &[u8]| {
19393 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
19394 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
19395 })
19396 };
19397 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
19398 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
19399 // of 4, its leaves at q+8 and a `show_existing_frame` header per
19400 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
19401 // four frames; four pictures is one short mini-GOP, which is the
19402 // shape that pays least (the ARF's own quality has no later group to
19403 // carry it), so this is not the BD gate's number.
19404 // Re-taken again on lane-av1cfl: the chroma search offers
19405 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
19406 // so every block taking either codes different syntax and different
19407 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
19408 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
19409 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
19410 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
19411 // so these four pictures code as one truncated group -- a hidden
19412 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
19413 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
19414 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
19415 // Re-taken on lane-fintra: the sequence header sets
19416 // `enable_filter_intra`, so every DC_PRED intra block of at most
19417 // 32x32 without a luma palette carries a `use_filter_intra` flag and
19418 // the blocks that take one code a filter-intra mode, a different
19419 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
19420 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
19421 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
19422 // (default pyramid `8:-32:16`, one truncated group of 8 with its
19423 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
19424 // root can code a REAL residual now (one TX_64X64 luma transform and
19425 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
19426 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
19427 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
19428 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
19429 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
19430 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
19431 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
19432 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
19433 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
19434 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
19435 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
19436 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
19437 // these four pictures -- offers every superblock a 64x64 intra root
19438 // now. `EC_AV1_I64=0` restores 8557 / 33345.
19439 // Re-taken on lane-pricer: the inter RD search prices a single
19440 // reference through the tree and the neighbour contexts the writer
19441 // really codes it with, so every inter picture's reference decisions
19442 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
19443 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
19444 // for `skip`/`is_inter` and for the whole compound reference tree, so
19445 // every inter block's cost -- and with it the skip and reference
19446 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
19447 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
19448 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
19449 // single and compound are priced against the same syntax -- 8311 ->
19450 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
19451 // Re-taken on lane-newmv: the motion search charges its own rate term
19452 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
19453 // and each subpel stage re-runs from its own winner
19454 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
19455 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
19456 // and 33014 -> 33090 at q=60.
19457 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
19458 // from libaom's objective tpl mapping, so every inter picture's
19459 // quantizer grid -- and every decision priced against it -- moved
19460 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
19461 // at the merge of both lanes.
19462 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
19463 // per-superblock `delta_qindex` at 1.5x the preset's strength
19464 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
19465 // grids -- and every decision priced against them -- moved:
19466 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
19467 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
19468 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
19469 // pixels -- and the leaves that predict from them -- moved:
19470 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
19471 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
19472 // the shipped stream did not move.
19473 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
19474 // picture is coded in 128x128 superblocks now, the inter ones
19475 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
19476 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
19477 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
19478 // by default, on top of the ARF temporal filter).
19479 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
19480 // candidates the 64 root already did ([`b128_compound`]), so every
19481 // inter frame that carries `reference_select` codes different blocks
19482 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
19483 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
19484 // Re-taken on lane-arftf: that filter's strength swept on the deciding
19485 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
19486 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
19487 // 33017 at q=60 (the same LENGTH, different bytes).
19488 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
19489 // lane-rlclamp onto the 128 compound default.
19490 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
19491 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
19492 // so every inter frame whose RD takes one codes a different partition
19493 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
19494 // quantizer the rect cut never wins its own comparison on this clip.
19495 // `EC_AV1_B128HV=0` restores 8290 exactly.
19496 let pins: [(u8, usize, u64); 2] = [(150, 8291, 0x1f00bb0eb099a27f), (60, 33227, 0x57ee6b1f8eacd881)];
19497 let coded: Vec<(u8, usize, u64)> = pins
19498 .iter()
19499 .map(|&(q, _, _)| {
19500 let e = encode_sequence(&source, q, 0.5).unwrap();
19501 (q, e.stream.len(), fnv(&e.stream))
19502 })
19503 .collect();
19504 crate::speed::set_speed(was);
19505 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
19506 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
19507 }
19508 }
19509
19510 /// A ladder is only a ladder if both axes rise together.
19511 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
19512 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
19513 for w in ladder.windows(2) {
19514 assert!(
19515 w[1].0 > w[0].0 && w[1].1 > w[0].1,
19516 "{name}: not monotone, {ladder:?}"
19517 );
19518 }
19519 }
19520
19521 /// The sweep behind [`screen_content`]'s constants
19522 /// (`unswept-decision-constants`), on the SAME five clips
19523 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
19524 /// same native crop: for each colour bound N the share of 16x16 luma
19525 /// blocks with 2..=N distinct colours, and the share of those whose
19526 /// per-pixel variance also clears a floor V -- libaom's
19527 /// `av1_set_screen_content_options` counts the variance-cleared blocks
19528 /// too (its `counts_2`, which gates intrabc), and without that term a
19529 /// smooth dark film frame reads as screen content.
19530 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
19531 #[test]
19532 #[ignore = "reads the real library"]
19533 fn probe_screen_detect() {
19534 let _knobs = crate::speed::knob_read();
19535 if !have_ffmpeg() {
19536 eprintln!("SKIP probe_screen_detect: no ffmpeg");
19537 return;
19538 }
19539 let limits = [4usize, 8, 16, 32, 64, 128];
19540 let floors = [0u64, 4, 16, 64, 256];
19541 // The census of one clip at one size: mean share, over the frames, of
19542 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
19543 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
19544 let mut acc = [[0f64; 5]; 6];
19545 for picture in frames {
19546 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
19547 let mut hit = [[0usize; 5]; 6];
19548 let mut blocks = 0usize;
19549 for by in (0..ch).step_by(16) {
19550 for bx in (0..cw).step_by(16) {
19551 let mut seen = [false; 256];
19552 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
19553 for row in 0..16 {
19554 for col in 0..16 {
19555 let v = y[(by + row) * cw + bx + col];
19556 sum += u64::from(v);
19557 sq += u64::from(v) * u64::from(v);
19558 if !seen[usize::from(v)] {
19559 seen[usize::from(v)] = true;
19560 colors += 1;
19561 }
19562 }
19563 }
19564 let var = (sq - sum * sum / 256) / 256;
19565 blocks += 1;
19566 for (li, &limit) in limits.iter().enumerate() {
19567 if colors > 1 && colors <= limit {
19568 for (fi, &floor) in floors.iter().enumerate() {
19569 hit[li][fi] += usize::from(var > floor);
19570 }
19571 }
19572 }
19573 }
19574 }
19575 for li in 0..6 {
19576 for fi in 0..5 {
19577 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
19578 }
19579 }
19580 }
19581 let n = frames.len().max(1) as f64;
19582 eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len());
19583 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>());
19584 for (li, &limit) in limits.iter().enumerate() {
19585 eprintln!(
19586 " {limit:>5} |{}",
19587 (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>()
19588 );
19589 }
19590 };
19591 for (name, path, seek) in native_gate_clips() {
19592 let Some((nw, nh)) = probe_dims(&path) else {
19593 eprintln!("SKIP {name}: ffprobe gave no size");
19594 continue;
19595 };
19596 let cw = nw.min(1920) / 128 * 128;
19597 let ch = nh.min(1024) / 128 * 128;
19598 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
19599 let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12);
19600 census(&name, &frames, cw, ch);
19601 // The 640x384 gate scales instead of cropping, and the scaling
19602 // changes the census (bars smooth out): the constants have to
19603 // separate at BOTH sizes.
19604 let small = clip_frames(&path, &seek, 640, 384, 12);
19605 census(&name, &small, 640, 384);
19606 }
19607 }
19608
19609 /// The detector against the WHOLE real library (class
19610 /// `unswept-decision-constants`, user rule "his data is the gate"):
19611 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
19612 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
19613 /// duration, four frames each, 8-bit 4:2:0, at native size or a
19614 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
19615 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
19616 /// Prints per file and offset the share of qualifying 16x16 blocks, the
19617 /// [`screen_content`] verdict and a content hint (mean luma, luma
19618 /// standard deviation, inter MAD), then sweeps the colour bound against
19619 /// the variance floor over the whole library: for each (N, V) the worst
19620 /// (highest) share among the camera/film rows against the best (lowest)
19621 /// among the screen-recording rows, so the rule with the widest gap can
19622 /// be read off. Rows carry the manifest index, codec and size only --
19623 /// no titles, no home paths.
19624 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
19625 #[test]
19626 #[ignore = "reads the real library"]
19627 fn probe_screen_library() {
19628 let _knobs = crate::speed::knob_read();
19629 if !have_ffmpeg() {
19630 eprintln!("SKIP probe_screen_library: no ffmpeg");
19631 return;
19632 }
19633 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
19634 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
19635 eprintln!("SKIP probe_screen_library: no real-library manifest");
19636 return;
19637 };
19638 let limits = [4usize, 8, 16, 32, 64];
19639 let floors = [0u64, 4, 8, 16, 32, 64, 128];
19640 // Whatever ffmpeg gave us, without the exact-count assertion the
19641 // gate loaders make: a seek near the end of a clip returns fewer
19642 // frames, and that is a row to print, not a panic.
19643 let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
19644 let out = Command::new("ffmpeg")
19645 .args(["-v", "error", "-ss", seek, "-i", clip])
19646 .args(["-frames:v", &n.to_string()])
19647 .args(["-vf", vf])
19648 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
19649 .output();
19650 let Ok(out) = out else { return Vec::new() };
19651 if !out.status.success() {
19652 return Vec::new();
19653 }
19654 let (luma, chroma) = (w * h, w * h / 4);
19655 let frame_len = luma + 2 * chroma;
19656 (0..out.stdout.len() / frame_len)
19657 .map(|i| {
19658 let b = &out.stdout[i * frame_len..][..frame_len];
19659 Picture {
19660 width: w,
19661 height: h,
19662 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
19663 u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
19664 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
19665 }
19666 })
19667 .collect()
19668 };
19669 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
19670 // variance > V, for every (N, V) of the sweep grid, over one frame.
19671 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
19672 let mut hit = [[0usize; 7]; 5];
19673 let mut blocks = 0usize;
19674 for by in (0..h).step_by(16) {
19675 for bx in (0..w).step_by(16) {
19676 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
19677 let mut seen = [false; 256];
19678 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
19679 for row in 0..bh {
19680 for col in 0..bw {
19681 let v = y[(by + row) * w + bx + col];
19682 sum += u64::from(v);
19683 sq += u64::from(v) * u64::from(v);
19684 if !seen[usize::from(v)] {
19685 seen[usize::from(v)] = true;
19686 colors += 1;
19687 }
19688 }
19689 }
19690 let n = (bh * bw) as u64;
19691 let var = (sq - sum * sum / n) / n;
19692 blocks += 1;
19693 for (li, &limit) in limits.iter().enumerate() {
19694 if colors > 1 && colors <= limit {
19695 for (fi, &floor) in floors.iter().enumerate() {
19696 hit[li][fi] += usize::from(var > floor);
19697 }
19698 }
19699 }
19700 }
19701 }
19702 let mut out = [[0f64; 7]; 5];
19703 for li in 0..5 {
19704 for fi in 0..7 {
19705 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
19706 }
19707 }
19708 out
19709 };
19710 // (index, label, path, duration, screen-by-its-own-content). The
19711 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
19712 // are desktop recordings; everything else in this library is camera
19713 // or film material.
19714 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
19715 for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] {
19716 let path = fixtures.join("video").join(file);
19717 if path.exists() {
19718 rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false));
19719 }
19720 }
19721 for (i, line) in manifest.lines().skip(1).enumerate() {
19722 let f: Vec<&str> = line.split('\t').collect();
19723 if f.len() < 10 {
19724 continue;
19725 }
19726 let (path, codec) = (f[0], f[2]);
19727 if codec == "-" || codec.is_empty() {
19728 continue;
19729 }
19730 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
19731 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
19732 continue;
19733 };
19734 if !std::path::Path::new(path).exists() {
19735 eprintln!("SKIP {}: file is gone", i + 1);
19736 continue;
19737 }
19738 let name = path.rsplit('/').next().unwrap_or(path);
19739 let is_capture = path.contains("/OBS/")
19740 || (name.len() > 19
19741 && name.as_bytes()[4] == b'-'
19742 && name.as_bytes()[7] == b'-'
19743 && name.as_bytes()[10] == b' '
19744 && name.as_bytes()[13] == b'-');
19745 rows.push((
19746 format!("{}", i + 1),
19747 format!("{codec} {w}x{h}"),
19748 path.to_string(),
19749 f[8].parse::<f64>().unwrap_or(0.0),
19750 is_capture,
19751 ));
19752 }
19753 // Per (N, V): the worst camera/film row and the best screen row, so
19754 // the separation of the whole library is one subtraction.
19755 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
19756 eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |");
19757 for (idx, label, path, dur, is_capture) in &rows {
19758 let Some((nw, nh)) = probe_dims(path) else {
19759 eprintln!("SKIP {idx}: ffprobe gave no size");
19760 continue;
19761 };
19762 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
19763 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
19764 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
19765 let mut file_grid = [[0f64; 7]; 5];
19766 let mut file_frames = 0usize;
19767 for pct in [10u32, 50, 90] {
19768 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
19769 let frames = decode(path, &seek, &vf, cw, ch, 4);
19770 if frames.is_empty() {
19771 eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" });
19772 continue;
19773 }
19774 let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64);
19775 let mut prev: Option<Vec<u8>> = None;
19776 for picture in &frames {
19777 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
19778 let grid = census(&y, cw, ch);
19779 for li in 0..5 {
19780 for fi in 0..7 {
19781 file_grid[li][fi] += grid[li][fi];
19782 }
19783 }
19784 file_frames += 1;
19785 // The shipped rule is (16 colours, var > 16): grid row 2,
19786 // floor 16 is column 3.
19787 share += grid[2][3];
19788 yes += usize::from(screen_content(&y, cw, cw, ch));
19789 let n = y.len() as f64;
19790 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
19791 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
19792 mean += sum / n;
19793 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
19794 if let Some(p) = &prev {
19795 mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n;
19796 }
19797 prev = Some(y);
19798 }
19799 let f = frames.len() as f64;
19800 eprintln!(
19801 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
19802 if *is_capture { "screen" } else { "camera" },
19803 share / f,
19804 if yes * 2 > frames.len() { "SCREEN" } else { "camera" },
19805 frames.len(),
19806 mean / f,
19807 sd / f,
19808 mad / (f - 1.0).max(1.0),
19809 );
19810 }
19811 if file_frames == 0 {
19812 continue;
19813 }
19814 for li in 0..5 {
19815 for fi in 0..7 {
19816 let s = file_grid[li][fi] / file_frames as f64;
19817 match is_capture {
19818 true => scr_min[li][fi] = scr_min[li][fi].min(s),
19819 false => cam_max[li][fi] = cam_max[li][fi].max(s),
19820 }
19821 }
19822 }
19823 }
19824 eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):");
19825 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>());
19826 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
19827 for (li, &limit) in limits.iter().enumerate() {
19828 let mut row = String::new();
19829 for fi in 0..7 {
19830 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
19831 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
19832 if s - c > best {
19833 best = s - c;
19834 best_rule = (limit, floors[fi]);
19835 }
19836 }
19837 eprintln!(" {limit:>5} |{row}");
19838 }
19839 // The threshold sits at the midpoint of the widest gap; the shipped
19840 // constant is its reciprocal in whole parts of the frame.
19841 let (li, fi) = (
19842 limits.iter().position(|&l| l == best_rule.0).unwrap(),
19843 floors.iter().position(|&f| f == best_rule.1).unwrap(),
19844 );
19845 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
19846 eprintln!(
19847 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
19848 best_rule.0,
19849 best_rule.1,
19850 best,
19851 cam_max[li][fi],
19852 scr_min[li][fi],
19853 mid,
19854 (100.0 / mid.max(0.1)).round() as usize,
19855 );
19856 }
19857
19858 /// The missing instrument: what this encoder costs against libaom and
19859 /// rav1e at matched fidelity, and how long it takes to get there.
19860 ///
19861 /// Recipe, identical on all three sides: 12 consecutive frames of each
19862 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
19863 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
19864 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
19865 /// it by default), 4:2:0 8-bit in and out. Reference points:
19866 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
19867 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
19868 /// tile_cols=1:tile_rows=1:threads=1`
19869 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
19870 /// ffmpeg-decoded frames of each encoder's own stream.
19871 ///
19872 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
19873 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
19874 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
19875 /// four encodes of that ladder together):
19876 ///
19877 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
19878 /// |---|---|---|---|---|
19879 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
19880 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
19881 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
19882 ///
19883 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
19884 /// the encoder takes -- every stream it writes is byte-identical, so the
19885 /// BD columns are this box's own re-run of the same recipe rather than a
19886 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
19887 /// rav1e). What moved is the wall of the four encodes:
19888 ///
19889 /// | clip | wall ours before | after | instructions:u before -> after |
19890 /// |---|---|---|---|
19891 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
19892 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
19893 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
19894 ///
19895 /// Three exact steps, none of which touches a coded bit: the coefficient
19896 /// rate pricer stopped rebuilding every CDF table per candidate
19897 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
19898 /// tile once per candidate (`decode::FilterReplay`), and the forward
19899 /// transform stopped transforming the all-zero residual that 70% of its
19900 /// calls carry.
19901 ///
19902 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
19903 ///
19904 /// | step | 1080p | 2160p | screen |
19905 /// |---|---|---|---|
19906 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
19907 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
19908 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
19909 ///
19910 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
19911 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
19912 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
19913 /// -- all three decided on the REAL film rows of
19914 /// [`bd_rate_screen_native`], which this downscaled recipe does not
19915 /// carry:
19916 ///
19917 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
19918 /// |---|---|---|---|
19919 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
19920 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
19921 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
19922 ///
19923 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
19924 /// DEFAULT of the sequence path this gate codes through -- the bars are
19925 /// non-screen so they take it, the capture is gated flat:
19926 ///
19927 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
19928 /// |---|---|---|---|---|
19929 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
19930 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
19931 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
19932 ///
19933 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
19934 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
19935 /// facade arm -- which is what "one mini-GOP driver, two entry points"
19936 /// means here. This downscaled recipe HATES the pyramid (as it hates
19937 /// every knob the real film rows of `bd_rate_screen_native` keep, which
19938 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
19939 /// above. The capture's row is the flat row to the byte in both runs --
19940 /// that equality IS the content gate.
19941 ///
19942 /// Loop restoration is NOT in yet: it is the one filter whose parameters
19943 /// are per restoration UNIT inside the tile payload, so it needs both
19944 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
19945 /// buffer to solve against -- neither of which this frame-header-level
19946 /// search reaches.
19947 ///
19948 /// The baseline it replaced, before an inter frame's blocks chose their
19949 /// own partition, was +501.4/+504.4/+440.9 against libaom and
19950 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
19951 ///
19952 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
19953 /// fidelity, while spending far more time than either (the partition
19954 /// search's own cost, uncut: see the two intra-pruning variants measured
19955 /// and rejected in the lane report). No
19956 /// threshold is asserted yet -- this run sets the baseline; the gate
19957 /// asserts four monotone points per ladder, and at EVERY ladder point of
19958 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
19959 /// `crate::stream::decode_stream` -- and asserts the encoder's
19960 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
19961 /// and V over every shown frame in display order. A failure names the
19962 /// clip, the q, the frame, the plane and the first differing sample.
19963 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
19964 /// which exposes no per-packet reconstruction, so that path asserts the
19965 /// two decoders against each other on all three planes.)
19966 ///
19967 /// Run:
19968 /// cargo test -p ec-av1 --release --lib -- --ignored \
19969 /// bd_rate_vs_libaom_and_rav1e --nocapture
19970 #[test]
19971 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
19972 fn bd_rate_vs_libaom_and_rav1e() {
19973 let _knobs = crate::speed::knob_write();
19974 if !have_ffmpeg() {
19975 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
19976 return;
19977 }
19978 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
19979 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
19980 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
19981 // rows for real content (the real rows live in the native gate).
19982 for (label, name) in [
19983 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
19984 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
19985 ] {
19986 let path = fixtures.join("video").join(name);
19987 if path.exists() {
19988 clips.push((label.to_string(), path));
19989 } else {
19990 eprintln!("SKIP clip {name}: missing");
19991 }
19992 }
19993 // Screen capture: the repo carries no screen-capture fixture, so take
19994 // the first OBS recording the real-library manifest names.
19995 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
19996 Ok(manifest) => {
19997 let screen = manifest
19998 .lines()
19999 .skip(1)
20000 .filter_map(|l| l.split('\t').next())
20001 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
20002 match screen {
20003 Some(p) => clips.push((
20004 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
20005 std::path::PathBuf::from(p),
20006 )),
20007 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
20008 }
20009 }
20010 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
20011 }
20012 assert!(!clips.is_empty(), "no source clip available");
20013
20014 let (width, height, frames) = (640usize, 384usize, 12usize);
20015 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
20016 .iter()
20017 .map(|q| {
20018 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
20019 .map(String::from)
20020 .to_vec()
20021 })
20022 .collect();
20023 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
20024 .iter()
20025 .map(|q| {
20026 vec![
20027 "-rav1e-params".to_string(),
20028 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
20029 ]
20030 })
20031 .collect();
20032 println!(
20033 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
20034 );
20035 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
20036 println!("|---|---|---|---|---|");
20037 for (name, path) in &clips {
20038 let fctx = &crate::decode::FrameCtx::for_encoder();
20039 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
20040 let _ = take_partition_hits();
20041 let _ = crate::tile::take_palette_hits();
20042 SCREEN_FRAMES.iter().for_each(|c| {
20043 c.store(0, std::sync::atomic::Ordering::Relaxed);
20044 });
20045 let _ = take_uv_mode_hits();
20046 let _ = crate::tile::take_inter_mode_hits();
20047 let _ = crate::tile::take_drl_hits();
20048 let _ = crate::tile::take_ref_hits();
20049 let _ = crate::tile::take_compound_mode_hits();
20050 let _ = crate::tile::take_compound_pair_hits();
20051 let _ = crate::tile::take_compound_size_hits();
20052 let _ = crate::tile::take_compound_leaf_mode_hits();
20053 let _ = take_b64_root_hits();
20054 let _ = take_b64_residual_hits();
20055 let _ = take_b64_compound_hits();
20056 let _ = crate::motion::take_census();
20057 // The entry-surface arm: run the SAME ladder through the
20058 // streaming facade the editor's export calls, which must print
20059 // the same BD numbers as the sequence path -- byte for byte the
20060 // same stream now that both drive one mini-GOP driver
20061 // (lane-av1pyrdef).
20062 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
20063 let (ours, ours_wall) = match facade {
20064 false => our_ladder(name, &source, width, height, fctx),
20065 true => {
20066 let pyramid = crate::encoder::Pyramid::from_env();
20067 let (ladder, wall, counts, bytes, effective) =
20068 our_ladder_facade(name, &source, width, height, pyramid);
20069 eprintln!(
20070 "{name}: facade, pyramid requested {pyramid:?} effective \
20071 {effective:?} -- frames key {} arf {} leaf {} \
20072 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
20073 counts[0], counts[1], counts[2], counts[3],
20074 bytes[0], bytes[1], bytes[2], bytes[3],
20075 );
20076 (ladder, wall)
20077 }
20078 };
20079 // How often the inter split actually fired over this clip's four
20080 // encodes, against the whole 32x32 that was the only outcome
20081 // before (gate-blind-to-feature).
20082 let [whole32, split32, whole16, split16] = take_partition_hits();
20083 // Which inter modes actually fired over this clip's four encodes,
20084 // and at which DRL index -- a mode nobody picks is a mode the BD
20085 // number cannot be crediting (gate-blind-to-feature).
20086 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
20087 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
20088 let refs = crate::tile::take_ref_hits();
20089 let modes_total = (nearest + near + global + new).max(1);
20090 eprintln!(
20091 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
20092 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
20093 {drl0}/{drl1}/{drl2}/{drl3}",
20094 100.0 * nearest as f64 / modes_total as f64,
20095 100.0 * near as f64 / modes_total as f64,
20096 100.0 * global as f64 / modes_total as f64,
20097 100.0 * new as f64 / modes_total as f64,
20098 );
20099 // The compound census: what share of the coded inter blocks took
20100 // a compound reference at all, which compound mode they took, and
20101 // which pair (gate-blind-to-feature -- a compound mode nobody
20102 // picks cannot be what a BD number credits).
20103 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
20104 // superblocks were left whole at all, and how many of those coded
20105 // a residual or took a compound reference.
20106 let (roots, root_res, root_comp) = (
20107 take_b64_root_hits(),
20108 take_b64_residual_hits(),
20109 take_b64_compound_hits(),
20110 );
20111 eprintln!(
20112 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
20113 );
20114 let comp_modes = crate::tile::take_compound_mode_hits();
20115 let comp_pairs = crate::tile::take_compound_pair_hits();
20116 let comp_sizes = crate::tile::take_compound_size_hits();
20117 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
20118 let comp_total: usize = comp_modes.iter().sum();
20119 eprintln!(
20120 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
20121 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
20122 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
20123 modes_total + comp_total,
20124 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
20125 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
20126 comp_modes[6], comp_modes[7],
20127 comp_pairs[3], comp_pairs[6],
20128 );
20129 eprintln!(
20130 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
20131 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
20132 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6],
20133 comp_leaf[7],
20134 );
20135 eprintln!(
20136 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
20137 comp_sizes[1], comp_sizes[2], comp_sizes[3],
20138 );
20139 // Where the wall-owning stage actually goes: how many candidate
20140 // evaluations (one `mc::predict` + SAD each) a search spends, how
20141 // many of them are subpel, and how often the winner is the seed
20142 // it started from -- the census the seeded search is judged by.
20143 let [calls, evals, subpel, rounds, near_pred, unmoved, widest, widest_moves] =
20144 crate::motion::take_census();
20145 let per = |n: u64| n as f64 / calls.max(1) as f64;
20146 eprintln!(
20147 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
20148 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
20149 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
20150 per(evals),
20151 100.0 * subpel as f64 / evals.max(1) as f64,
20152 per(rounds),
20153 100.0 * near_pred as f64 / calls.max(1) as f64,
20154 100.0 * unmoved as f64 / calls.max(1) as f64,
20155 );
20156 // lane-newmv, class `instrument at bound`: how often the winner
20157 // was walked to at the log stage's own WIDEST step -- a high
20158 // share means the search stops where its step lets it, not where
20159 // the content is.
20160 eprintln!(
20161 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
20162 100.0 * widest as f64 / calls.max(1) as f64,
20163 per(widest_moves),
20164 );
20165 eprintln!(
20166 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
20167 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
20168 );
20169 eprintln!(
20170 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
20171 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
20172 whole32 + split32,
20173 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
20174 whole16 + split16,
20175 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
20176 );
20177 // The deblocking level each of this clip's frames chose
20178 // (lane-av1filt): 0 everywhere would mean the filter never fires.
20179 let levels = crate::filter_search::take_chosen_levels();
20180 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
20181 let mean = |f: fn(&Chosen) -> u8| {
20182 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
20183 };
20184 eprintln!(
20185 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
20186 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
20187 levels.len(),
20188 mean(|l| l.0.0),
20189 mean(|l| l.0.1),
20190 mean(|l| l.1.0),
20191 mean(|l| l.1.1),
20192 mean(|l| l.2.0),
20193 mean(|l| l.2.1),
20194 );
20195 // How many strength presets each frame's CDEF list carried and
20196 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
20197 // everywhere would mean the per-unit choice never fires.
20198 let presets = crate::filter_search::take_cdef_presets();
20199 let mut by_bits = [0usize; 4];
20200 for (b, _) in &presets {
20201 by_bits[usize::from(*b)] += 1;
20202 }
20203 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
20204 let on_extra: usize = presets
20205 .iter()
20206 .flat_map(|(_, c)| c.iter().skip(1))
20207 .sum();
20208 eprintln!(
20209 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
20210 on a non-default preset ({:.1}%)",
20211 by_bits[0],
20212 by_bits[1],
20213 by_bits[2],
20214 by_bits[3],
20215 on_extra,
20216 units,
20217 100.0 * on_extra as f64 / units.max(1) as f64
20218 );
20219 // How the 64x64 luma restoration units split between
20220 // RESTORE_NONE and Wiener (lane-av1lr).
20221 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
20222 eprintln!(
20223 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
20224 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
20225 );
20226 // Which chroma modes the search actually wins with, against the
20227 // unconditional DC_PRED that was the only outcome before
20228 // (gate-blind-to-feature).
20229 // Screen-content detection and the palette it turns on
20230 // (gate-blind-to-feature): how many frames set
20231 // `allow_screen_content_tools`, how many blocks took a palette,
20232 // and of what size. A film clip must print `screen frames on=0`.
20233 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20234 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
20235 // Which tables the SEARCH priced against, per frame arming
20236 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
20237 // real starting ones. A film clip must show every inter arming on
20238 // the real side, a screen clip none of them.
20239 let (price_default, price_real) = crate::tile::take_pricing_hits();
20240 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
20241 let palette = crate::tile::take_palette_hits();
20242 eprintln!(
20243 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
20244 palette[0],
20245 (2..=8)
20246 .filter(|&n| palette[n] > 0)
20247 .map(|n| format!("{n}={}", palette[n]))
20248 .collect::<Vec<_>>()
20249 .join(" ")
20250 );
20251 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
20252 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
20253 // only ever fires at one magnitude is a search that never left
20254 // its first candidate (gate-blind-to-feature).
20255 // The luma angle-delta histogram (lane-av1cfl): how many
20256 // directional blocks won at each delta. All-zero would mean the
20257 // refinement never beat the base angle.
20258 let deltas = take_angle_delta_hits();
20259 if deltas.iter().sum::<usize>() > 0 {
20260 eprintln!(
20261 "{name}: angle_delta_y {}",
20262 deltas
20263 .iter()
20264 .enumerate()
20265 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
20266 .collect::<Vec<_>>()
20267 .join(" ")
20268 );
20269 }
20270 let alphas = take_cfl_alpha_hits();
20271 if alphas.iter().sum::<usize>() > 0 {
20272 eprintln!(
20273 "{name}: cfl |alpha| {}",
20274 alphas
20275 .iter()
20276 .enumerate()
20277 .filter(|&(_, &n)| n > 0)
20278 .map(|(a, &n)| format!("{a}={n}"))
20279 .collect::<Vec<_>>()
20280 .join(" ")
20281 );
20282 }
20283 let palette_uv = crate::tile::take_palette_uv_hits();
20284 eprintln!(
20285 "{name}: chroma palette blocks {} sizes {}",
20286 palette_uv[0],
20287 (2..=8)
20288 .filter(|&n| palette_uv[n] > 0)
20289 .map(|n| format!("{n}={}", palette_uv[n]))
20290 .collect::<Vec<_>>()
20291 .join(" ")
20292 );
20293 let uv = take_uv_mode_hits();
20294 let uv_total: usize = uv.iter().sum();
20295 eprintln!(
20296 "{name}: uv modes {}",
20297 uv.iter()
20298 .enumerate()
20299 .filter(|&(_, &n)| n > 0)
20300 .map(|(m, &n)| format!(
20301 "{}={n} ({:.1}%)",
20302 UV_MODE_NAMES[m],
20303 100.0 * n as f64 / uv_total.max(1) as f64
20304 ))
20305 .collect::<Vec<_>>()
20306 .join(" ")
20307 );
20308 // Which transform depth the intra blocks of this clip's key
20309 // frames resolved to (lane-av1tx): depth 0 is one transform over
20310 // the whole block, 1 and 2 its halvings.
20311 let depths = take_tx_depth_hits();
20312 let depth_total: usize = depths.iter().sum();
20313 eprintln!(
20314 "{name}: intra tx depths {}",
20315 depths
20316 .iter()
20317 .enumerate()
20318 .map(|(d, &n)| format!(
20319 "{d}={n} ({:.1}%)",
20320 100.0 * n as f64 / depth_total.max(1) as f64
20321 ))
20322 .collect::<Vec<_>>()
20323 .join(" ")
20324 );
20325 print_inter_tx_census(name);
20326 // lane-av1obmc: how many blocks actually CODED a motion_mode
20327 // symbol and which value they took, by footprint -- "OBMC is on"
20328 // as a measurement rather than a claim (class
20329 // `gate-blind-to-feature`).
20330 let mm = crate::tile::take_motion_mode_hits();
20331 eprintln!(
20332 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
20333 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
20334 eligible)",
20335 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
20336 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20337 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20338 mm.iter().sum::<usize>(),
20339 );
20340 let (aom, aom_wall) =
20341 external_ladder(&source, width, height, "libaom-av1", &aom_points);
20342 let (rav1e, rav1e_wall) =
20343 external_ladder(&source, width, height, "librav1e", &rav1e_points);
20344 assert_monotone(&format!("{name}: ours"), &ours);
20345 assert_monotone(&format!("{name}: libaom"), &aom);
20346 assert_monotone(&format!("{name}: rav1e"), &rav1e);
20347 let points = ours
20348 .iter()
20349 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20350 .collect::<Vec<_>>()
20351 .join(", ");
20352 println!(
20353 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
20354 bd_rate(&aom, &ours) * 100.0,
20355 bd_rate(&rav1e, &ours) * 100.0,
20356 );
20357 println!(
20358 "| references | libaom {} | rav1e {} | | |",
20359 aom.iter()
20360 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20361 .collect::<Vec<_>>()
20362 .join(", "),
20363 rav1e
20364 .iter()
20365 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20366 .collect::<Vec<_>>()
20367 .join(", "),
20368 );
20369 }
20370 assert_ladder_decodes();
20371 }
20372 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
20373 /// split by block class in lane-av1txdepth): depth 0 is one transform over
20374 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
20375 /// leaves and the 32x32 root, each single-reference or compound. A class
20376 /// with no counts at all never reached `commit_inter_luma` -- which is
20377 /// what its knob being off looks like (class `gate-blind-to-feature`).
20378 fn print_inter_tx_census(name: &str) {
20379 let splits = take_inter_tx_split_hits();
20380 let total: usize = splits.iter().sum();
20381 let row = |label: &str, base: usize| {
20382 let (n0, n1) = (splits[base], splits[base + 1]);
20383 format!(
20384 "{label} 0={n0} 1={n1} ({:.1}% split)",
20385 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
20386 )
20387 };
20388 eprintln!(
20389 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
20390 row("leaf single", 0),
20391 row("leaf compound", 2),
20392 row("32x32 single", 4),
20393 row("32x32 compound", 6),
20394 );
20395 // lane-txrd: which types the two searches actually COMMITTED over
20396 // this row's four encodes -- the gate could not say whether a type
20397 // search fired at all (class `gate-blind-to-feature`).
20398 const NAMES: [&str; 16] = [
20399 "IDTX", "DCT_DCT", "ADST_ADST", "ADST_DCT", "DCT_ADST", "V_DCT", "H_DCT",
20400 "FLIPADST_DCT", "DCT_FLIPADST", "FLIPADST_FLIPADST", "ADST_FLIPADST",
20401 "FLIPADST_ADST", "V_ADST", "H_ADST", "V_FLIPADST", "H_FLIPADST",
20402 ];
20403 let name_of = |t: usize| NAMES[t];
20404 for (label, hits) in [("inter", take_inter_tx_type_hits()), ("intra", take_tx_type_hits())] {
20405 let total: usize = hits.iter().sum();
20406 let live: Vec<String> = hits
20407 .iter()
20408 .enumerate()
20409 .filter(|&(_, &n)| n > 0)
20410 .map(|(t, &n)| format!("{}={n} ({:.1}%)", name_of(t), 100.0 * n as f64 / total.max(1) as f64))
20411 .collect();
20412 eprintln!("{name}: {label} tx_type of {total} units -- {}", live.join(" "));
20413 }
20414 let t = take_txrd_stats();
20415 if t[0] > 0 {
20416 eprintln!(
20417 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
20418 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
20419 t[0], t[1], t[3] as f64 / 64.0, t[2], t[4] as f64 / 64.0,
20420 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
20421 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
20422 );
20423 eprintln!(
20424 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
20425 flat: dsse {:+.2}%, dbits {:+.2}%)",
20426 t[5], t[6] as f64 / 64.0,
20427 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
20428 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
20429 );
20430 }
20431 }
20432
20433 /// The video stream's coded size, from ffprobe.
20434 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
20435 crate::probe::dims(clip)
20436 }
20437
20438 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
20439 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
20440 /// superblock-aligned one, still centred and still even for 4:2:0.
20441 ///
20442 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
20443 /// superblocks by design, so no default gate row has a block the frame
20444 /// edge cuts through -- while every arbitrary export size does (3840x1608
20445 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
20446 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
20447 /// read on.
20448 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
20449 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
20450 let (w, h) = spec.split_once('x').expect("EC_AV1_NATIVE_CROP is <width>x<height>");
20451 let (cw, ch): (usize, usize) =
20452 (w.parse().expect("crop width"), h.parse().expect("crop height"));
20453 let (nw, nh) = crate::probe::dims(clip)?;
20454 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
20455 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
20456 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
20457 }
20458
20459 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
20460 /// with `probe_screen_detect` so the detector sweep measures exactly the
20461 /// clips the keep table is read off. Selector env vars as documented on
20462 /// the gate; a missing clip prints a SKIP and drops its row.
20463 fn native_gate_clips() -> Vec<(String, String, String)> {
20464 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
20465 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
20466 let (film, film4k, screen) = (
20467 on("EC_AV1_NATIVE_FILM"),
20468 on("EC_AV1_NATIVE_FILM4K"),
20469 on("EC_AV1_NATIVE_SCREEN"),
20470 );
20471 // No selector at all means every clip; any selector means that subset.
20472 let all = !(film || film4k || screen);
20473 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
20474 // not film -- they print as "bars" so no reader takes them for real
20475 // content -- and the two rows below them are the real AV1 films.
20476 let mut clips: Vec<(String, String, String)> = Vec::new();
20477 for (want, label, file) in [
20478 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
20479 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
20480 ] {
20481 if !want {
20482 continue;
20483 }
20484 let path = fixtures.join("video").join(file);
20485 match path.exists() {
20486 true => {
20487 clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into()))
20488 }
20489 false => eprintln!("SKIP {label}: {file} missing"),
20490 }
20491 }
20492 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
20493 // The real films, taken out of the real-library manifest by codec and
20494 // coded width so no title and no home path lives in this file. Each
20495 // seek is PINNED (class `seeded fixture not reproducible`) at a
20496 // moving, non-black window -- a black leader would make every arm
20497 // read +0.000 (class `flat sample window`). Both sources are 10-bit
20498 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
20499 // what all three encoders see, so the comparison stays
20500 // encoder-vs-encoder.
20501 let pick = |width: &str| -> Option<String> {
20502 let m = manifest.as_ref().ok()?;
20503 m.lines()
20504 .skip(1)
20505 .map(|l| l.split('\t').collect::<Vec<_>>())
20506 .find(|f| {
20507 f.len() > 4
20508 && f[2] == "av1"
20509 && f[3] == width
20510 && std::path::Path::new(f[0]).exists()
20511 })
20512 .map(|f| f[0].to_string())
20513 };
20514 for (want, label, width, seek) in [
20515 (all || film, "film A (1080p source)", "1920", "00:35:00"),
20516 (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"),
20517 ] {
20518 if !want {
20519 continue;
20520 }
20521 match pick(width) {
20522 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
20523 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
20524 }
20525 }
20526 if all || screen {
20527 match &manifest {
20528 Ok(manifest) => match manifest
20529 .lines()
20530 .skip(1)
20531 .filter_map(|l| l.split('\t').next())
20532 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
20533 {
20534 Some(p) => clips.push((
20535 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
20536 p.to_string(),
20537 "0".into(),
20538 )),
20539 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
20540 },
20541 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
20542 }
20543 }
20544 clips
20545 }
20546
20547 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
20548 /// downscales the OBS capture to 640x384, which destroys exactly the
20549 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
20550 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
20551 /// on that recipe is taken on content the tool cannot serve. This arm
20552 /// crops -- never scales -- a superblock-aligned window out of the middle
20553 /// of the capture at its own resolution (at most 1920x1024, so the wall
20554 /// stays in the minutes) and runs the same 12-frame, four-quantizer
20555 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
20556 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
20557 /// sample-exactness assertion `our_ladder` makes.
20558 ///
20559 /// It is its own `--ignored` test so the default gate's wall does not
20560 /// grow. Every variant is an environment knob, and each of those is a
20561 /// `OnceLock` read once per process, so a variant is a separate run:
20562 ///
20563 /// cargo test -p ec-av1 --release --lib -- --ignored \
20564 /// bd_rate_screen_native --nocapture # baseline
20565 /// EC_AV1_INTRABC=1 ... same command # intra block copy
20566 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
20567 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
20568 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
20569 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
20570 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
20571 ///
20572 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
20573 /// through (lane-av1pyrdef); the run prints the requested and the
20574 /// effective pyramid per clip, and a screen clip's effective one is
20575 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
20576 /// streaming facade instead, which prints the per-level frame and byte
20577 /// census and asserts ffmpeg's decode against our own decoder on all
20578 /// three planes in display order; both arms code the same bytes
20579 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
20580 ///
20581 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
20582 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
20583 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
20584 /// cost -- so every "film" column in the historical tables of this file
20585 /// is that generator, not film. The real content is `film A`, `film B`
20586 /// (native crops out of the two AV1 films the real-library manifest
20587 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
20588 /// decision only the bars rows support is not supported.
20589 ///
20590 /// Measured 2026-09-07, the five rows before and after the screen
20591 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
20592 /// BOTH real films were classified as screen content on 48/48 frames, so
20593 /// their coefficients were priced against the DEFAULT CDFs and the
20594 /// palette search ran over film; after, both are non-screen (0/48) and
20595 /// the capture is unchanged at 48/48:
20596 ///
20597 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
20598 /// |---|---|---|---|
20599 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
20600 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
20601 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
20602 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
20603 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
20604 ///
20605 /// Both bars rows and the capture are byte-identical across that change
20606 /// (their classification never moved); the palette search over film was
20607 /// costing roughly a tenth of the film rows' wall.
20608 ///
20609 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
20610 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
20611 /// the capture is gated flat and does not move a byte:
20612 ///
20613 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
20614 /// |---|---|---|---|---|
20615 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
20616 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
20617 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
20618 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
20619 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
20620 ///
20621 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
20622 /// which is the point of the shared driver: the two entry points code one
20623 /// stream. The bars rows are fixtures (recorded, never a decision); the
20624 /// two real films are what the pyramid ships for.
20625 ///
20626 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
20627 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
20628 /// setting any one of them keeps only the selected rows (the two 1080p
20629 /// rows, the two 2160p rows, the capture row respectively). A missing
20630 /// real film SKIPs its row; it never fails the gate.
20631 #[test]
20632 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
20633 fn bd_rate_screen_native() {
20634 let _knobs = crate::speed::knob_read();
20635 native_bd_arm("bd_rate_screen_native", 12, false);
20636 }
20637
20638 /// The LONG-GOP arm of the native BD gate: the same recipe as
20639 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
20640 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
20641 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
20642 /// reaches libaom as `--kf-max-dist=48` and rav1e as
20643 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
20644 /// inter pictures.
20645 ///
20646 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
20647 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
20648 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
20649 /// above 12 codes the same stream there -- the shipped `16` was measured
20650 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
20651 /// group (class `instrument at bound` / `gate blind to feature`). The
20652 /// user's exports are long GOPs, so the pyramid shape is decided here.
20653 ///
20654 /// cargo test -p ec-av1 --release --lib -- --ignored \
20655 /// bd_rate_film_long_gop --nocapture
20656 ///
20657 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
20658 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
20659 /// Read every row off the log's own "pyramid requested/effective" print,
20660 /// never off the argument order of the runs (lane-pyr3 misattributed
20661 /// three rows that way).
20662 ///
20663 /// Table: `lanes/pyr4.sweep.txt`.
20664 #[test]
20665 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
20666 fn bd_rate_film_long_gop() {
20667 let _knobs = crate::speed::knob_write();
20668 native_bd_arm("bd_rate_film_long_gop", 48, true);
20669 }
20670
20671 /// The shared driver of the two native BD arms above: `frames` pictures
20672 /// per row (the sequence's `gop` is the same number, so one key frame),
20673 /// four quantizers, `films_only` dropping every row but the two real
20674 /// films.
20675 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
20676 if !have_ffmpeg() {
20677 eprintln!("SKIP {label}: no ffmpeg");
20678 return;
20679 }
20680 let mut clips = native_gate_clips();
20681 if films_only {
20682 clips.retain(|(name, _, _)| name.starts_with("film "));
20683 }
20684 if clips.is_empty() {
20685 eprintln!("SKIP {label}: no clip");
20686 return;
20687 }
20688
20689 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
20690 .iter()
20691 .map(|q| {
20692 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
20693 .map(String::from)
20694 .to_vec()
20695 })
20696 .collect();
20697 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
20698 .iter()
20699 .map(|q| {
20700 vec![
20701 "-rav1e-params".to_string(),
20702 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
20703 ]
20704 })
20705 .collect();
20706 println!(
20707 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
20708 intrabc {}, palette maxcolors {}",
20709 armed_tiles(),
20710 crate::par::tile_threads(),
20711 intrabc_enabled(),
20712 palette_max_colors(),
20713 );
20714 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |");
20715 println!("|---|---|---|---|---|");
20716 for (name, path, seek) in &clips {
20717 let fctx = &crate::decode::FrameCtx::for_encoder();
20718 if probe_dims(path).is_none() {
20719 eprintln!("SKIP {name}: ffprobe gave no size");
20720 continue;
20721 }
20722 // A whole number of 128-wide superblocks, at most 1920x1024, out
20723 // of the middle of the frame; the offsets stay even for 4:2:0.
20724 // ONE definition, shared with `examples/enc_probe` so the probe
20725 // cannot measure a different window than this gate (lane-probe).
20726 let (vf, cw, ch) = match native_crop_override(path) {
20727 Some(over) => over,
20728 None => crate::probe::gate_crop(path),
20729 };
20730 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
20731 SCREEN_FRAMES.iter().for_each(|c| {
20732 c.store(0, std::sync::atomic::Ordering::Relaxed);
20733 });
20734 let _ = crate::tile::take_palette_hits();
20735 let _ = crate::tile::take_palette_uv_hits();
20736 let _ = crate::tile::take_intrabc_hits();
20737 let _ = take_intrabc_search();
20738 let _ = crate::tile::take_filter_intra_hits();
20739 let _ = take_edge_census();
20740 // The sequence path itself codes the pyramid now
20741 // (lane-av1pyrdef), and prints what it requested and what the
20742 // content gate left effective.
20743 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
20744 // lane-sse: the blocks the true frame edge cuts through, and how
20745 // much of their RAW squared error sat in the padding the encoder
20746 // invented past it -- what the inside-only score stopped ranking
20747 // on. Empty on a superblock-aligned crop, which is every default
20748 // gate row (class `gate-blind-to-feature`).
20749 if edge_census() {
20750 for (side, n, inside, padding) in take_edge_census() {
20751 eprintln!(
20752 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
20753 padding_sse={padding} ({:.1}% of raw)",
20754 100.0 * padding as f64 / (inside + padding).max(1) as f64,
20755 );
20756 }
20757 }
20758 // gate-blind-to-feature: what the screen tools actually did at
20759 // native resolution, over this clip's four encodes.
20760 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20761 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
20762 // Which tables the SEARCH priced against, per frame arming
20763 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
20764 // real starting ones. A film clip must show every inter arming on
20765 // the real side, a screen clip none of them.
20766 let (price_default, price_real) = crate::tile::take_pricing_hits();
20767 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
20768 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
20769 // superblocks stayed whole, and how many of those coded a
20770 // residual, split that residual's luma, or took a compound
20771 // reference (class `gate-blind-to-feature`).
20772 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
20773 // the superblocks offered the trial were coded whole.
20774 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
20775 eprintln!(
20776 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
20777 {i64_edge} on a superblock the frame edge cuts",
20778 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
20779 );
20780 eprintln!(
20781 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
20782 {} (search) / {} (writer); rect/AB pieces with a residual \
20783 {} (search) / {} (writer)",
20784 take_b128_none_hits(),
20785 crate::tile::take_sb128_none_hits(),
20786 take_b128_residual_hits(),
20787 crate::tile::take_sb128_residual_hits(),
20788 take_b128_rectres_hits(),
20789 crate::tile::take_sb128_rectres_hits(),
20790 );
20791 eprintln!(
20792 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
20793 take_b64_root_hits(),
20794 take_b64_residual_hits(),
20795 take_b64_var_tx_hits(),
20796 take_b64_compound_hits(),
20797 );
20798 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
20799 // of every priced block): what the deadzone quantiser handed the
20800 // RDOQ pass and what the pass changed, over every TRIAL block of
20801 // this row's four encodes -- not over the coded stream, so it is
20802 // the bits AT STAKE in the search, not in the bitstream.
20803 let rq = crate::tile::take_rdoq_stats();
20804 if rq[0] > 0 {
20805 eprintln!(
20806 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
20807 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
20808 rq[0],
20809 rq[1],
20810 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
20811 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
20812 rq[4],
20813 rq[5],
20814 rq[7] as f64 / 64.0,
20815 rq[6] as f64 / 64.0,
20816 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
20817 );
20818 }
20819 // lane-av1obmc2: the same motion_mode census the 640x384 gate
20820 // prints (class `gate-blind-to-feature`) -- how many blocks coded
20821 // the symbol at each footprint and how many took OBMC. Without it
20822 // the native table, which is the standing keep table, could not
20823 // say whether the tool fired at all.
20824 let mm = crate::tile::take_motion_mode_hits();
20825 eprintln!(
20826 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
20827 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
20828 eligible)",
20829 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
20830 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20831 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20832 mm.iter().sum::<usize>(),
20833 );
20834 print_inter_tx_census(name);
20835 // lane-last2 (class `gate-blind-to-feature`): which reference the
20836 // 32x32-and-below inter blocks of this clip's four encodes chose.
20837 // The native table is the standing keep table, so a second past
20838 // reference that never won a block has to be visible HERE and not
20839 // only in a synthetic witness.
20840 let rh = crate::encode::take_ref_frame_hits();
20841 let rtot: usize = rh.iter().sum();
20842 eprintln!(
20843 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
20844 (LAST2 {:.1}%)",
20845 rh[1], rh[2], rh[4], rh[7], rtot,
20846 100.0 * rh[2] as f64 / rtot.max(1) as f64,
20847 );
20848 let palette = crate::tile::take_palette_hits();
20849 let palette_uv = crate::tile::take_palette_uv_hits();
20850 let ibc = crate::tile::take_intrabc_hits();
20851 let search = take_intrabc_search();
20852 eprintln!(
20853 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
20854 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
20855 won {})",
20856 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
20857 palette[0],
20858 palette_uv[0],
20859 ibc[0],
20860 search[0],
20861 search[1],
20862 search[2],
20863 );
20864 // gate-blind-to-feature: how often the five recursive filter-intra
20865 // modes actually won a block over this clip's four encodes -- a
20866 // tool that never fires is not measured by the row above it.
20867 let fi = crate::tile::take_filter_intra_hits();
20868 eprintln!(
20869 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
20870 filter_intra_on(),
20871 fi[0],
20872 fi[1],
20873 fi[2],
20874 fi[3],
20875 fi[4],
20876 fi[5],
20877 );
20878 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
20879 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
20880 assert_monotone(&format!("{name}: ours"), &ours);
20881 assert_monotone(&format!("{name}: libaom"), &aom);
20882 assert_monotone(&format!("{name}: rav1e"), &rav1e);
20883 let points = ours
20884 .iter()
20885 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20886 .collect::<Vec<_>>()
20887 .join(", ");
20888 println!(
20889 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
20890 bd_rate(&aom, &ours) * 100.0,
20891 bd_rate(&rav1e, &ours) * 100.0,
20892 );
20893 // lane-pareto2: the two references at THEIR fast presets, plus
20894 // SVT-AV1, measured in the SAME arm as the row above -- the only
20895 // way the wall column of a Pareto table means anything (class:
20896 // wall tables are comparable only inside one interleaved batch).
20897 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
20898 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
20899 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
20900 [50, 100, 150, 200]
20901 .iter()
20902 .map(|q| {
20903 vec![
20904 "-rav1e-params".to_string(),
20905 format!(
20906 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
20907 ),
20908 ]
20909 })
20910 .collect()
20911 };
20912 let aom_at = |cu: u32| -> Vec<Vec<String>> {
20913 [5, 20, 35, 45]
20914 .iter()
20915 .map(|q| {
20916 vec![
20917 "-cpu-used".to_string(),
20918 cu.to_string(),
20919 "-b:v".to_string(),
20920 "0".to_string(),
20921 "-crf".to_string(),
20922 q.to_string(),
20923 ]
20924 })
20925 .collect()
20926 };
20927 let svt_at = |pr: u32| -> Vec<Vec<String>> {
20928 [20, 35, 45, 55]
20929 .iter()
20930 .map(|q| {
20931 vec![
20932 "-preset".to_string(),
20933 pr.to_string(),
20934 "-crf".to_string(),
20935 q.to_string(),
20936 "-svtav1-params".to_string(),
20937 "lp=1".to_string(),
20938 ]
20939 })
20940 .collect()
20941 };
20942 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
20943 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
20944 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
20945 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
20946 ];
20947 if have_encoder("libsvtav1") {
20948 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
20949 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
20950 } else {
20951 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
20952 }
20953 for (label, encoder, points) in arms {
20954 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
20955 // A REFERENCE stream our decoder cannot read is a note in
20956 // this table, not a gate failure: these rows exist to
20957 // price the references, and `assert_ladder_decodes` keeps
20958 // its teeth for the two ladders the keep table is read off.
20959 let notes =
20960 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
20961 if !notes.is_empty() {
20962 eprintln!("{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)", notes.len());
20963 }
20964 assert_monotone(&format!("{name}: {label}"), &lad);
20965 println!(
20966 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
20967 bd_rate(&aom, &lad) * 100.0,
20968 bd_rate(&rav1e, &lad) * 100.0,
20969 );
20970 }
20971 }
20972 }
20973 assert_ladder_decodes();
20974 }
20975
20976 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
20977 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
20978 /// on the two film clips at their native gate crop. The 2160p clip loses
20979 /// at every arm of the propagating map and the named suspect was that its
20980 /// heavily filtered flat cells give a tiny denominator, so the dependence
20981 /// ratio explodes exactly where coding is cheap; this prints the numbers
20982 /// that confirm or refute it.
20983 #[test]
20984 #[ignore = "needs ffmpeg and the film fixtures"]
20985 fn tpl_intra_denominator_histogram() {
20986 let _knobs = crate::speed::knob_read();
20987 if !have_ffmpeg() {
20988 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
20989 return;
20990 }
20991 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
20992 for (label, file) in [
20993 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
20994 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
20995 ] {
20996 let path = fixtures.join("video").join(file);
20997 if !path.exists() {
20998 eprintln!("SKIP {label}: {file} missing");
20999 continue;
21000 }
21001 let path = path.to_str().unwrap();
21002 let Some((nw, nh)) = probe_dims(path) else {
21003 eprintln!("SKIP {label}: ffprobe gave no size");
21004 continue;
21005 };
21006 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
21007 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21008 let source =
21009 clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
21010 let mut costs: Vec<f64> = Vec::new();
21011 for pic in &source {
21012 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
21013 costs.extend(
21014 super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)),
21015 );
21016 }
21017 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
21018 let mut sorted = costs.clone();
21019 sorted.sort_by(f64::total_cmp);
21020 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
21021 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
21022 eprintln!(
21023 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
21024 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
21025 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
21026 below 1.0x {} ({:.1}%)",
21027 costs.len(),
21028 q(0.0),
21029 q(0.01),
21030 q(0.05),
21031 q(0.25),
21032 q(0.50),
21033 q(0.75),
21034 q(0.99),
21035 q(1.0),
21036 below(0.25),
21037 100.0 * below(0.25) as f64 / costs.len() as f64,
21038 below(0.5),
21039 100.0 * below(0.5) as f64 / costs.len() as f64,
21040 below(1.0),
21041 100.0 * below(1.0) as f64 / costs.len() as f64,
21042 );
21043 }
21044 }
21045
21046 /// The probe arms the gate's source (lane-probe, class `instrument
21047 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
21048 /// command line and had no `-ss`, so it read film B from frame 0 -- a
21049 /// black leader -- and coded 59 kB where the gate's own ladder point
21050 /// coded 89 kB of the same title; every census taken through it was
21051 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
21052 /// the shared loader honours the seek (arming the probe's way and the
21053 /// gate's way gives byte-identical streams, and dropping the seek does
21054 /// not), on a synthetic clip whose content moves over time.
21055 #[test]
21056 fn the_probe_arms_the_gates_source() {
21057 let _knobs = crate::speed::knob_write();
21058 if !have_ffmpeg() {
21059 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
21060 return;
21061 }
21062 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
21063 std::fs::create_dir_all(&dir).unwrap();
21064 let clip = dir.join("testsrc2.y4m");
21065 // 384x202: neither side is a multiple of 128, so the gate's centre
21066 // window is a real derivation and not the frame itself -- exactly the
21067 // shape film B has (3840x1608, never 3840x2160).
21068 let ok = Command::new("ffmpeg")
21069 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"])
21070 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
21071 .arg(&clip)
21072 .status()
21073 .expect("ffmpeg failed to run")
21074 .success();
21075 assert!(ok, "ffmpeg could not write the synthetic clip");
21076 let path = clip.to_str().unwrap();
21077
21078 // The window: superblock-aligned, centred, even offsets.
21079 let (vf, w, h) = crate::probe::gate_crop(path);
21080 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
21081
21082 let (seek, q) = ("00:00:01", 150u8);
21083 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
21084 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
21085 assert!(
21086 gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
21087 "the probe's source differs from the gate's at the same window"
21088 );
21089 let bytes = |src: &[Picture]| {
21090 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
21091 .unwrap()
21092 .stream
21093 };
21094 assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes");
21095 // The two witnesses that both halves of the arming reach ffmpeg: the
21096 // seek, and the crop's own offset (the film-B defect in miniature --
21097 // the probe was reading `crop=..:568` of a 1608-high frame).
21098 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
21099 assert_ne!(
21100 bytes(&gate),
21101 bytes(&unseeked),
21102 "seeked and unseeked arming coded the same bytes -- the seek is inert"
21103 );
21104 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
21105 assert_ne!(
21106 bytes(&gate),
21107 bytes(&offset),
21108 "centred and top-aligned windows coded the same bytes -- the crop is inert"
21109 );
21110 std::fs::remove_dir_all(&dir).ok();
21111 }
21112
21113 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
21114 /// point inside the test binary, to compare against `examples/enc_probe`.
21115 #[test]
21116 #[ignore = "diagnostic: needs ffmpeg and a clip"]
21117 fn probe_parity_point() {
21118 let _knobs = crate::speed::knob_write();
21119 let g = |k: &str| std::env::var(k).unwrap();
21120 let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap();
21121 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
21122 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
21123 let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames);
21124 let fctx = &crate::decode::FrameCtx::for_encoder();
21125 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
21126 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
21127 for &b in &e.stream {
21128 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
21129 }
21130 eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
21131 e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid());
21132 }
21133 /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The
21134 /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`):
21135 /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in
21136 /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32
21137 /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags
21138 /// the census's far row measures were already banked by `arf_altref`.
21139 /// This census stays the PRICING arm (class `gate-blind-to-feature`): its
21140 /// best-of-two SAD shares are read against the fire share the gate census
21141 /// prints (`references ... LAST2 n (n%)`) and the refutation in
21142 /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the
21143 /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off
21144 /// `LAST`, the backward `ALTREF`, and the rate term price in.
21145 ///
21146 /// The measurement is on the gate's own window and loader (`gate_crop`,
21147 /// 12 pictures) of the two real films: every 16x16 luma block of every
21148 /// picture gets one full-pel diamond search against the NEAR reference
21149 /// and the same search against the FAR one, at the two lags the pyramid
21150 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
21151 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
21152 /// reference wins at all and by more than 10%, and -- the number the
21153 /// decision is taken on -- the total SAD of best-of-{near, far} against
21154 /// the total SAD of near alone, which is the prediction energy a second
21155 /// reference could remove before any rate is paid for naming it.
21156 ///
21157 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
21158 #[test]
21159 #[ignore = "reads the real films"]
21160 fn last2_census() {
21161 if !have_ffmpeg() {
21162 eprintln!("SKIP last2_census: no ffmpeg");
21163 return;
21164 }
21165 const SIDE: usize = 16;
21166 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
21167 // `None` when the displaced block leaves the picture.
21168 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
21169 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
21170 if sy < 0 || sx < 0 {
21171 return None;
21172 }
21173 let (sy, sx) = (sy as usize, sx as usize);
21174 if sy + SIDE > r.height || sx + SIDE > r.width {
21175 return None;
21176 }
21177 let mut acc = 0u64;
21178 for row in 0..SIDE {
21179 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
21180 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
21181 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
21182 }
21183 Some(acc)
21184 };
21185 // A log-step diamond from the zero motion vector: the cheapest search
21186 // that still finds real pans. Both references get exactly this one,
21187 // so the comparison is search-fair.
21188 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
21189 let mut best = (sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX), (0isize, 0isize));
21190 let mut step = 16isize;
21191 while step >= 1 {
21192 let centre = best.1;
21193 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
21194 let mv = (centre.0 + dy * step, centre.1 + dx * step);
21195 if let Some(s) = sad(cur, r, bx, by, mv) {
21196 if s < best.0 {
21197 best = (s, mv);
21198 }
21199 }
21200 }
21201 step /= 2;
21202 }
21203 best.0
21204 };
21205 println!("| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |");
21206 println!("|---|---|---|---|---|---|---|---|");
21207 for (name, path, seek) in native_gate_clips() {
21208 if !name.starts_with("film ") {
21209 continue;
21210 }
21211 let (vf, cw, ch) = crate::probe::gate_crop(&path);
21212 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
21213 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
21214 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
21215 let (mut near_sad, mut best_sad) = (0u64, 0u64);
21216 for i in far..pictures.len() {
21217 let cur = &pictures[i];
21218 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
21219 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
21220 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
21221 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
21222 blocks += 1;
21223 wins += u64::from(f < n);
21224 big += u64::from(f as f64 * 1.1 < n as f64);
21225 near_sad += n;
21226 best_sad += n.min(f);
21227 }
21228 }
21229 }
21230 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
21231 println!(
21232 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
21233 pct(wins),
21234 pct(big),
21235 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
21236 );
21237 }
21238 }
21239 }
21240
21241 /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
21242 /// temporal filter of its SOURCE would take off it, priced before any
21243 /// encoder change (class `gate-blind-to-feature`).
21244 ///
21245 /// The stream census says our top ARF costs 6992 B a frame against
21246 /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
21247 /// quality, and that 61% of the gap is residual, not syntax. Two
21248 /// explanations are separable here without an encoder: our anchor
21249 /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
21250 /// the residual it codes at that lag is dominated by film grain, which no
21251 /// motion search can predict (source noise). So, per ARF position of the
21252 /// gate's own 48-picture window:
21253 ///
21254 /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
21255 /// * the same at lag 8 with the CURRENT picture temporally filtered --
21256 /// a libaom-shaped motion-compensated average of the +-2 display
21257 /// neighbours, weights `exp(-mse / strength)` -- which is the residual
21258 /// energy an ARF temporal filter would remove, and
21259 /// * PSNR of that filtered picture against the unfiltered one, the
21260 /// CEILING the filtered ARF's own PSNR is then measured under (the
21261 /// BD gate scores against the unfiltered source).
21262 ///
21263 /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
21264 /// --ignored arf_pred_census --nocapture
21265 #[test]
21266 #[ignore = "reads the real films"]
21267 fn arf_pred_census() {
21268 if !have_ffmpeg() {
21269 eprintln!("SKIP arf_pred_census: no ffmpeg");
21270 return;
21271 }
21272 const SIDE: usize = 16;
21273 let strength: f64 = std::env::var("EC_ARF_TF_S")
21274 .ok()
21275 .and_then(|v| v.parse().ok())
21276 .unwrap_or(30.0);
21277 let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
21278 // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
21279 // when the displaced block leaves the picture.
21280 let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
21281 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
21282 if sy < 0 || sx < 0 {
21283 return None;
21284 }
21285 let (sy, sx) = (sy as usize, sx as usize);
21286 if sy + SIDE > r.height || sx + SIDE > r.width {
21287 return None;
21288 }
21289 let mut acc = 0u64;
21290 for row in 0..SIDE {
21291 let c = &cur[row * cw..][..SIDE];
21292 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
21293 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
21294 }
21295 Some((acc, (sy, sx)))
21296 };
21297 // The same log-step diamond `last2_census` uses, so the two censuses'
21298 // SADs are comparable.
21299 let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
21300 let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
21301 Some(v) => v,
21302 None => return (u64::MAX, (by, bx)),
21303 };
21304 let mut centre = (0isize, 0isize);
21305 let mut step = 16isize;
21306 while step >= 1 {
21307 let from = centre;
21308 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
21309 let mv = (from.0 + dy * step, from.1 + dx * step);
21310 if let Some(s) = at(cur, cw, r, bx, by, mv) {
21311 if s.0 < best.0 {
21312 best = s;
21313 centre = mv;
21314 }
21315 }
21316 }
21317 step /= 2;
21318 }
21319 best
21320 };
21321 println!(
21322 "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
21323 );
21324 println!("|---|---|---|---|---|---|---|");
21325 for (name, path, seek) in native_gate_clips() {
21326 if !name.starts_with("film ") {
21327 continue;
21328 }
21329 let (vf, cw, ch) = crate::probe::gate_crop(&path);
21330 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
21331 let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
21332 let (mut tf_sse, mut tf_px) = (0f64, 0u64);
21333 for i in (8..pictures.len()).step_by(8) {
21334 arfs += 1;
21335 let cur = &pictures[i];
21336 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
21337 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
21338 let block: Vec<u16> = (0..SIDE)
21339 .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
21340 .collect();
21341 n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
21342 n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
21343 // The temporal filter: each +-2 display neighbour is
21344 // motion-compensated onto this block and averaged in
21345 // with libaom's shape, a weight that falls with the
21346 // match's own mean squared error.
21347 let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
21348 let mut wsum = 1.0f64;
21349 // `EC_ARF_TF_PAST=1` restricts the filter to the
21350 // DISPLAY-PAST neighbours -- the only ones the
21351 // encoder's own group buffer holds when it codes its
21352 // top ARF (the group's future is not buffered yet).
21353 let offs: &[isize] = match past {
21354 true => &[-2, -1],
21355 false => &[-2, -1, 1, 2],
21356 };
21357 for &d in offs {
21358 let j = i as isize + d;
21359 let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
21360 else {
21361 continue;
21362 };
21363 let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
21364 let mut sse = 0f64;
21365 for row in 0..SIDE {
21366 for col in 0..SIDE {
21367 let d = f64::from(block[row * SIDE + col])
21368 - f64::from(nb.y[(sy + row) * nb.width + sx + col]);
21369 sse += d * d;
21370 }
21371 }
21372 let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp();
21373 for row in 0..SIDE {
21374 for col in 0..SIDE {
21375 acc[row * SIDE + col] +=
21376 w * f64::from(nb.y[(sy + row) * nb.width + sx + col]);
21377 }
21378 }
21379 wsum += w;
21380 }
21381 let filtered: Vec<u16> = acc
21382 .iter()
21383 .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16)
21384 .collect();
21385 for (a, b) in filtered.iter().zip(&block) {
21386 let d = f64::from(*a) - f64::from(*b);
21387 tf_sse += d * d;
21388 }
21389 tf_px += (SIDE * SIDE) as u64;
21390 ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0;
21391 px += (SIDE * SIDE) as u64;
21392 }
21393 }
21394 }
21395 let per = |v: u64| v as f64 / px.max(1) as f64;
21396 let mse = tf_sse / tf_px.max(1) as f64;
21397 println!(
21398 "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |",
21399 per(n8),
21400 per(n4),
21401 per(ntf),
21402 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64,
21403 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(),
21404 );
21405 }
21406 }
21407
21408 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
21409 /// hardwire the REGULAR kernel, so the encoder could not have coded a
21410 /// SMOOTH or SHARP frame even if the header had said so -- the search,
21411 /// the trials, the recon and the frame header now all read
21412 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
21413 /// distinct stream (a filter that never reached the prediction would code
21414 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
21415 /// reconstructs every frame of each of them exactly, which is what proves
21416 /// the header and the prediction agree.
21417 #[test]
21418 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
21419 let _knobs = crate::speed::knob_write();
21420 if !have_ffmpeg() {
21421 eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg");
21422 return;
21423 }
21424 let (width, height) = (256usize, 128usize);
21425 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
21426 // all three kernels would code the same bytes and the test would pass
21427 // on a wiring that does nothing (class `fixture proves the symbol, not
21428 // the signal`). `panned_test_card` shifts by whole pixels, so the
21429 // search finds the sub-pel positions off the reconstruction instead:
21430 // three frames of a slow diagonal pan.
21431 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
21432 let mut streams = Vec::new();
21433 for filter in [
21434 ec_av1_syntax::InterpolationFilter::Eighttap,
21435 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
21436 ec_av1_syntax::InterpolationFilter::EighttapSharp,
21437 ] {
21438 set_frame_interp(Some(filter));
21439 let fctx = &crate::decode::FrameCtx::for_encoder();
21440 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
21441 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
21442 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
21443 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
21444 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
21445 assert_eq!(decoded.y, frame.reconstruction.y, "{filter:?} frame {i}: luma");
21446 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
21447 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
21448 }
21449 streams.push((filter, encoded.stream));
21450 }
21451 set_frame_interp(None);
21452 for (i, (fa, a)) in streams.iter().enumerate() {
21453 for (fb, b) in &streams[i + 1..] {
21454 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
21455 }
21456 }
21457 }
21458
21459
21460 /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
21461 /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
21462 /// residual outright (`round_to_valid_mv` rounds it away first), so the
21463 /// finest vector the encoder could commit to was a quarter pel. With the
21464 /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
21465 /// non-zero component and the search's fourth stage refines to the
21466 /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
21467 /// on arm, and -- the part that makes it a signal rather than a symbol
21468 /// count (class `fixture proves the symbol, not the signal`) -- that some
21469 /// of them come out ZERO, i.e. name a vector the off arm cannot code at
21470 /// all. Both streams are decoded by ffmpeg AND by this crate's own
21471 /// decoder and asserted sample-exact against the encoder's own
21472 /// reconstruction, which is what proves the header bit and the symbols
21473 /// agree.
21474 #[test]
21475 fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
21476 let _knobs = crate::speed::knob_write();
21477 if !have_ffmpeg() {
21478 eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg");
21479 return;
21480 }
21481 let (width, height) = (256usize, 128usize);
21482 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
21483 let mut arms = Vec::new();
21484 for hp in [false, true] {
21485 set_high_precision_mv(Some(hp));
21486 let _ = crate::tile::take_hp_symbols();
21487 let fctx = &crate::decode::FrameCtx::for_encoder();
21488 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
21489 .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
21490 let (symbols, eighth) = crate::tile::take_hp_symbols();
21491 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
21492 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
21493 assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
21494 assert_eq!(ours.len(), pictures.len(), "hp={hp}: our decoder frame count");
21495 for (i, e) in encoded.frames.iter().enumerate() {
21496 for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
21497 if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction)
21498 {
21499 panic!(
21500 "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
21501 the encoder reconstructed {want}"
21502 );
21503 }
21504 }
21505 }
21506 arms.push((symbols, eighth, encoded.stream));
21507 }
21508 set_high_precision_mv(None);
21509 let (off, on) = (&arms[0], &arms[1]);
21510 assert_eq!(off.0, 0, "a frame without the header bit codes no hp symbol");
21511 assert!(on.0 > 0, "a high-precision frame codes hp symbols (got {})", on.0);
21512 assert!(
21513 on.1 > 0,
21514 "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
21515 on.0
21516 );
21517 assert_ne!(off.2, on.2, "the two arms coded the same bytes");
21518 println!(
21519 "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
21520 off.0,
21521 off.2.len(),
21522 on.0,
21523 on.1,
21524 on.2.len()
21525 );
21526 }
21527}